text
stringlengths
15
59.8k
meta
dict
Q: EJB + Hibernate + REST client LazyInitializationException My REST client was working until I added Hibernate for the persistence then whenever I make a request I obtain an Error 500 with this message: Failed to lazily initialize a collection of role: uo.sdi.dto.User.tasks, could not initialize proxy - no Session. I've been reading lots of answers about this topic but none of them happen on this scenario. The error raises when I call the "FindLoggableUser" method in order to check whether a user can be logged on or not. FindLoggableUser User user = Factories.persistence.getUserDao().findByLoginAndPassword(login, password); FindByLoginAndPassword User res = Jpa.getManager() .createQuery(Jdbc.getSqlQuery("USER_FIND_BY_LOGIN_AND_PASSWORD") ,User.class).setParameter(1, login).setParameter(2, password) .getSingleResult(); return res; Jpa.java public class Jpa { private static ThreadLocal<EntityManager> emThread = new ThreadLocal<EntityManager>(); public static EntityManager getManager() { EntityManager entityManager = emThread.get(); if (entityManager == null) { entityManager = jndiFind("java:/GtdJpaEntityManager"); emThread.set(entityManager); } return entityManager; } private static EntityManager jndiFind(String name) { Context ctx; try { ctx = new InitialContext(); return (EntityManager) ctx.lookup(name); } catch (NamingException e) { throw new RuntimeException(e); } } } And my user class User.java @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(unique = true, nullable = false) private String login; @Column(unique = true, nullable = false) private String email; private String password; private Boolean isAdmin = false; @Enumerated(EnumType.STRING) private UserStatus status = UserStatus.ENABLED; @OneToMany(mappedBy="user") private Set<Task> tasks = new HashSet<Task>(); @OneToMany(mappedBy="user") private Set<Category> categories = new HashSet<Category>(); These are the attributes of my class and the error raises when tryin to access the tasks collection: public Set<Task> getTasks(){ return new HashSet<Task>(tasks); } I've tried setting the initialization as eager but it also fails. Regarding other questions, some people recommended to control the session manually in order to get an approach to the session per request pattern, but I've also read that it is not possible to control the session when using an EntityManager. Do you have any solution for this problem? Thanks in advance. A: You must configure lazy for collections In your case is for tasks.
{ "language": "en", "url": "https://stackoverflow.com/questions/43705288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get total count of Records including line item in Netsuite var columns = []; var filters= []; filters.push(new nlobjSearchFilter('mainline', null, 'is', 'false')); columns.push(new nlobjSearchColumn('internalid', null, 'COUNT')); var results = nlapiSearchRecord('salesorder', null, filters, columns); When we use this we only get count of total grouped sales order. I want count when mainline is false. Is there any faster way to get all the count including line items. By this i mean to say count of all repeted sales order for different line items. A: function countTotalRecords(type){ var count =0; var i=0; var j=1000; var columns = []; var filters= []; columns.push(new nlobjSearchColumn('internalid')); var search = nlapiCreateSearch(type,filters,columns); var resultSet = search.runSearch(); do{ var result =resultSet.getResults(i,j); count += result.length; i=j; j=j+1000; }while(result.length == 1000); return count; } I found a way to count the total Records including line items. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/48658272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AngularJS add variable to scope problems I am working on a more complex project(10000+ LoC) and during development I encountered a problem very often. When I add a simple variable to scope like: $scope.editing = true; $sope.editing=false; $scope.changeTextButtonClicked = function() { $scope.editText; } <span ng-hide="editing">{{editText}}</span> <input type="text" ng-model="editText" ng-show="editing"> <input type ="button" ng-click="changeTextButtonClicked()"> The current value of $scope.editText can't be accessed from the controllers javascript code! In some cases I got the old value when accessing $scope.editText like the DOM is not updated but when printing it directly on the website with {{editText}} it works and gets updated but in the controller I get the old value. It happened that I have one value for {{editText}} on the website and another value for $scope.editText in the controller (invalid one - previous). I solved this with adding it to a data array or any other array that is nested inside the scope: $scope.data={} $scope.data.editText = ...; Can anybody explain to me why it works sometimes with $scope.variable and sometime it doesn't and you need to add $scope.**foobar**.variable? A: I had the same problem time ago then i read this tutorial about scopes. https://github.com/angular/angular.js/wiki/Understanding-Scopes Anyway the main concept is that when you use ng-model always use a dot notation. so $scope.user={} and then $scope.user.name. Hope it helps. A: Ok i got it finally. The problem is that the $watch can be only bound to an object and observe it and not to a elementary field like string, int . boolean & co. The bad thing is when you have a object complex structure you cant only bind it to a property but rather to the whole object that causes performance issues if its a multilevel object.
{ "language": "en", "url": "https://stackoverflow.com/questions/27145493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using Blocks and GCD to manage tasks I'm learning iOS and when it comes to GCD, it's confusing. Let's get it out of the way, I'm writing a small program that fetch data from the internet. Here is my viewcontroller NSMutableArray dataArray = [NSMutableArray array]; [querysomethingwithblock:(^ { //do some stuff here [otherquerywithblock:( ^ { //do some stuff here // Here I got the data from internet // Do loop action [dataArray addObject:data]; })]; })]; // here I want to perform some actions only after get data from internet [self performAction:dataArray]; How can I achieve this purpose. In practical, [self performAction:dataArray] always get fired before I get the data. I tried to play with GCD but no luck. Here is some patterns I've tried so far dispatch_async(queue, ^{ // Do query stuff here dispatch_async(dispatch_get_mainqueue(), ^{ //perform action here }); {; Or using dispatch_group_async, dispatch_group_wait, dispatch_group_notify The only way I can handle right now is to use dispatch_after but the point is the downloading time is variable, it's not good practice to have a specific time here Thank you so much for any advice. A: The part of code called Do query stuff here i assume is async already, why put it inside a dispatch_queue then? If instead you manage to do a synchronous query, your code (the second snippet) would work, as the dispatch to the main queue would be executed only after the query finished. If you don't have an option to execute the query in a synchronous manner, then you need some mechanism to register either a block or a callback to be executed when the download is finished. At the end of the day, it all depends on what kind of query you have in there and what methods it offers for you to register an action to be performed when the download is finished.
{ "language": "en", "url": "https://stackoverflow.com/questions/18899423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can i get xml file as a response from jsp BufferedHttpServletResponse bufferedHttpServletResponse = new BufferedHttpServletResponse(response); request.getRequestDispatcher(jspPage).forward(request, bufferedHttpServletResponse); String xmlData = bufferedHttpServletResponse.getData(); This is what i am using along with modelAndView my anyChart component require data in XML file,this file should be generated dynamically but it says response is already committed. A: You could use a Servlet and directly print out the answer: public void service(ServletRequest request, ServletResponse response){ response.setContentType("text/xml;charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); writer.append("<result>"); // print your result writer.append("</result>"); It's not from within a JSP, but it almost looks like you are already inside a Servlet. If you are using Spring Web MVC, what your referral to modelAndView suggests, you might just want to use a method in your controller with @ResponseBodyannotation on the return type. @RequestMapping(value = "/xmlresponse", method = RequestMethod.GET) public @ResponseBody ResultObjectWithJaxbAnnotations gernerateXmlResult() { Don't forget <mvc:annotation-driven /> in your Spring application-context - but you will have that most likely already.
{ "language": "en", "url": "https://stackoverflow.com/questions/27104045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Proper deletion of bad character strings in classic ASP I performed a OWASP-ZAP security test on my classic asp application. It came back with a Format String Vulnerability. The report says it used ZAP%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s as the attack for some form input field parameters (e.g. username). The report suggests to Rewrite the background program using proper deletion of bad character strings. What does this actually mean in my case? Is it in this case enough to replace special characters when using request() - e.g. replace % in request(username)? Or do I have to delete the bad characters on the client side? Reference: https://www.owasp.org/index.php/Format_string_attack A: It might be a false-positive. I would need to see more of your code and the input that was provided to it that triggered the warning from ZAP. Taking any security-related action on the client side can never be trusted because client-side validation can be circumvented with minimal know-how. You're left with performing sanitization on the server-side where the functions/subs doing the sanitization cannot be augmented.
{ "language": "en", "url": "https://stackoverflow.com/questions/42582517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Send data to Arduino via Express without request I have an Express server running and Arduinos currently make POST requests to it. The server then does some other processing. I'm trying to make Express to send an event (data) to the Arduino and then have the Arduino generate an interrupt when it receives the data. However, I'd like Express to send data to the Arduino without the Arduino sending an HTTP request to the server in the first place. I could periodically poll the server but I don't expect events to happen often and I think polling the server every second or so to see if new data is available is wasteful. const express = require("express"); const bodyParser = require("body-parser"); app.get("/", (req, res) => { return res.status(200).send({ message: "Success!" }); }); //Invalid code but lets say the Arduino was on IP 192.168.0.223 //and we wanted to push data to it app.sendData("192.168.0.233", {temperature: 20.0}); To clarify, above is part of my code. If I make a request from the Arduino to Express route '/' then I can send a response with data from the server to the Arduino. However, if the Arduino never made a request in the first place, how can I send (or push) data to it? #include <SPI.h> #include <Ethernet.h> byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192, 168, 1, 177); EthernetServer server(80); void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.println("Ethernet WebServer Example"); // start the Ethernet connection and the server: Ethernet.begin(mac, ip); // Check for Ethernet hardware present if (Ethernet.hardwareStatus() == EthernetNoHardware) { Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); while (true) { delay(1); // do nothing, no point running without Ethernet hardware } } if (Ethernet.linkStatus() == LinkOFF) { Serial.println("Ethernet cable is not connected."); } // start the server server.begin(); Serial.print("server is at "); Serial.println(Ethernet.localIP()); } void loop() { // listen for incoming clients EthernetClient client = server.available(); if (client) { Serial.println("new client"); // an http request ends with a blank line boolean currentLineIsBlank = true; while (client.connected()) { <-- this is blocking code if (client.available()) { char c = client.read(); Serial.write(c); if (c == '\n' && currentLineIsBlank) { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); // the connection will be closed after completion of the response client.println("Refresh: 5"); // refresh the page automatically every 5 sec client.println(); client.println("<!DOCTYPE HTML>"); client.println("<html>"); // output the value of each analog input pin for (int analogChannel = 0; analogChannel < 6; analogChannel++) { int sensorReading = analogRead(analogChannel); client.print("analog input "); client.print(analogChannel); client.print(" is "); client.print(sensorReading); client.println("<br />"); } client.println("</html>"); break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disconnected"); } } The above snippet sets up a server on the Arduino but it still has to actively listen for connections and then check to see if the client is connected and then read in the data. If this is the way it has to be done then I'll rethink my approach. I wanted the server to simply send data to an IP and the Arduino will generate an interrupt that I can service. Sort of how UART works? There's no initial request data just comes along and generates an interrupt that you can handle. A: Thanks to @jfriend00 for pointing me in the direction of websockets and this article for general guidance I decided to use ws for the server: const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 3005 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { console.log('received: %s', message); }); setInterval(() => { ws.send(`${new Date()}`); }, 1000); }); And on the Arduino the ATmega branch of the WebSockets library #define MONITOR_SPEED 921600 #include <SPI.h> #include <Ethernet.h> #include <WebSocketsClient.h> WebSocketsClient webSocket; //MAC address for arduino- these can be manually assigned //but cannot conflict with any other address on the same network byte mac[] = {0xAE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; // Set the static IP address to use if the DHCP fails to assign static IPAddress ip(192, 168, 0, 177); static IPAddress myDns(192, 168, 0, 1); static EthernetClient client; void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) { switch(type) { case WStype_DISCONNECTED: Serial.println("[WSc] Disconnected!\n"); break; case WStype_CONNECTED: { Serial.print("[WSc] Connected to url: "); Serial.println((char *)payload); // send message to server when Connected webSocket.sendTXT("Connected"); } break; case WStype_TEXT: Serial.print("[WSc] get text: "); Serial.println((char *)payload); // send message to server // webSocket.sendTXT("message here"); break; case WStype_BIN: Serial.print("[WSc] get binary length: "); Serial.println(length); // hexdump(payload, length); // send data to server // webSocket.sendBIN(payload, length); break; } } void setup() { // Open serial communications and wait for port to open: Serial.begin(MONITOR_SPEED); //921600 while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } // start the Ethernet connection: Serial.println("Initialize Ethernet with DHCP:"); if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // Check for Ethernet hardware present if (Ethernet.hardwareStatus() == EthernetNoHardware) { Serial.println("Ethernet shield was not found."); Serial.println("Program will continue to run without shield but will not report to web server"); } if (Ethernet.linkStatus() == LinkOFF) { Serial.println("Ethernet cable is not connected."); } // try to congifure using IP address instead of DHCP: Ethernet.begin(mac, ip, myDns); } byte macBuffer[6]; // create a buffer to hold the MAC address Ethernet.MACAddress(macBuffer); // fill the buffer Serial.print(" MAC address : "); for (byte octet = 0; octet < 6; octet++) { Serial.print(macBuffer[octet], HEX); if (octet < 5) { Serial.print(':'); } } Serial.println(""); Serial.print(" DHCP assigned IP : "); Serial.println(Ethernet.localIP()); webSocket.begin("192.168.0.189", 3005); webSocket.onEvent(webSocketEvent); } void loop() { webSocket.loop(); Ethernet.maintain(); if (!client.connected()) { client.stop(); } } This should print the current date and time on your serial monitor: [WSc] get text: Fri Mar 19 2021 10:13:12 GMT-0400 (Atlantic Standard Time) [WSc] get text: Fri Mar 19 2021 10:13:13 GMT-0400 (Atlantic Standard Time) [WSc] get text: Fri Mar 19 2021 10:13:14 GMT-0400 (Atlantic Standard Time) [WSc] get text: Fri Mar 19 2021 10:13:15 GMT-0400 (Atlantic Standard Time) [WSc] get text: Fri Mar 19 2021 10:13:16 GMT-0400 (Atlantic Standard Time) And on your server: received: Connected
{ "language": "en", "url": "https://stackoverflow.com/questions/66697173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery addClass when a radio button in a group is selected I have the following code: var selectedMarkerClass = 'was-selected'; $('.group_1').change(function() { $(this).addClass(selectedMarkerClass); if ($('.' + selectedMarkerClass).length == $('.group_1').length) { $('#2').removeClass('red'); } }); Here is the HTML in question: <input class="single_text_input group_1" type="text" name="primary_referral" /> <input class="single_text_input group_1" type="text" name="secondary_referral" /> <input class="group_1" type="radio" name="referral_open" value="Yes" /> Yes <input class="group_1" type="radio" name="referral_open" value="No" /> No <span id="2" class="red">Referral Group</span> What is happening now is that both radio buttons in the group have to be changed in order for the class to be removed from the span. I would like it to work where only one of the radio buttons in the group has to be changed. A: Use the click event not change event. $('.group_1').click(function() { $(this).addClass(selectedMarkerClass); if ($('.' + selectedMarkerClass).length == $('.group_1').length) { $('#2').removeClass('red'); } }); Update: if ($('.' + selectedMarkerClass).length == $('.group_1').length) Is tripping you up. You are removing the red class only if the selected class has been added to each radio and you can only add the selected class if you click each radio. A better way would be: $('.group_1').click(function() { $('#2').removeClass('red'); }); Less code is often times better. You can't unselect a radio. So any click on the radios ensures at least one is clicked. A: Try it with click event instead. You see the change take place after the second click because change gets fired after the first radio button loses focus. A: After both radio button changed, $('.' + selectedMarkerClass).length == 2 and $('.group_1').length == 4 because you are using .group_1 class for radio buttons and as well as for input[type=text] too. need filter your radio button, use "[name=referral_open]", var selectedMarkerClass = 'was-selected'; $('.group_1').change(function () { $(this).addClass(selectedMarkerClass); if ($('.' + selectedMarkerClass).length == $('.group_1[name=referral_open]').length) { $('#2').removeClass('red'); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/12388767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using MVC 4 SimpleMembership with an existing database-first EF model I am trying to use SimpleMembership in my MVC 4 for the first time and I already have an existing database and EF5 model created based on it! I searched a lot but I cant find how I could use it in my case and also to have everything under my own model. It would be great if somebody can give me an idea how to do this. Thanks A: In your web.config in the appSettings tag, add the line <add key="enableSimpleMembership" value="true"/> SimpleMembership is built in so from here you simply need to write [InitializeSimpleMembership] above your public class AccountController: Controller When you want to force a user to log in for a certain page you write in the pages controller [Authorize] That tables will be automatically generated in your database. If you want to add more fields to these tables you will need to simply google it. Here's a link for more information http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx A: Purely as a point of reference, it might be a good idea to create a new Internet Application template of an ASP.NET MVC 4 Web Application project (i.e. via File > New Project). If you look at the AccountController, as @zms6445 says, it is decorated with an InitializeSimpleMembership attribute. You can find the implementation of this attribute in the InitializeSimpleMembershipAttribute.cs file in the Filters folder within the root directory. In here, this is the missing part of the puzzle - you need to hook up your existing database so that it is used by the SimpleMembershipProvider. This is the code you need: private class SimpleMembershipInitializer { public SimpleMembershipInitializer() { try { if (!WebSecurity.Initialized) { WebSecurity.InitializeDatabaseConnection("CONNECTION_STRING_NAME", "USER_TABLE", "USER_ID_FIELD", "USER_NAME_FIELD", autoCreateTables: true); } } catch (Exception ex) { throw new InvalidOperationException("Something is wrong", ex); } } } Some things to note: * *CONNECTION_STRING_NAME is an entry in your web.config ConnectionStrings - you CANNOT use the model connection string here - the SimpleMembershipProvider does not recognise that format! You need to specify an System.Data.SqlClient connection string, e.g. <add name="CONNECTION_STRING_NAME" connectionString="data source=SERVER;initial catalog=DATABASE;user id=USER;password=PASSWORD;" providerName="System.Data.SqlClient" /> *USER_TABLE is the table in your database to hold extra user information, such as first name, surname etc. This is linked to the autogenerated tables via the USER_ID_FIELD. *USER_ID_FIELD is usually the primary key of your Users table. It must be of type int. *USER_ID_NAME is a unique name for the user, which could be an Email address. *autoCreateTables is set to true to ensure the tables required for the SimpleMembership to work are created if they don't already exist. Of course, this code only gets fired if you hit a page via the AccountController, since this has been decorated by the attribute. You could put a breakpoint in there and see it in action. This should get you started - the Internet Application template is a pretty good template to follow if you get stuck. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/15112214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Neural Network makes same predictions for different instances with different features Out of interest, I created (or at least tried to create) an Artificial Neural Network with four layers as a classifier for the famous Iris flower data set. The target values vary from 0 to 2 as labels for the three different flowers. For simplicity´s sake, I left away biases. The problem is: Even though the mean squared error actually gets reduced and seems to converge, the network ends up classifying all instances (both train and test) equally. Every time I run it, it´s "choosing" a label between 1 and 3, never below or higher. So it seems that the gradient descent is somewhat working. Could it be due to the missing biases? Or did I missunderstand the algorithm? Or maybe the derivatives are incorrect? I learned the mathematical theory behind back propagation here: https://google-developers.appspot.com/machine-learning/crash-course/backprop-scroll/ neuralnetwork.py import numpy as np import math def sigmoid(x): return (math.e**x) / (math.e**x + 1) def sigmoid_deriv(x): return sigmoid(x) * (1 - sigmoid(x)) def ReLU(x): return x * (x > 0) def ReLU_deriv(x): if x > 0: return 1 else: return 0 def mean_square_error(output_vector, correct_vector): error = 0 for i in range(0, len(output_vector)): error += (output_vector[i][0] - correct_vector[i][0])**2 return 1/len(output_vector) * error def div_x_output(y, y_correct, nr_instances): return 2 / nr_instances * (y - y_correct) * ReLU_deriv(y) def div_x(y): return sigmoid_deriv(y) def partial_deriv_synapses_output(learning_rate, prediction, solution, nr_instances, x, i, hidden_layer_1): return learning_rate * div_x_output(prediction, solution, nr_instances) * hidden_layer_1[x][i] def partial_deriv_synapses_1(learning_rate, y, i, j, hidden_layer_0): return learning_rate * div_x(y) * hidden_layer_0[j][i] def partial_deriv_synapses_0(learning_rate, y, i, j, input_matrix): return learning_rate * div_x(y) * input_matrix[j][i] class NeuralNetwork: def __init__(self, synapses_0, synapses_1, synapses_2): self.synapses_0 = synapses_0 self.synapses_1 = synapses_1 self.synapses_2 = synapses_2 self.sigmoid = np.vectorize(sigmoid) self.ReLU = np.vectorize(ReLU) def fit(self, input_matrix, solutions, learning_rate, nr_instances): hidden_layer_0 = self.sigmoid(np.dot(input_matrix, self.synapses_0)) hidden_layer_1 = self.sigmoid(np.dot(hidden_layer_0, self.synapses_1)) output_layer = self.ReLU(np.dot(hidden_layer_1, self.synapses_2)) while mean_square_error(output_layer, solutions) > 0.7: print(mean_square_error(output_layer, solutions)) x = 0 for prediction in output_layer: # back propagate synapses 2 for i in range(0, len(self.synapses_2)): self.synapses_2[i][0] -= partial_deriv_synapses_output(learning_rate, prediction[0], solutions[x][0], nr_instances, x, i, hidden_layer_1) # back propagate synapses 1 y_deriv_vector_synapses_1 = np.array([1. for i in range(0, len(self.synapses_1[0]))]) for i in range(0, len(self.synapses_1[0])): y_deriv_vector_synapses_1[i] = div_x_output(prediction[0], solutions[x][0], nr_instances) * self.synapses_2[i][0] for i in range(0, len(self.synapses_1)): for j in range(0, len(self.synapses_1[0])): self.synapses_1[i][j] -= partial_deriv_synapses_1(learning_rate, y_deriv_vector_synapses_1[j], i, j, hidden_layer_0) # back propagate synapses 0 y_deriv_vector_synapses_0 = np.array([1. for i in range(0, len(self.synapses_0[0]))]) for i in range(0, len(self.synapses_0[0])): y_deriv_vector_synapses_0[i] = sum([div_x(y_deriv_vector_synapses_1[k]) * self.synapses_1[i][k] for k in range(0, len(self.synapses_1[0]))]) for i in range(0, len(self.synapses_0)): for j in range(0, len(self.synapses_0[0])): self.synapses_0[i][j] -= partial_deriv_synapses_0(learning_rate, y_deriv_vector_synapses_0[j], i, j, input_matrix) hidden_layer_0 = self.sigmoid(np.dot(input_matrix, self.synapses_0)) hidden_layer_1 = self.sigmoid(np.dot(hidden_layer_0, self.synapses_1)) output_layer = self.sigmoid(np.dot(hidden_layer_1, self.synapses_2)) x += 1 def predict(self, input_vector): hidden_layer_0 = self.sigmoid(np.dot(input_vector, self.synapses_0)) hidden_layer_1 = self.sigmoid(np.dot(hidden_layer_0, self.synapses_1)) output_layer = self.ReLU(np.dot(hidden_layer_1, self.synapses_2)) return output_layer[0] main.py from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split import numpy as np import random from neuralnetwork import NeuralNetwork iris = load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .2) network = NeuralNetwork(np.array([[random.random() for i in range(0, 8)] for j in range(0, 4)]), np.array([[random.random() for i in range(0, 3)] for j in range(0, 8)]), np.array([[random.random() for i in range(0, 1)] for j in range(0, 3)])) network.fit(np.array([x for x in X_train]), np.array([[y] for y in y_train]), 0.1, len(X_train)) error_count = 0 counter = 0 for x in X_train: prediction = round(network.predict(x)) print("prediction: "+ str(prediction) + ", actual: " + str(y_train[counter])) if prediction != y_train[counter]: error_count += 1 counter += 1 print("The error count is: " + str(error_count)) I appreciate all kind of help or tips! A: The issue is due to your loss function; mean squared error (MSE) is meaningful for regression problems, while here you face a classification one (3-class), hence your loss function should be Cross Entropy (also called log-loss). For multi-class classification, sigmoid is also not advisable; so, at a high-level, here are some other code modifications advisable for your problem: * *One-hot encode your 3 classes *Use softmax activation for your last layer, which should have 3 units (i.e. as many as the number of your classes)
{ "language": "en", "url": "https://stackoverflow.com/questions/54959563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Don't show side menu on drag ionic I have a calendar element on my ionic app. When user swipe left or right on it, it goes to a different month. One problem/challenge is that when I swipe to the right the side bar is showing. I did use drag-content="false" and that disabled the swipe menu function everywhere but I want it only on that calendar element. I found this Stackoverflow post with a answer but I did not understand how it worked because I can't find any difference between the content elements. In that post they also included a codepen link to an answer CODEPEN UPDATE: Here a link to the calendar plugin A: Maybe you could bind drag-content directive to a scope variable (boolean) and then change its value when mouse is over the calendar component: <ion-side-menu-content drag-content="drag"> So register the listeners for mouseover/mouseleave events on calendar: <flex-calendar on-touch="mouseoverCalendar()" on-release="mouseleaveCalendar()" drag-content="toggledrag" options="options" events="events"></flex-calendar> and insert in your controller: $scope.drag = true; $scope.mouseoverCalendar = function() { $scope.drag = false; }; $scope.mouseleaveCalendar = function() { $scope.drag = true; }; Here is an example using Flex Calendar: http://codepen.io/beaver71/pen/bEmaJZ A: Put this into the controller of your calendar-view and it will the menu as you enter the calendar and re-enable it as you leave the view: $scope.$on('$ionicView.enter', function(){ $ionicSideMenuDelegate.canDragContent(false); }); $scope.$on('$ionicView.leave', function(){ $ionicSideMenuDelegate.canDragContent(true); }); Answer from this post
{ "language": "en", "url": "https://stackoverflow.com/questions/35221871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Click the imageview that is in the listview to go to another activity There is a imageview and a textview in a listview. I want to click the imageview to go to another activity with the value of the hashmap. I uesed setOnItemClickListener is as below: lvAll.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) { testBadgeMap = (HashMap<String, Object>) parent.getItemAtPosition(position); } }); But I can't set the listener for the imageview in order I can't click the imageview. How can I click the imageview to go to another activity with the value of hashmap? A: You have to use Adapter code to handle the click within the list items. @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) con .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.yourlayout, parent, false); Button row = (Button) rowView.findViewById(R.id.btnSample); final int n = position; row.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent next = new Intent(context, NextActivity.class); startActivity(next); } }); return rowView; } A: you can use image.setOnClickListener() but i suggest to use ImageButton,it's extends from imageView ,it will Interception click event,then you can click it A: public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; RecordHolder holder = null; if (row == null) { LayoutInflater inflater = ((Activity)mcontext).getLayoutInflater(); row = inflater.inflate(R.layout.custom_layout, parent, false); holder = new RecordHolder(); holder.tv_name=(TextView) row.findViewById(R.id.tv_name); holder.btn_custom_delete=(Button) row.findViewById(R.id.btn_custom_delete); holder.btn_custom_insert=(Button) row.findViewById(R.id.btn_custom_insert); row.setTag(holder); } else { holder = (RecordHolder) row.getTag(); } holder.tv_name.setTag(position); holder.btn_custom_delete.setTag(position); holder.tv_name.setText(getItem(position)); holder.tv_name.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int pos = (Integer) view.getTag(); Intent intent = new Intent(mcontext , ActionActivity.class); // Here You can also get you position of arraylist or hashmap by pos i.e integer variable value. startActivity(intent); } }); return row; }
{ "language": "en", "url": "https://stackoverflow.com/questions/31983263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Column added to table but does not show up I'm new to Postgres. I created a database and a table, then I added columns to the table: ALTER TABLE NDQ01 ADD COLUMN Date, date To verify, I did: \d+ ndq01 and the output is: Table "public.ndq01" Column | Type | Collation | Nullable | Default | Storage | Stats target | Description --------+------+-----------+----------+---------+---------+--------------+------------- My new column name "Date" does not show up. What did I do wrong? Thanks very much. UPDATE: This is the error from Putty: dbfinance01-# alter table ndq01 add column Date date; ERROR: syntax error at or near "alter" LINE 2: alter table ndq01 add column Date date; A: Looks like the alter table did not succeed. Try removing the comma: alter table NDQ01 add column Date date; Check out \h alter table in psql for more information. To clarify based on other answers, according to the current docs, date is not a reserved word in Postgres, and can be set as a column name (tested on version 11.2): =# \d+ ndq01; Table "public.ndq01" Column | Type | Collation | Nullable | Default | Storage | Stats target | Description --------+------+-----------+----------+---------+---------+--------------+------------- date | date | | | | plain | | SQL Key Words docs
{ "language": "en", "url": "https://stackoverflow.com/questions/56264117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deploying NextJS front end and Expresss back end to Heroku Here is my directory structure * *app * *frontend *backend I don't have a package.json file in the main directory but both the frontend and backend have package.json files. The frontend is a fully functional NextJS app and the backend is an Express server handling api/data requests. I have one repository for the entire app. My goal is to push this app in its current structure to Heroku, set up whatever environment variables I need, and have Heroku deal with the build details. I have yet to find any tutorials or any SO questions that target my instance specifically. So far I just tried to push the whole repo but this is there error message I'm getting: remote: Compressing source files... done. remote: Building source: remote: remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed I'm assuming this is because there is no package.json file in the root directory to tell Heroku what to do. I don't have enough experience to know if this really is my problem or not. Unfortunately, I don't really know the direction I need to go here and I'm having a really hard time finding tutorials or any help when I search about this. I'm coming to understand the process and details a little more as I go along but I could definitely use a good explanation as to what I need to do, how I need to do it, and why I need to do it. I know I'm asking for a lot but anything helps. Thank you. A: I would suggest restructuring the project so that it has a package.json in the root folder. A simple way to make it work is by letting the Express app serve the NextJS app. I was having the same issue as you. I realized that deploying a NextJS app isn't as straight-forward as deploying a Create-React-App app. I ended up following the official recommendation of the NextJS team for deployment, which is to let Vercel serve it. It was actually incredibly easy. I managed to deploy the NextJS app in a matter of minutes. Create a Vercel account, add a new app and deploy it. The downside of this is that you will use Heroku for deploying your backend, and Vercel for deploying your frontend. But if you are using GitHub for example, Vercel will automatically re-deploy your NextJS app everytime you push to your main branch. So, in actuality you won't even have to do much in Vercel after deploying it the first time. There are probably other ways and workarounds, but according to Vercel (who by the way are the creators of NextJS), deploying it with Vercel is the easiest way.
{ "language": "en", "url": "https://stackoverflow.com/questions/64795433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Out of a set of data returned grouped by months, only the initial month is returning incorrect data I am trying to return data for the last 24 months as of the end of last month. Only the initial month returns incorrect data, while all the other months are correct. I believe the issue is in the strBeginDate = section of the code. Any ideas what would be causing partially returned data for the initial month? Thank you very much. Sub GetStaticApprovalRates_Slide6() Dim strBeginDate Dim strEndDate strEndDate = Sheets("Instructions").Range("EndDate").Value strBeginDate = DateAdd("m", -23, strEndDate) + 1 Sheets("Slide6Data").Select A: It's hard to say exactly what's wrong based only on what you posted. But I do see that you are calculating the start date based on the end date, by only subtracting months. There is no allowance for days. So you might be missing some of that first month by not allowing for the early days of that first month. That is , if end date occurs mid-month, I think your algorithm would cause start date to be mid-month also. Perhaps missing days 1-x of that first month.
{ "language": "en", "url": "https://stackoverflow.com/questions/23061508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Unable to access merge field values inside visualforce component in angularJs View: <div ng-controller = "ClPortalRegistrationController"> <div ng-repeat="(key, value) in ObjectApiFieldsetMap"> {{key}} {{value}} //this is printing correct result <c:FieldSetComponent objectAPIName="'{{key}}'" fieldSet="'{{value}}'" cid="'{{key}}'" sectionTitle="Section 1" columns="2" textAlign="center"></c:FieldSetComponent> </div> </div> Controller: $scope.ObjectApiFieldsetMap = { Applications__c: "Application_FieldSet_One", clcommon__Collateral__c: "Collateral_FieldSet_One" }; Now when I'm trying to access {{key}},{{value}} inside c:FieldSetComponent ,its only passing string as {{key}} and {{value}} and not the converted result. How can I access values stored inside key, value inside component? A: Posting the solution which I implemented as a work around. Turns out that you cannot access angular merge field values inside visualforce components. So instead of manipulating(segregating input into key-value pair) values inside angular controller, I have to push the logic to apex controller. <apex:component controller="RegistrationController" access="global"> <apex:repeat value="{!ObjectApiFieldsetMap}" var="apiName"> <c:FieldSetComponent objectAPIName="{!apiName}" fieldSet="{!ObjectApiFieldsetMap[apiName]}" cid="{!apiName}{!ObjectApiFieldsetMap[apiName]}" columns="1" textAlign="center"> </c:FieldSetComponent> </apex:repeat> </apex:component> And in my apex controller i.e RegistrationController , I have set the logic to segregate key values from a map input which I'm using inside visualforce component global class RegistrationController { global Map<String,String> ObjectApiFieldsetMap { get { ObjectApiFieldsetMap = arrangeApiFieldSetsByOrder(); return ObjectApiFieldsetMap; } set; } global Map<String,String> arrangeApiFieldSetsByOrder() { Map<String,String> ObjectApiFieldsetMap = new Map<String,String>(); /* logic for segregation */ return ObjectApiFieldsetMap; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/38631117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Binding JavaScript Variables to HTML Elements I've got this system whereby a Bootstrap table is created. In each cell in the each row, a numerical value appears representing the number of, say, customers in that region. Something like, ----------------------------------- Region | Number ----------------------------------- New York | 5 New England | 8 Florida | 3 ----------------------------------- The number is calculated in JavaScript when the DOM loads. The JavaScript receives all customers in an unorganized array, which I then sorted out into a proper matrix called customers[region], where each element in customers is itself an array of objects, like this: var customers = { 0 : ["customer1","customer2","customer3"], 1 : ["customer4","customer5","customer6"], 2 : ["customer7","customer8","customer9"] } The table cells are filled in dynamically with some JS code looking like var cell = "<td><a id='testLink0' href='#'>" + customers[0].length + "</a></td>" $("#row1").append(string); // Gets one of the rows, and appends to it Now, however, I want to load a modal window when the user clicks one of the numbers. The modal window will show a table of all of the customers in that region. I am able to turn each of the numbers into a link that opens the modal window, but I can't find a good way to pass the modal window the data. So I want to bind customers[0] to one link, bind customers[1] to another link, etc, so that when the link is clicked, the modal window receives that specific JavaScript object. $(document).ready(function() { $('a#testLink0').click(function(e) { $.get('template.html', function(data){ modal.open({content: data}); }); }); How can I pass the JavaScript object to some JavaScritp code in template.html? Note that the number of links is actually much, much greater, so much greater that it would be best to assign the links dynamically. Any suggestions? A: It seems to be a better approach simply to generate the ids (or any other attributes of those links) dynamically but in a way that you're able to map the given generated attribute value (for instance an id of customers1) to the hash key of your object connected to that link (customers1 would lead you to the key 1 in your hash, for instance) so you're able to get that attribute value from the click event -> e (by examining the value of e.target - http://api.jquery.com/category/events/event-object/) passed to your .click(function(e) {...})and then simply read the hash property you want to populate your modal.
{ "language": "en", "url": "https://stackoverflow.com/questions/33225972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Randomly sample rows based on year-month data = {'date':['2019-01-01', '2019-01-02', '2020-01-01', '2020-02-02'], 'tweets':["aaa", "bbb", "ccc", "ddd"]} df = pandas.DataFrame(data) df['daate'] = pandas.to_datetime(df['date'], infer_datetime_format=True) So I have an object type date and a datetime64[ns] type date. Image that I have 100 rows in each year-month. How can I randomly sample 10 rows in each year-month and put them into a data frame? Thanks! A: Use DataFrame.groupby per years and months or month periods and use custom lambda function with DataFrame.sample: df1 = (df.groupby([df['daate'].dt.year, df['daate'].dt.month], group_keys=False) .apply(lambda x: x.sample(n=10))) Or: df1 = (df.groupby(df['daate'].dt.to_period('m'), group_keys=False) .apply(lambda x: x.sample(n=10))) Sample: data = {'daate':pd.date_range('2019-01-01', '2020-01-22'), 'tweets':np.random.choice(["aaa", "bbb", "ccc", "ddd"], 387) } df = pd.DataFrame(data) df1 = (df.groupby([df['daate'].dt.year, df['daate'].dt.month], group_keys=False) .apply(lambda x: x.sample(n=10))) print (df1) date tweets daate 9 2019-01-10 bbb 2019-01-10 29 2019-01-30 ddd 2019-01-30 17 2019-01-18 ccc 2019-01-18 12 2019-01-13 ccc 2019-01-13 20 2019-01-21 ddd 2019-01-21 .. ... ... ... 381 2020-01-17 bbb 2020-01-17 375 2020-01-11 aaa 2020-01-11 373 2020-01-09 bbb 2020-01-09 368 2020-01-04 aaa 2020-01-04 382 2020-01-18 bbb 2020-01-18 [130 rows x 3 columns] A: import pandas as pd data = {"date": ["2019-01-01", "2019-01-02", "2020-01-01", "2020-02-02"], "tweets": ["aaa", "bbb", "ccc", "ddd"]} df = pd.DataFrame(data) df["daate"] = pd.to_datetime(df["date"], infer_datetime_format=True) # Just duplicating row df = df.loc[df.index.repeat(100)] # The actual code available_dates = df["daate"].unique() sampled_df = pd.DataFrame() for each_date in available_dates: rows_with_that_date = df.loc[df["daate"] == each_date] sampled_rows_with_that_date = rows_with_that_date.sample(5) # 5 samples sampled_df = sampled_df.append(sampled_rows_with_that_date) print(len(sampled_df))
{ "language": "en", "url": "https://stackoverflow.com/questions/68826749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check that number of received calls is within range with NSubstitute Is there a way to check with NSubstitute that number of received calls falls within certain range? I would like to do something like: myMock.Received(r => r > 1 && r <= 5).MyMethod(); Alternatively, if I could get the exact number of received calls that would do the job as well. I am unit testing retries and timeouts and based on system load and other tests running number of retries can vary during unit test execution. A: The NSubstitute API does not currently support this exactly (but it's a nice idea!). There is a hacky-ish way of doing it using the unofficial .ReceivedCalls extension: var calls = myMock.ReceivedCalls() .Count(x => x.GetMethodInfo().Name == nameof(myMock.MyMethod)); Assert.InRange(calls, 1, 5); The better way to do this using a custom Quantity from the NSubstitute.ReceivedExtensions namespace: // DISCLAIMER: draft code only. Review and test before using. public class RangeQuantity : Quantity { private readonly int min; private readonly int maxInclusive; public RangeQuantity(int min, int maxInclusive) { // TODO: validate args, min < maxInclusive. this.min = min; this.maxInclusive = maxInclusive; } public override string Describe(string singularNoun, string pluralNoun) => $"between {min} and {maxInclusive} (inclusive) {((maxInclusive == 1) ? singularNoun : pluralNoun)}"; public override bool Matches<T>(IEnumerable<T> items) { var count = items.Count(); return count >= min && count <= maxInclusive; } public override bool RequiresMoreThan<T>(IEnumerable<T> items) => items.Count() < min; } Then: myMock.Received(new RangeQuantity(3,5)).MyMethod(); (Note you will need using NSubstitute.ReceivedExtensions; for this.)
{ "language": "en", "url": "https://stackoverflow.com/questions/56013065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android Retrofit NetworkBoundResource returns null I am trying to retrieve data from a third-party API using Retrofit and NetworkBoundResource (https://developer.android.com/jetpack/guide#addendum). However when this NetworkBoundResource runs it returns null. The JSON I'm trying to fetch is as follows: { "id":93 "name":"Business" "total":587 "has_next":true "podcasts":[] } Hoping someone can help! Relevant code below. Podcasts.kt @Keep @Entity( tableName = "podcasts" ) @Parcelize data class Podcast( @PrimaryKey @ColumnInfo(name = "id") val id: String, @ColumnInfo(name = "title") val title: String, @ColumnInfo(name = "publisher") val publisher: String, @ColumnInfo(name = "image") val image: String, @ColumnInfo(name = "thumbnal") val thumbnail: String, @ColumnInfo(name = "url") val url: String, @ColumnInfo(name = "total_episodes") @Json(name = "total_episodes") val total: Int, @ColumnInfo(name = "favourite") var favourite: Boolean = false, ) : Parcelable @Entity( tableName = "best_podcasts", indices = [Index( value = ["id"], unique = true )] ) data class BestPodcasts( @PrimaryKey @ColumnInfo(name = "id") val id: String, @ColumnInfo(name = "podcasts") val podcasts: List<Podcast> ) NetworkBoundResource abstract class NetworkBoundResource<ResultType, RequestType> @MainThread constructor(private val appExecutors: AppExecutors) { // private val result = MediatorLiveData<Resource<ResultType>>() init { result.value = Resource.loading(null) @Suppress("LeakingThis") val dbSource = loadFromDb() result.addSource(dbSource) { data -> result.removeSource(dbSource) if (shouldFetch(data)) { fetchFromNetwork(dbSource) } else { result.addSource(dbSource) { newData -> setValue(Resource.success(newData)) } } } } @MainThread private fun setValue(newValue: Resource<ResultType>) { if (result.value != newValue) { result.value = newValue } } private fun fetchFromNetwork(dbSource: LiveData<ResultType>) { val apiResponse = createCall() // we re-attach dbSource as a new source, it will dispatch its latest value quickly result.addSource(dbSource) { newData -> setValue(Resource.loading(newData)) } result.addSource(apiResponse) { response -> result.removeSource(apiResponse) result.removeSource(dbSource) when (response) { is ApiSuccessResponse -> { appExecutors.diskIO().execute { saveCallResult(processResponse(response)) appExecutors.mainThread().execute { // we specially request a new live data, // otherwise we will get immediately last cached value, // which may not be updated with latest results received from network. result.addSource(loadFromDb()) { newData -> setValue(Resource.success(newData)) } } } } is ApiEmptyResponse -> { appExecutors.mainThread().execute { // reload from disk whatever we had result.addSource(loadFromDb()) { newData -> setValue(Resource.success(newData)) } } } is ApiErrorResponse -> { onFetchFailed() result.addSource(dbSource) { newData -> setValue(Resource.error(response.errorMessage, newData)) } } } } } fun asLiveData() = result as LiveData<Resource<ResultType>> @WorkerThread protected open fun processResponse(response: ApiSuccessResponse<RequestType>) = response.body @WorkerThread protected abstract fun saveCallResult(item: RequestType) @MainThread protected abstract fun shouldFetch(data: ResultType?): Boolean @MainThread protected abstract fun loadFromDb(): LiveData<ResultType> @MainThread protected abstract fun createCall(): LiveData<ApiResponse<RequestType>> protected open fun onFetchFailed() { Log.d("AHHHH", "Fetch failed") } } RemoteDataSource class RemoteDataSource { private val podcastApiService = PodcastApi.retrofitService fun downloadBestPodcasts(): LiveData<ApiResponse<BestPodcasts>> { return podcastApiService.downloadBestPodcasts() } } DataRepository class DataRepository( private val localDataSource: LocalDataSource, private val remoteDataSource: RemoteDataSource, private val appExecutors: AppExecutors ) { fun downloadBestPodcasts(shouldFetch: Boolean): LiveData<Resource<BestPodcasts>> { return object : NetworkBoundResource<BestPodcasts, BestPodcasts>(appExecutors) { override fun saveCallResult(item: BestPodcasts) { localDataSource.insertBestPodcasts(item) } override fun shouldFetch(data: BestPodcasts?) = data == null || shouldFetch override fun loadFromDb(): LiveData<BestPodcasts> = localDataSource.getBestPodcasts() override fun createCall() = remoteDataSource.downloadBestPodcasts() }.asLiveData() } } WebService private val retrofit = Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(LiveDataCallAdapterFactory()) .baseUrl(BASE_URL) .build() interface WebService { @GET("best_podcasts") fun downloadBestPodcasts( @Header("X-ListenAPI-Key") apiKey: String = BuildConfig.API_KEY, @Query("genre") genreId: Int? = null ): LiveData<ApiResponse<BestPodcasts>> }
{ "language": "en", "url": "https://stackoverflow.com/questions/67008054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to flatten bigquery record with multiple repeated fields? I'm trying to query against app-engine datastore backup data. In python, the entities are described as something like this: class Bar(ndb.Model): property1 = ndb.StringProperty() property2 = ndb.StringProperty() class Foo(ndb.Model): bar = ndb.StructuredProperty(Bar, repeated=True) baz = ndb.StringProperty() Unfortunately when Foo gets backed up and loaded into bigquery, the table schema gets loaded as: bar | RECORD | NULLABLE bar.property1 | STRING | REPEATED bar.property2 | STRING | REPEATED baz | STRING | NULLABLE What I would like to do is to get a table of all bar.property1 and associated bar.property2 where baz = 'baz'. Is there a simple way to flatten Foo so that the bar records are "zipped" together? If that's not possible, is there another solution? A: As hinted in a comment by @Mosha, it seems that big query supports User Defined Functions (UDF). You can input it in the UDF Editor tab on the web UI. In this case, I used something like: function flattenTogether(row, emit) { if (row.bar && row.bar.property1) { for (var i=0; i < row.bar.property1.length; i++) { emit({property1: row.bar.property1[i], name: row.bar.property2[i]}); } } }; bigquery.defineFunction( 'flattenBar', ['bar.property1', 'bar.property2'], [{'name': 'property1', 'type': 'string'}, {'name': 'property2', 'type': 'string'}], flattenTogether); And then the query looked like: SELECT property1, property2, FROM flattenBar( SELECT bar.property1, bar.property2, FROM [dataset.foo] WHERE baz = 'baz') A: Since baz is not repeated, you can simply filter on it in WHERE clause without any flattening: SELECT bar.property1, bar.property2 FROM t WHERE baz = 'baz'
{ "language": "en", "url": "https://stackoverflow.com/questions/33880321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: shell script triggering through control-m Generally, i have a shell script which run in Control-m with certain parameters like: sh shell_script_program.sh 'param_1' 'param_2' 'param_3' But, in order to test the program i have to change the parameter values passing to the shell script. So i was editing whole time when ever i want to run the program. sh shell_script_program.sh 'value_1' 'value_2' 'value_3' sh shell_script_program.sh 'value_1' 'value_3' 'value_4' Is there any way to automate the different set of parameters passed as arguments to the script. Could you please provide a hint for any solution. A: You can create a file with a different set of paramaters like $cat input_param.txt 'param_1' 'param_2' 'param_3' 'value_1' 'value_2' 'value_3' 'value_1' 'value_3' 'value_4' $ and call script in loop while read param; do echo ./shell_script_program.sh ${param} | sh ; done < input_param.txt A: You can create a wrapper script for this. Create an environment file with the parameters value. For eg a .env file with the param values. You can modify the param value by making changes to .env file. cat .env param_1=value1 param_2=value2 In the wrapper load the environment file. Wrapper script Code: cat wrapper.sh ./.env file sh shell_script_program.sh 'value_1' 'value_2' 'value_3' Check for exit status echo $? sh shell_script_program.sh 'param_1' 'param_2' 'param_3' echo $? You can execute wrapper script sh wrapper.sh Based on exit status you can decide whether to proceed or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/61791738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Cloud SDK Windows Installer Error: "System cannot find the path specified" When I tried install Google Cloud SDK by its own installer I get this: "Sistem belirtilen yolu bulamiyor" means "System cannot find the path specified" And this is my enviroment variables: C:/HERE where my Python executable file is. So who is going to tell me what is going on here? Also my Python version is 3.7.6 EDIT: This part is extra and a bit long but here are my log files. I hope it helps. I am tryin to make a CRM program and I need to connect it to Cloud Services. Thanks for any help! 2020-10-13 00:15:24,919 DEBUG root Loaded Command Group: ['gcloud', 'components'] 2020-10-13 00:15:24,926 DEBUG root Loaded Command Group: ['gcloud', 'components', 'copy_bundled_python'] 2020-10-13 00:15:24,927 DEBUG root Running [gcloud.components.copy-bundled-python] with arguments: [] 2020-10-13 00:15:32,618 INFO root Display format: "value(python_location)" 2020-10-13 00:15:32,618 INFO ___FILE_ONLY___ C:\Users\ALICEM~1\AppData\Local\Temp\tmpfffjhsuk\python\python.exe 2020-10-13 00:15:32,623 DEBUG root Metrics reporting process started... 2020-10-13 00:17:18,590 DEBUG root Loaded Command Group: ['gcloud', 'components'] 2020-10-13 00:17:18,598 DEBUG root Loaded Command Group: ['gcloud', 'components', 'post_process'] 2020-10-13 00:17:18,600 DEBUG root Running [gcloud.components.post-process] with arguments: [] 2020-10-13 00:18:41,822 INFO root Display format: "none" Last one is a bit long so i took the last bit 2020-10-13 00:17:17,480 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ 2020-10-13 00:17:17,480 INFO ___FILE_ONLY___ ╠═ Creating backup and activating new installation ═╣ 2020-10-13 00:17:17,480 INFO ___FILE_ONLY___ ╚ 2020-10-13 00:17:17,480 DEBUG root Attempting to move directory [C:\Users\Ali cem üzüm\AppData\Local\Google\Cloud SDK\google-cloud-sdk] to [C:\Users\Ali cem üzüm\AppData\Local\Google\Cloud SDK\google-cloud-sdk.staging\.install\.backup] 2020-10-13 00:17:17,498 INFO ___FILE_ONLY___ ══════════════════════════════ 2020-10-13 00:17:17,498 DEBUG root Attempting to move directory [C:\Users\Ali cem üzüm\AppData\Local\Google\Cloud SDK\google-cloud-sdk.staging] to [C:\Users\Ali cem üzüm\AppData\Local\Google\Cloud SDK\google-cloud-sdk] 2020-10-13 00:17:17,522 INFO ___FILE_ONLY___ ══════════════════════════════ 2020-10-13 00:17:17,522 INFO ___FILE_ONLY___ ╝ 2020-10-13 00:17:17,609 DEBUG root Updating notification cache... 2020-10-13 00:17:17,609 INFO ___FILE_ONLY___ 2020-10-13 00:17:17,612 INFO ___FILE_ONLY___ Performing post processing steps... 2020-10-13 00:17:17,613 DEBUG root Executing command: ['C:\\Users\\ALICEM~1\\AppData\\Local\\Temp\\tmpfffjhsuk\\python\\python.exe', '-S', 'C:\\Users\\Ali cem üzüm\\AppData\\Local\\Google\\Cloud SDK\\google-cloud-sdk\\lib/gcloud.py', 'components', 'post-process'] 2020-10-13 00:18:41,872 DEBUG ___FILE_ONLY___ 2020-10-13 00:18:41,873 DEBUG ___FILE_ONLY___ 2020-10-13 00:18:42,044 INFO ___FILE_ONLY___ Update done! 2020-10-13 00:18:42,049 INFO root Display format: "none" A: I recommend you double check your PATH variable. As per: "If your installation is unsuccessful due to the find command not being recognized, ensure your PATH environment variable is set to include the folder containing find. Usually, this is C:\WINDOWS\system32;" I noticed that you added the logs :), I would like to mention that sometimes there are some issues with special characters in the admin user name(~),so just a quick test, could you please try to use another user without any special character in the name? Another option is installing manually Python 2.7 and set an environment variable with "CLOUDSDK_PYTHON" with a direct path to python.exe. For example: C:\HERE\python.exe Finally, I found this Stackoverflow post that could help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/64321755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Laravel Pass Data To Form on Another Page I am attempting to essentially pass a variable from one page url to another to assist in filling out a form. I have a Script model and a Prescription model. Each script can have multiple prescriptions. So on the Scripts show page, I'm wanting to have a create button that allows users to click it, and it sends them to the Prescriptions create page, but auto-fills out the script_id for the user in the controller. This way it is definitively tagged to the correct script. So if someone clicks on 'Create Prescription' on test.com/scripts/34/show, it takes them to test.com/prescriptions/create and automatically applies 34 as the script_id field - ideally either a hidden field, or directly passed to the controller somehow so that the user can't tamper with it. A: You can use session, before returning prescriptions/create page you can do Session::flash('script_id', $script_id); and when user submits prescription creation just take it $script_id = Session::get('script_id');
{ "language": "en", "url": "https://stackoverflow.com/questions/53051663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding value of row below in R - most efficient My data: no.att year freq 1 1896 380 2 1900 1936 3 1904 1301 4 1906 1733 5 1908 3101 6 1912 4040 7 1920 4292 8 1924 5693 9 1928 5574 10 1932 3321 11 1936 7401 12 1948 7480 13 1952 9358 14 1956 6434 15 1960 9235 16 1964 9480 17 1968 10479 18 1972 11959 19 1976 10502 20 1980 8937 21 1984 11588 22 1988 14676 23 1992 16413 24 1994 3160 25 1996 13780 26 1998 3605 27 2000 13821 28 2002 4109 29 2004 13443 30 2006 4382 31 2008 13602 32 2010 4402 33 2012 12920 34 2014 4891 35 2016 13688 My goal: from year 1992 and forwards the observation interval changes from every 4th year to every 2nd year. I want to keep it every 4th year. so I want to -> no.att[24,2] + no.att[25,2] my solution is: x <- 24 y <- 25 temp <- no.att[x,2] temp1 <- no.att[y,2] no.att[y,2] <- temp + temp1 x <- x + 2 y <- y + 2 running the above once and then skipping the two top lines does the trick. What would an alternative to this approach be? A: Using ave to sum freq every 4 yearly, ans <- dat ans$freq <- ave(dat$freq, ceiling(dat$year/4), FUN=sum) ans[ans$year %in% seq(1896,2016,4),] output: year freq 1 1896 380 2 1900 1936 3 1904 1301 5 1908 4834 6 1912 4040 7 1920 4292 8 1924 5693 9 1928 5574 10 1932 3321 11 1936 7401 12 1948 7480 13 1952 9358 14 1956 6434 15 1960 9235 16 1964 9480 17 1968 10479 18 1972 11959 19 1976 10502 20 1980 8937 21 1984 11588 22 1988 14676 23 1992 16413 25 1996 16940 27 2000 17426 29 2004 17552 31 2008 17984 33 2012 17322 35 2016 18579 data: dat <- read.table(text="year freq 1896 380 1900 1936 1904 1301 1906 1733 1908 3101 1912 4040 1920 4292 1924 5693 1928 5574 1932 3321 1936 7401 1948 7480 1952 9358 1956 6434 1960 9235 1964 9480 1968 10479 1972 11959 1976 10502 1980 8937 1984 11588 1988 14676 1992 16413 1994 3160 1996 13780 1998 3605 2000 13821 2002 4109 2004 13443 2006 4382 2008 13602 2010 4402 2012 12920 2014 4891 2016 13688", header=TRUE)
{ "language": "en", "url": "https://stackoverflow.com/questions/52163109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android not sizing Custom Dialog big enough I am using a custom Dialog that contains a text field, an image, and a button. The text can contain HTML. Sometimes the bottom of the dialog gets chopped off the bottom when the text is long enough. How can I prevent this? I want Android to determine the size of the dialog but it doesn't seem to be doing that. DO I need to size the Dialog myself in this case? Here is the layout... <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/alert_root_incorrect" style="@style/AlertDialogTheme" android:background="@drawable/rounded_alert" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" > <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/rounded_alert" > <TableLayout android:stretchColumns="0" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TableRow> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="left" android:textStyle="bold" android:text="Sorry, that's wrong!" android:textColor="@color/gray_dark" /> <ImageView android:id="@+id/check" android:background="@drawable/xmark" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:layout_marginRight="10dp" /> </TableRow> </TableLayout> <TextView android:id="@+id/alert_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ellipsize="none" android:text="In fact, this is where the explanation will go. Something about how this passage related to the topic" android:textColor="#000000" /> <Button android:id="@+id/okay_button" android:layout_width="100dp" android:layout_height="wrap_content" android:gravity="center" android:layout_gravity="center_horizontal" android:background="@drawable/rounded_alert_button" android:text="Okay" android:textColor="@color/white" android:textSize="20sp" /> </LinearLayout> </LinearLayout> And here is the code I am using to load it... if ( null == layout ) { this.layout = inflater.inflate(R.layout.alert_incorrect, (ViewGroup) findViewById(R.id.alert_root_incorrect)); } TextView message = (TextView) layout.findViewById(R.id.alert_text); message.setText(Html.fromHtml(card.getConclusion())); ((Button) layout.findViewById(R.id.okay_button)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dismissDialog(INCORRECT_DIALOG); nextQuestion(); } }); layout.requestLayout(); dialog = new Dialog(this, R.style.AlertDialogTheme); dialog.setContentView(layout); dialog.setCancelable(false); return dialog; And here's a snap of what I mean.. Thanks, John A: This is not perfect but I've corrected it by setting the layout of the dialog relative to the default display. dialog = new Dialog(this, R.style.AlertDialogTheme); dialog.setContentView(layout); Window window = dialog.getWindow(); window.setLayout( (int)(window.getWindowManager().getDefaultDisplay().getWidth() * .90), (int)(window.getWindowManager().getDefaultDisplay().getHeight() * .90 )); dialog.setCancelable(false); Just tweak the ".90" values until it feels right. A: Here is the solution: * *You should add a Linearlayout at the outside of your dialog's xml file *Then set this Linearlayout's gravity as "center" *the last step is creating a LayoutParams and set it to the dialog android.view.WindowManager.LayoutParams lp = new android.view.WindowManager.LayoutParams(); lp.width = android.view.WindowManager.LayoutParams.FILL_PARENT; lp.height = android.view.WindowManager.LayoutParams.FILL_PARENT; alertDialog.getWindow().setAttributes(lp);
{ "language": "en", "url": "https://stackoverflow.com/questions/3800951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Javascript putting comma in text I'm having problems with my (javascript) API. When I use the coinmarketcap API (https://api.coinmarketcap.com/v1/ticker). As for "max_supply" for bitcoin, it gives me "16865112.0" in text. This is a problem. I want to automatically put comma's in the number like 16,865,112.0 normally I use toLocaleString() but it is marked as text and it doesnt work. $.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) { for (var i = 0; i < data.length - 1; i++) { if (data[i].id == "bitcoin") { $("#total_supply").html(data[i].total_supply.toLocaleString()); } } }); Any suggestions? A: You can still do it, just first convert string to number. var value = "16865112.0"; value = +value; // convert to number var fV = Number(value).toLocaleString(); console.log(fV); A: You are calling Number.toLocaleString on String. You need to convert it to Number first by calling parseInt or Number() constructor (you can change your current locale too). $.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) { for (var i = 0; i < data.length - 1; i++) { if (data[i].id == "bitcoin") { $("#total_supply").html(Number(data[i].total_supply).toLocaleString('en-US')); } } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="total_supply"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/48796196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does Apple allow changing from Non-consumable IAP to Subscription? I have an iOS App with a Non-consumable In-App Purchase, now I want to change my app to subscription business model. Does Apple Review Guidelines allow this change? Surely the old purchaser can continue to use the app without paying again.
{ "language": "en", "url": "https://stackoverflow.com/questions/61029141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to preserve the leading zero when changing a string into a number using Javascript? How do I convert a string such as "03" into a number and keep the zero at the beginning of the string? Using Number("03") will remove the leading 0 and return 3, but I want to keep the 0 there. How would I go about doing this? Here's my JS function for context: function format(input, unit) { if (new RegExp(unit, 'i').test('minute second')) { if (String(input).length === 1) return Number(`0${input}`); else return input; } else if (unit === 'hour') { return input; } } Thanks! EDIT: What I got so far let timer = { hours: 0, minutes: 1, seconds: 30, updateTimerDisplay() { document.getElementById('hour').innerHTML = this.hour; document.getElementById('minute').innerHTML = String(format(this.minutes, 'minute')); document.getElementById('second').innerHTML = String(format(this.seconds, 'second')); }, startTimer() { const { updateTimerDisplay: updateDisplay } = this; let update = setInterval(_ => { this.seconds -= 1; if (this.seconds < 0) { this.seconds = 59; this.minutes -= 1; } if (this.minutes < 0) { this.minutes = 59; this.hours -= 1; } updateDisplay(); }, 1000); } }; timer.updateTimerDisplay(); timer.startTimer(); function format(input, unit) { if (new RegExp(unit, 'i').test('minute second')) { if (String(input).length === 1) return `0${input}`; else return String(input); } } A: Some issues: * *Spelling of this.hour: should be this.hours *By calling updateDisplay you don't pass on the expected value for this. It is better to just keep the original name of the method, and use this.updateTimerDisplay. *Don't convert the 0-prefixed string back to number: you are interested in something to display, so keep the string format. Without changing too much else in your code, the above corrections make it work: let timer = { hours: 0, minutes: 1, seconds: 30, updateTimerDisplay() { // Use textContent, not innerHTML (that is for HTML content) document.getElementById('hour').textContent = this.hours; // spelling! // The function format returns a string, so no need to call String on it: document.getElementById('minute').textContent = format(this.minutes, 'minute'); document.getElementById('second').textContent = format(this.seconds, 'second'); }, startTimer() { // Don't read a function reference into a variable, as you'll lose the this-binding // --------- const { updateTimerDisplay: updateDisplay } = this; let update = setInterval(_ => { this.seconds -= 1; if (this.seconds < 0) { this.seconds = 59; this.minutes -= 1; } if (this.minutes < 0) { this.minutes = 59; this.hours -= 1; } // By having `this.` here, you pass that this-reference to the function this.updateTimerDisplay(); }, 1000); } }; timer.updateTimerDisplay(); timer.startTimer(); function format(input, unit) { // RegExp is overkill here. Just use includes: if (['minute', 'second'].includes(unit.toLowerCase())) { // Don't convert with Number: it must be a string: if (String(input).length === 1) return `0${input}`; else return String(input); } } <span id="hour"></span>:<span id="minute"></span>:<span id="second"></span>
{ "language": "en", "url": "https://stackoverflow.com/questions/66726978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error : 'Sprite' was not declared in this scope I write a game and I need to create a vector of the sprite that represents the enemies in my map struct, but because map.h include sprite.h and vice versa I have an error 'Sprite' is not declared in this scope. I heard about forward declaration; is that the solution? #ifndef SPRITE_H #define SPRITE_H #include "map.h" #include "anim.h" struct Sprite { Animation an; float x,y; int w,h; float vx,vy; bool air; int right, left, top, bottom; int sens; }; void InitSprite(Sprite* sp,Charset* c,float x,float y,int nbstats); int EssaiDeplacement(Map* m,Sprite *sp,float vx,float vy); void Affine(Map* m,Sprite *sp,float vx,float vy); void Move(Map* m,Sprite *sp,const Uint8 *keys); void RenderSprite(Sprite* sp,Charset* c); void Tile_Collision(Sprite* sp,Map* m); void Evolue(Sprite* sp,const Uint8 *state); #endif #ifndef MAP_H #define MAP_H #include <string> #include "mario.h" #include "sprite.h" struct Map { Charset* c; int xtiles_level,ytiles_level; std::vector<std::vector<int> >tableau; std::vector<int> tiles; std::vector<std::vector<int> > limits; std::vector<Sprite> enemys; }; void Load_Tiles(Map* m,Charset* c,const char* fichier,int largeur_monde,int hauteur_monde); void Load_Level(Map* m,const char* fichier); void AfficherMap(Map* m,SDL_Renderer* renderer); void SaveMap(Map* m,const char* fichier); int TileCollision(SDL_Rect *test,Map* m); #endif The error is in map.h. A: Seeing cyclic redundancy in your code! Forward declaration should resolve the issue. Another way: #ifndef COMMON_H #define COMMON_H #include "anim.h" struct Sprite { }; struct Map { }; #endif #ifndef SPRITE_H #define SPRITE_H #include "common.h" void InitSprite(Sprite* sp, Charset* c, float x, float y, int nbstats); /* ... */ #endif #ifndef MAP_H #define MAP_H #include "common.h" #include "mario.h" #include "sprite.h" void Load_Tiles(Map* m, Charset* c, const char* fichier, int largeur_monde, int hauteur_monde); /* ... */ #endif
{ "language": "en", "url": "https://stackoverflow.com/questions/58137920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to swap first div with last div on mobile version? I have divs as follows. <div class="row"> <div class="col-sm-12" id="first-row"></div> <div class="col-sm-12" id="second-row"></div> <div class="col-sm-12" id="third-row"></div> <div class="col-sm-12" id="fourth-row"></div> </div> How can i swap first-row div with fourth-row div on mobile devices? Is it possible to do with just css? What could be best stragety to achieve this, I can do this with javascript, but wanted to know whether it is possible with just css. I am using bootstrap 3 Expected result on mobile <div class="row"> <div class="col-sm-12" id="fourth-row"></div> <div class="col-sm-12" id="second-row"></div> <div class="col-sm-12" id="third-row"></div> <div class="col-sm-12" id="first-row"></div> </div> A: If you use flexbox on the row, you can use the order property to do this for you. (you can use media queries for adding display: flex to target mobile devices) See how the positions of fourth-row and first-row are swapped in the demo below: div.row { display: flex; flex-direction: column; } [id$='-row'] { order: 2; } #first-row { order: 3; } #fourth-row { order: 1; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <div class="row"> <div class="col-sm-12" id="first-row">1</div> <div class="col-sm-12" id="second-row">2</div> <div class="col-sm-12" id="third-row">3</div> <div class="col-sm-12" id="fourth-row">4</div> </div> A: Use Flex property to swap elements. Here is an article about it Reverse Elements Order. Unable to demonstrate the mobile only part, so please use the below CSS. @media only screen and (min-width : 480px) { .row { display: flex; flex-direction: column-reverse; } } $('button').on('click', function(){ $('.row').toggleClass('row-reverse'); }) .row-reverse { display: flex; flex-direction: column-reverse; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row"> <div class="col-sm-12" id="first-row">first</div> <div class="col-sm-12" id="second-row">second</div> <div class="col-sm-12" id="third-row">third</div> <div class="col-sm-12" id="fourth-row">fourth</div> </div> <button>reverse/unreverse</button> A: If you just want to change the look in different screen sizes, you can use default Bootstrap grid ordering: https://getbootstrap.com/docs/3.3/css/#grid-column-ordering Might be easier to see the responsive result here: https://codepen.io/anon/pen/vJQmXq <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <div class="row"> <div class="col-sm-12 col-md-3 col-md-push-9" id="fourth-row">4</div> <div class="col-sm-12 col-md-3" id="second-row">2</div> <div class="col-sm-12 col-md-3" id="third-row">3</div> <div class="col-sm-12 col-md-3 col-md-pull-9" id="first-row">1</div> </div> A: Here you go with a solution using jQuery https://jsfiddle.net/68bfxozm/1/ var updateDivOrder = function() { if($(document).width() < 500){ var first = $('#first-row').clone(); var last = $('#fourth-row').clone(); $('.row div').first().remove(); $('.row div').last().remove(); $('.row div').first().before(last); $('.row div').last().after(first); } else { var first = $('#first-row').clone(); var last = $('#fourth-row').clone(); $('.row div').first().remove(); $('.row div').last().remove(); $('.row div').first().before(first); $('.row div').last().after(last); } } updateDivOrder(); $(window).resize(updateDivOrder); <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row"> <div class="col-sm-12" id="first-row">1</div> <div class="col-sm-12" id="second-row">2</div> <div class="col-sm-12" id="third-row">3</div> <div class="col-sm-12" id="fourth-row">4</div> </div> My assumption is mobile width will be less than 500px. Hope this will help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/45945121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Making Highly Customized, Hoverable, Overlappable, Widgets I want to up my game in UI design using PyQt5. I feel like the resources for UI customization in PyQt5 are not easy to find. It is possible to try and make personalized widget, but the overall method seems non-standardized. I need to build an arrow widget that is hoverable, overlappable with other widgets and highly customized. As I read in this tutorial and some other posts, it possible to do exactly what you need using paintEvent. Thus that is what I tried, but overall, I feel like the method is quite messy, and I'd like some guidelines on building complex Customized, general widget. Here's what I have: Customized Shape: I built my code based on this Hoverable property: I read everywhere that modifying the projects styleSheet is usually the way to go, especially if you want to make your Widget general and adapt to colors, the problem is that I wasn't able to find how to use properly self.palette to fetch the current colors of the QApplication styleSheet. I feel like i's have to maybe use enterEvent and leaveEvent, but I tried to redraw the whole widget with a painter in those functions and it said QPainter::begin: Painter already active QWidget::paintEngine: Should no longer be called QPainter::begin: Paint device returned engine == 0, type: 1 QPainter::setRenderHint: Painter must be active to set rendering hints Overlappable Property: I found a previous post which seemed to have found a solution: create a second widget that is children of the main widget, in order to be able to move the children around. I tried that but it seems that it doesn't want to move, no matter the position I give the widget. Here is my code: import sys from PyQt5.QtWidgets import QWidget, QHBoxLayout, QGraphicsDropShadowEffect, QApplication, QFrame, QPushButton from PyQt5.QtCore import Qt, QPoint, QLine from PyQt5.QtGui import QPainter, QPen, QColor, QPalette class MainWidget(QWidget): def __init__(self): super(MainWidget, self).__init__() self.resize(500, 500) self.layout = QHBoxLayout() self.setLayout(self.layout) self.myPush = QPushButton() self.layout.addWidget(self.myPush) self.arrow = ArrowWidget(self) position = QPoint(-40, 0) self.layout.addWidget(self.arrow) self.arrow.move(position) class ArrowWidget(QWidget): def __init__(self, parent=None): super(ArrowWidget, self).__init__(parent) self.setWindowFlag(Qt.FramelessWindowHint) self.setAttribute(Qt.WA_TranslucentBackground) self.w = 200 self.h = 200 self.blurRadius = 20 self.xO = 0 self.yO = 20 self.resize(self.w, self.h) self.layout = QHBoxLayout() # myFrame = QFrame() # self.layout.addWidget(myFrame) self.setLayout(self.layout) self.setStyleSheet("QWidget:hover{border-color: rgb(255,0,0);background-color: rgb(255,50,0);}") shadow = QGraphicsDropShadowEffect(blurRadius=self.blurRadius, xOffset=self.xO, yOffset=self.yO) self.setGraphicsEffect(shadow) def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.begin(self) # painter.setBrush(self.palette().window()) # painter.setPen(QPen(QPalette, 5)) ok = self.frameGeometry().width()/2-self.blurRadius/2-self.xO/2 oky = self.frameGeometry().height()/2-self.blurRadius/2-self.yO/2 painter.drawEllipse(QPoint(self.frameGeometry().width()/2-self.blurRadius/2-self.xO/2, self.frameGeometry().height()/2-self.blurRadius/2-self.yO/2), self.w/2-self.blurRadius/2-self.yO/2-self.xO/2, self.h/2-self.blurRadius/2-self.yO/2-self.xO/2) painter.drawLines(QLine(ok-25, oky-50, ok+25, oky), QLine(ok+25, oky, ok-25, oky+50)) painter.end() if __name__ == '__main__': app = QApplication(sys.argv) testWidget = MainWidget() testWidget.show() sys.exit(app.exec_()) If someone could help me make this work and explain along the way to help us better understand the structure of customized widgets and explain a better method that isn't messy like this one, I believe it would be a plus to the beginners like me using PyQt5 as a main Framework for UI making. A: There is no "standard" method for custom widgets, but usually paintEvent overriding is required. There are different issues in your example, I'll try and address to them. Overlapping If you want a widget to be "overlappable", it must not be added to a layout. Adding a widget to a layout will mean that it will have its "slot" within the layout, which in turn will try to compute its sizes (based on the widgets it contains); also, normally a layout has only one widget per "layout slot", making it almost impossible to make widget overlap; the QGridLayout is a special case which allows (by code only, not using Designer) to add more widget to the same slot(s), or make some overlap others. Finally, once a widget is part of a layout, it cannot be freely moved nor resized (unless you set a fixedSize). The only real solution to this is to create the widget with a parent. This will make it possible to use move() and resize(), but only within the boundaries of the parent. Hovering While it's true that most widgets can use the :hover selector in the stylesheet, it only works for standard widgets, which do most of their painting by themself (through QStyle functions). About this, while it's possible to do some custom painting with stylesheets, it's generally used for very specific cases, and even in this case there is no easy way to access to the stylesheet properties. In your case, there's no need to use stylesheets, but just override enterEvent and leaveEvent, set there any color you need for painting and then call self.update() at the end. Painting The reason you're getting those warnings is because you are calling begin after declaring the QPainter with the paint device as an argument: once it's created it automatically calls begin with the device argument. Also, it usually is not required to call end(), as it is automatically called when the QPainter is destroyed, which happens when the paintEvent returns since it's a local variable. Example I created a small example based on your question. It creates a window with a button and a label within a QGridLayout, and also uses a QFrame set under them (since it's been added first), showing the "overlapping" layout I wrote about before. Then there's your arrow widget, created with the main window as parent, and that can be moved around by clicking on it and dragging it. import sys from PyQt5 import QtCore, QtGui, QtWidgets class ArrowWidget(QtWidgets.QWidget): def __init__(self, parent=None): super().__init__(parent) # since the widget will not be added to a layout, ensure # that it has a fixed size (otherwise it'll use QWidget default size) self.setFixedSize(200, 200) self.blurRadius = 20 self.xO = 0 self.yO = 20 shadow = QtWidgets.QGraphicsDropShadowEffect(blurRadius=self.blurRadius, xOffset=self.xO, yOffset=self.yO) self.setGraphicsEffect(shadow) # create pen and brush colors for painting self.currentPen = self.normalPen = QtGui.QPen(QtCore.Qt.black) self.hoverPen = QtGui.QPen(QtCore.Qt.darkGray) self.currentBrush = self.normalBrush = QtGui.QColor(QtCore.Qt.transparent) self.hoverBrush = QtGui.QColor(128, 192, 192, 128) def mousePressEvent(self, event): if event.buttons() == QtCore.Qt.LeftButton: self.mousePos = event.pos() def mouseMoveEvent(self, event): # move the widget based on its position and "delta" of the coordinates # where it was clicked. Be careful to use button*s* and not button # within mouseMoveEvent if event.buttons() == QtCore.Qt.LeftButton: self.move(self.pos() + event.pos() - self.mousePos) def enterEvent(self, event): self.currentPen = self.hoverPen self.currentBrush = self.hoverBrush self.update() def leaveEvent(self, event): self.currentPen = self.normalPen self.currentBrush = self.normalBrush self.update() def paintEvent(self, event): qp = QtGui.QPainter(self) qp.setRenderHints(qp.Antialiasing) # painting is not based on "pixels", to get accurate results # translation of .5 is required, expecially when using 1 pixel lines qp.translate(.5, .5) # painting rectangle is always 1px smaller than the actual size rect = self.rect().adjusted(0, 0, -1, -1) qp.setPen(self.currentPen) qp.setBrush(self.currentBrush) # draw an ellipse smaller than the widget qp.drawEllipse(rect.adjusted(25, 25, -25, -25)) # draw arrow lines based on the center; since a QRect center is a QPoint # we can add or subtract another QPoint to get the new positions for # top-left, right and bottom left corners qp.drawLine(rect.center() + QtCore.QPoint(-25, -50), rect.center() + QtCore.QPoint(25, 0)) qp.drawLine(rect.center() + QtCore.QPoint(25, 0), rect.center() + QtCore.QPoint(-25, 50)) class MainWidget(QtWidgets.QWidget): def __init__(self): super().__init__() layout = QtWidgets.QGridLayout() self.setLayout(layout) self.button = QtWidgets.QPushButton('button') layout.addWidget(self.button, 0, 0) self.label = QtWidgets.QLabel('label') self.label.setAlignment(QtCore.Qt.AlignCenter) layout.addWidget(self.label, 0, 1) # create a frame that uses as much space as possible self.frame = QtWidgets.QFrame() self.frame.setFrameShape(self.frame.StyledPanel|self.frame.Raised) self.frame.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) # add it to the layout, ensuring it spans all rows and columns layout.addWidget(self.frame, 0, 0, layout.rowCount(), layout.columnCount()) # "lower" the frame to the bottom of the widget's stack, otherwise # it will be "over" the other widgets, preventing them to receive # mouse events self.frame.lower() self.resize(640, 480) # finally, create your widget with a parent, *without* adding to a layout self.arrowWidget = ArrowWidget(self) # now you can place it wherever you want self.arrowWidget.move(220, 140) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) testWidget = MainWidget() testWidget.show() sys.exit(app.exec_())
{ "language": "en", "url": "https://stackoverflow.com/questions/57270293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: voa_class related exception while browsing through objects in DB, using Telerik libraries Edit2: this question started as a question on how to browse through tables, but it turned into a question about Telerik voa_class exception Edit1: this question contains two ways of trying to do the same thing. I would like to do something like: var Obj1 = database.GetData<Class1>().First(); var Obj2 = database.GetData<Class1>().Next(); First attempt The idea of Next() is simply to take another one. As Next() method does not exist, so I've decided to try this here: var Obj1 = database.GetData<Class1>().First(); var Obj2 = database.GetData<Class1>().Single(o => o.Name != Obj1.Name); This, however, generates a weird exception: Telerik.OpenAccess.Exceptions.DataStoreException HResult=0x80131500 Message=Row for OID GenericOID@87f2834a Class1 Id=2 NOTRES is not in the hierarchy starting at <Namespace>.Class1 ('Class1s') (voa_class for row is ...) Source=Telerik.OpenAccess.Runtime StackTrace: at OpenAccessRuntime.ExceptionWrapper.Throw() at OpenAccessRuntime.storagemanager.logging.LoggingStorageManager.executeQueryAll(ApplicationContext context, ImmutableQueryDetails query, CompiledQuery compiledQuery, QueryParameters parameters, Int32 skip, Int32 take) at OpenAccessRuntime.DataObjects.UnsynchronizedPMProxy.getAllQueryResults(CompiledQuery cq, QueryParameters parameters, Int32 skip, Int32 take) at OpenAccessRuntime.DataObjects.ForwardQueryResult.Resolve() at OpenAccessRuntime.DataObjects.ForwardQueryResult.Initialize() at OpenAccessRuntime.DataObjects.ForwardQueryResult.get_Item(Int32 indexParam) at OpenAccessRuntime.ListEnumerator.setCurrent(Int32 _pos) at OpenAccessRuntime.ListEnumerator.Move(Int32 relative) at OpenAccessRuntime.ListEnumerator.MoveNext() at Telerik.OpenAccess.Query.TypedEnumerator`1.MoveNext() at Telerik.OpenAccess.Query.ExpressionExecution.PerformDatabaseQuerySingle[TResult,T](ChainedContext context, Expression expression, QueryableCategory before, Int32& found, Int32 elemAt, Boolean single, Boolean diffType) at Telerik.OpenAccess.Query.ExpressionExecution.PerformQuerySingle[T,TResult](ExpressionCutter cutter, MethodCallExpression mce, ChainedContext piece, QueryOptions options) at Telerik.OpenAccess.Query.Piece`1.ExecuteSingle[TResult](Expression expression) at Telerik.OpenAccess.Query.Piece`1.System.Linq.IQueryProvider.Execute[TResult](Expression expr) at System.Linq.Queryable.Single[TSource](IQueryable`1 source, Expression`1 predicate) at <CurrentClass>.<CurrentMethod>() in C:\...\<Source_Code>.cs:line 54 at ... Second attempt (This second attempt is based on this other question.) IQueryable<Class1> query = database.GetData<Class1>(); query.OrderBy(u => u.Id); var Obj1 = query.First(); query = query.Skip(1); var Obj2 = query.First(); <== this line gives me an exception. As an exception I get a similar one than the first. What is this about? A: Apparently the source code is correct, but there seem to be problems with the database: The table, corresponding with Class1, contains a column voa_class. The content of that column should be <NameSpace_of_Class1>.Class1. In case there's something else, like <Whatever_NameSpace>.<AnotherClass> or <AnotherNameSpace>.Class1 (like in my case), the mentioned exception gets generated.
{ "language": "en", "url": "https://stackoverflow.com/questions/69032638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Eclipse: Installation failed due to invalid APK file I've got a new Android project in Eclipse, one activity and TextView, nothing else. I didn't modify anything. When I try to run the application on the usb on my phone (zte v970m with android 4.1.1), I get In console Installation failed due to invalid APK file! Please check logcat output for more details. Launch canceled! In LogCat 09-24 12:21:01.174: D/dalvikvm(584): Not late-enabling CheckJNI (already on) 09-24 12:21:01.854: E/Trace(584): error opening trace file: No such file or directory (2) 09-24 12:21:02.684: D/gralloc_goldfish(584): Emulator without GPU emulation detected. Pls, help me to find solution. By the way with AVD all works. My .java package com.example.testusbdebug; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } } my .xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/hello_world" /> </RelativeLayout> and my manifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.testusbdebug" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.testusbdebug.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> </manifest> A: to make it easier for you I would re-download the whole bundle in http://developer.android.com/sdk/index.html
{ "language": "en", "url": "https://stackoverflow.com/questions/18983417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Data File Size Stays Same Whereas Log File Size Is Increasing I am using the following snippet to track the data and log file size increase after certain operations: SELECT @SQL = STUFF(( SELECT ' USE [' + d.name + '] INSERT INTO #space (database_id, data_used_size, log_used_size) SELECT DB_ID() , SUM(CASE WHEN [type] = 0 THEN space_used END) , SUM(CASE WHEN [type] = 1 THEN space_used END) FROM ( SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8) FROM sys.database_files s GROUP BY s.[type] ) t;' FROM sys.databases d WHERE d.[state] = 0 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') EXEC sys.sp_executesql @SQL The problem is, after each write operation, log file size increases as expected but the data file size stays the same for 4 or five operations and then suddenly increases. Why would this be?
{ "language": "en", "url": "https://stackoverflow.com/questions/50847063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: npm package.json and docker (mounting it...) I am using Docker, so this case might look weird. But I want my whole /data directory to be mounted inside my docker container when developing. My /data folder container my package.json file, an app directory and a bunch of other stuff. The problem is that I want my node_modules folder to NOT be persistent, only the package.json file. I have tried a couple of things, but package.json and npm is giving me a hard time here... * *Mounting the package.json file directly will break npm. npm tries to rename the file on save, which is not possible when its a mounted file. *Mounting the parent folder (/data) will mount the node_modules folder. *I cant find any configuration option to put node_modules in another folder outside /data, example /dist *Putting package.json in /data/conf mounting the /data/conf as a volume instead wont work. I cant find any way to specify the package.json path in npmrc. *Putting package.json in /data/conf and symlinking it to /data/package.json wont work. npm breaks the symlink and replaces it with a file. Copying data back and forth to/from inside the docker container is how I am doing it now.. A little tedious.. I also want a clean solution.. A: As you have already answered, I think that might be the only solution right now. When you are building your Docker image, do something like: COPY data/package.json /data/ RUN mkdir /dist/node_modules && ln -s /dist/node_modules /data/node_modules && cd /data && npm install And for other stuff (like bower, do the same thing) COPY data/.bowerrc /data/ COPY data/bower.json /data/ RUN mkdir /dist/vendor && ln -s /dist/vendor /data/vendor && cd /data && bower install --allow-root And COPY data/ /data at the end (so you are able to use Dockers caching and not having to do npm/docker installation when there is a change to data. You will also need to create the symlinks you need and store them in your git-repo. They will be invalid on the outside, but will happely work on the inside of your container. Using this solution, you are able to mount your $PWD/data:/data without getting the npm/bower "junk" outside your container. And you will still be able to build your image as a standalone deployment of your service.. A: A similar and alternative way is to use NODE_ENV variable instead of creating a symlink. RUN mkdir -p /dist/node_modules RUN cp -r node_modules/* /dist/node_modules/ ENV NODE_PATH /dist/node_modules Here you first create a new directory for node_modules, copy all modules there, and have Node read the modules from there. A: I've been having this problem for some time now, and the accepted solution didn't work for me* I found this link, which had an edit pointing here and this indeed worked for me: volumes: - ./:/data - /data/node_modules In this case the Engine creates a volume (see Compose reference on volumes) which is not mounted to your source directory. This was the easiest solution and didn't require me to do any symlinking, setting paths, etc. For reference, my simple Dockerfile just looks like this: # install node requirements WORKDIR /data COPY ./package.json ./package.json RUN npm install -qq # add source code COPY ./ ./ # run watch script CMD npm run watch (The watch script is just webpack --watch -d) Hope this is able to help someone and save hours of time like it did for me! '*' = I couldn't get webpack to work from my package.json scripts and installing anything while inside the container created the node_modules folder with whatever I just installed (I run npm i --save [packages] from inside the container to get the package update the package.json until the next rebuild) A: The solution I went with was placing the node_modules folder in /dist/node_modules, and making a symlink to it from /data/node_modules. I can do this both in my Dockerfile so it will use it when building, and I can submit my symlinks to my git-repo. Everything worked out nicely.. A: Maybe you can save your container, and then rebuild it regularly with a minimal dockerfile FROM my_container and a .dockerignore file containing /data/node_modules See the doc http://docs.docker.com/reference/builder/#the-dockerignore-file
{ "language": "en", "url": "https://stackoverflow.com/questions/26757264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: return a $post with related user model after update in Laravel Is there any way to return the $post after update along the user information? Example: public function update(Request $request, $id) { //on_put, from_user, NewDesc // define rules $rules = array( 'NewDesc' => 'max:600' ); $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return Response()->json($validator); } else{ $post = Post::find($id); $description = $request->input('NewDesc'); $post->update(['description' => $description]); return Response()->json($post); } } This returns the new updated $post to my script but what if I want to send also the user data with it? A: You haven't really given us the information about the users and how they relate, so I will guess... Try something like... return Response()->json($post->load('user')); A: Try something like that: return Response()->json(['post' => $post, 'userdata' => $userdata]);
{ "language": "en", "url": "https://stackoverflow.com/questions/37817098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Absolute center horizontal and vertical a div with fluid width and height? how to make absolute center horizontal and vertical a div with fluid width and height using css? Thanks in advance for helping. #div_parent{ background:#ccc; position:relative; } .div_child{ background-color:#338BC7; position: absolute; left: 50%; width: auto; height: auto; padding: 20px; top:25%; background: blue; color: white; text-align: center; border:1px solid #ccc; } <div id="div_parent"> <div class="div_child"> <p>Centered In The Middle Of The Page.</p> </div> </div> A: A couple of problems with your code: * *You do not have a width and height specified on your html and body, without which any of descendent elements wouldn't have a reference to set their positions and/or dimensions in percent units. *You do not have dimensions (width/height) specified on your #div_parent, without which you cannot position its absolutely positioned child (which is relative to it) to the vertical center. Moreover, as you want to position your .div_child to the center of the page, why do you have a parent wrapped around it anyway. Apart from fixing the above, a trick which is usually used to align elements both horizontally and vertically is to use transform: translate to shift it back by 50%. Like this: .div_child { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); ... } Fiddle: http://jsfiddle.net/abhitalks/Lnqvqnkn/ Snippet: * { box-sizing: border-box; paddin:0; margin: 0; } html, body { height: 100%; width: 100%; } #div_parent{ height: 100%; width: 100%; background: #ccc; position: relative;} .div_child { background-color: #338BC7; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: auto; height: auto; padding: 20px; color: white; text-align: center; border: 1px solid #ccc; } <div id="div_parent"> <div class="div_child"> <p>Centered In The Middle Of The Page.</p> </div> </div> A: When I need fluid width, I prefer using this method: CSS .background { display: table; width: 100%; height: 100%; position: absolute; left: 0; top: 0; } .background > div { display: table-cell; vertical-align: middle; text-align: center; } HTML <div> <div> <p>Centered In The Middle Of The Page.</p> </div> </div> Demo on jsfiddle. Hope it works for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/33538592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot make button non-interactable through seperate script I'm trying to make a button interactable after a certain scene (playing level) has been loaded. It's a button in a menu scene that represent the loaded scene itself (level selectable after playing it). The problem is this: If the users passes a certain level, say level 1, level 2 gets loaded, and a static method gets called: public static void AllowTut2() { Tut2Allowed = true; //public static bool initialised in this script tutorial2.interactable = true; //tutorial2 is a button in the "menu scene" } To make it clear where the variables come from, this is part of the same script: public class LevelSelectScript : MonoBehaviour { public Button tutorial2; public static bool Tut2Allowed = false; //...some other variables void Start () { tutorial2 = tutorial2.GetComponent<Button>(); tutorial2.enabled = false; //more later on ///... some other code } } Now the problem is this error: An object reference is required to access non-static member `LevelSelectScript.tutorial2' (refers to method AllowTut2). It seems that I cannot change tutorial2.interactable trough the given static method (called in another script). It basically says the button tutorial2 is non-static, therefore cannot use this in a static method. Now if I make the button static, i.e. change public Button tutorial2; to public static Button tutorial2; then I have no way to assign the button object in the scene to this variable in the attached script. Does someone perhaps know a solution to this problem? Thanks in advance! A: if you want to use static varaibles and also use inspector for assigning you can use singleton , here is where you can learn it
{ "language": "en", "url": "https://stackoverflow.com/questions/33186525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: javascript form validation not working on chrome & FF here's the html/javascript code... I've tested it on safari and it works fine but in chrome & FF it doesn't validate at all. it directs me automatically to the action link <div id="mc_embed_signup"> <form action="http://example.com/subscribe/post?u=f752d10720e6104f1" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank"> <input type="email" value="" name="EMAIL" class="text" id="mce-EMAIL" placeholder="Enter you email"> <div style="position: absolute; left: -5000px;"><input type="text" name="b_f752d10720e6104f109250a61_95e4fc5f29" value=""></div> <input type="submit" value="submit" name="subscribe" id="mc-embedded-subscribe" class="button" > </form> </div> </div> </div> </div> <script type="text/javascript"> function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function validate(){ var email = $("#mce-EMAIL").val(); if (!validateEmail(email)) { $("#mce-EMAIL").css("border-color", "red"); return false; } $("#mce-EMAIL").css("border-color", "#dbdbdb"); return true; } $(document).ready(function(){ $("form").bind("submit", validate); }); </script> Thank you in advance. A: function validate(){ var email = $("#mce-EMAIL").val(); if (!validateEmail(email)) { $("#mce-EMAIL").css("border-color", "red"); return false; } else{ $("#mce-EMAIL").css("border-color", "#dbdbdb"); $("form").submit(); return true; } } $(document).ready(function(){ $("#mc-embedded-subscribe").on("click",function(){ validate()}); }); this might be better , binding submit with validate , would submit the form anyway !
{ "language": "en", "url": "https://stackoverflow.com/questions/23124827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bootstrap Carousel with previous and next image I found this example to create a bootstrap carousel with previous and next images. https://codepen.io/glebkema/pen/RKavve All images are 33% but I would like to have it like: 10% | 80% | 10%. Is it possible to modify the css to make the previous and next image 10% of the width and the center image 80% ? A: When the item group is getting focus, it adds the active class. So you can do something like this: .item.active .item__third:nth-child(1), .item.active .item__third:nth-child(3) { width:10%; } .item.active .item__third:nth-child(2) { width:80%; } Or generally on .item .item__third class: .item .item__third:nth-child(1), .item .item__third:nth-child(3) { width:10%; } .item .item__third:nth-child(2) { width:80%; }
{ "language": "en", "url": "https://stackoverflow.com/questions/48749180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert nested object via JSON using web api with NHibernate I'm writing an application that consist of a ReadAPI and a WriteAPI. The read API contains the domain classes, and uses EF CORE code first to generate the SQL DB, and to read from it. The write API uses NHibernate to write to the database that is generated by EF Core. So far I have inserted 'simple' object via the write API, which has worked fine. I'm encountering a problem now. I have a domain class, Driver, that has a nested object, Address, inside. At DB level a driver can have one address and an address can belong to multiple drivers. I'm trying to POST a JSON object, a driver object, via the write API. As to now, I've solved inserting the address by creating an address record in DB in advance, and giving the address ID in the JSON. What I want to do now is giving the complete nested JSON object and have NHibernate generate the inserts for me. I have tried so many things but I feel like I am getting nowhere. Any advice would be much appreciated. I'm using .Net Core with NHiberate 5.3.5, which has the mapping by code functionality already. If someone can solve it using Fluent NH instead, that is fine as well since I will convert it to NH 5.3.5 notation myself then. My code: Domain classes: Driver: namespace Models { public class Chauffeur : IIdentifiable { public virtual long Id { get; set; } public virtual string Naam { get; set; } public virtual string Voornaam { get; set; } public virtual DateTime GeboorteDatum { get; set; } //todo validatie public virtual string RijksRegisterNummer { get; set; } public virtual RijbewijsTypes TypeRijbewijs { get; set; } public virtual bool Actief { get; set; } //rel adres public virtual long AdresId { get; set; } public virtual Adres Adres { get; set; } //rel tankkaart public virtual long TankkaartId { get; set; } public virtual Tankkaart Tankkaart { get; set; } } } Address: namespace Models { public class Adres : IIdentifiable { public virtual long Id { get; set; } public virtual string Straat { get; set; } public virtual int Nummer { get; set; } public virtual string Stad { get; set; } public virtual int Postcode { get; set; } public virtual ICollection<Chauffeur> Chauffeurs { get; set; } } } My DriverMap so far: namespace WriteAPI { public class ChauffeurMap : ClassMapping<Chauffeur> { public ChauffeurMap() { this.Table("Chauffeurs"); this.Id(c => c.Id, c => { c.Generator(Generators.Native); c.Type(NHibernateUtil.Int64); c.Column("Id"); c.UnsavedValue(0); }); this.Property(c => c.Naam); this.Property(c => c.Voornaam); this.Property(c => c.GeboorteDatum); this.Property(c => c.RijksRegisterNummer); this.Property(c => c.TypeRijbewijs); this.Property(c => c.Actief); this.Property(c => c.AdresId); this.Property(c => c.TankkaartId); } } } Using this mapping i could insert the nested object, by using an existing child address ID. How I inserted this via a post: { "Naam" : "Bart", "Voornaam" : "Jannsses", "AdresId" : 4, "GeboorteDatum" : "1979-04-25", "RijksRegisterNummer" : "999-888-7777", "TypeRijbewijs" : 1, "Actief" : true } How I would like to insert it in the future: { "Naam" : "Bart", "Voornaam" : "Jannsses", "Adres" : { "Straat": "Boomstraat", "Nummer": 1, "Stad": "Gent", "Postcode": 9000 }, "GeboorteDatum" : "1979-04-25", "RijksRegisterNummer" : "999-888-7777", "TypeRijbewijs" : 1, "Actief" : true } Note that the ID of an address is auto generated at DB level. Any help would be much appreciated. Kind regards A: You would need to add ManyToOne mapping in your ChauffeurMap class this.ManyToOne(x => x.Adres , m => { m.Column("AdresId"); // AdresId can be insert and update m.Update(true); m.Insert(true); m.Cascade(Cascade.None); m.Fetch(FetchKind.Join); m.NotFound(NotFoundMode.Exception); m.Lazy(LazyRelation.Proxy); m.ForeignKey("AdresId"); }); And you would also need additional mapping class for Adres as AdresMap. I hope you already have it. If not, please add it as below - public class AdresMap : ClassMapping<Adres> { public AdresMap() { this.Table("Adres"); //Your table name this.Id(c => c.Id, c => { c.Generator(Generators.Native); c.Type(NHibernateUtil.Int64); c.Column("Id"); c.UnsavedValue(0); }); Set(x => x.Chauffeurs, c => { c.Key(k => { k.Column("Id"); k.ForeignKey("AdresId"); }); c.Inverse(true); c.Cascade(Cascade.None); }, r => r.OneToMany(o => { })); this.Property(x => x.Straat ); // ... other properties } }
{ "language": "en", "url": "https://stackoverflow.com/questions/65020398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Calling consecutive DLL's from {tmp} in Inno Setup I want to use a DLL (lets say 'A.dll'), that I created in Delphi, within my Inno Setup script that uses a bunch of other DLLs ('B.dll', 'C.dll', ...). All these dll-files are included in the Files-section as follows: [Files] Source:"libs\*.dll"; Flags: dontcopy In the code section I declare methods of the used DLL as described in the Online help and add the loadwithalteredsearchpath flag: procedure MyMethod; external 'MyMethod@files:A.dll,B.dll,C.dll stdcall loadwithalteredsearchpath'; When the installer starts, all needed files are copied into the temporary directory the constant {#tmp} is pointing to. However, MyMethod starts its execution just fine (checked it with some Showmessages), but the whole thing breaks, when the method tries to use the other DLLs. Next to the temporary folder from {#tmp} two other temporary directories are created during the setup (all with the 'IS-xxxxx.tmp' pattern), which contain 'setup.tmp' (which is not occurent in {#tmp}). When I now manually copy all the DLL's (besides A.dll) into both these other directories at the beginning of the setup, then everything works fine. But when I let it run only as defined in my script, then A.dll doesn't seem to find the other libraries. Does anybody know, why this is happening and how I can fix this? This seems to be a problem with the PATH, but I thought that Inno Setup adds the tmp-dir into the PATH, so that the setup can find the DLL's (which it does, but strangely only for A.dll). Thanks in advance for your help! :) EDIT: The actual error I get, when I use one of the 'foreign' DLL's (B.dll, C.dll, ...) by calling one of their methods inside of A.dll during the Inno Setup: Access violation at address 00408CC7 in module 'setup.tmp'. Read of adress 00000000. EDIT 2: I think I realized why my problem is happening: With ExtractFilePath (first link) in my own A.dll I discovered, that the setup.exe is not executed within {tmp} but one of the other two temporary dirs that are creating at the beginning of the setup. It also appears, that not {tmp} but the current working dir (thus the dir, where inno is executed) is added to the library search path (second link). This would explain, why the other libraries (B.dll, C.dll, ...) can only be accessed when manually copying to this other temp dir. I suppose that A.dll is extracted and called from {tmp} without a problem, because it is referred as the "main-library" in the external command. I thought that with loadwithalteredsearchpath the other libraries could remain in the same directory, but that doesn't seem to work. But how can I fix this now in an nifty way? I think I could copy the DLLs manually to the setup-path (by using ExtractFilePath(ParamStr(0)), after they have been extracted to {tmp} to solve the problem. But this seems to be a dirty workaround as using DLLs in Inno Setup is supposed to work differently. * *How to get path where is temporary Inno setup file is located *External function calls with multiple dependent DLLs A: Well I'm not sure if you only load the DLLs without registering them in the system registry. However your first EDIT shows an error triggered by attempts to access some stack of the registry, so I assume you are. In that case, I simply use a batch file (which fires commands in the CMD console) to register my DLLs as I would one by one: @echo off echo Registering DevExpress DLLs %~dp0gacutil.exe /i %~dp0DevExpress.BonusSkins.v12.1.dll %~dp0gacutil.exe /i %~dp0DevExpress.Charts.v12.1.Core.dll So, I place this in the RUN section of the iss script: [Run] Filename:C:\myFolder\RegisterDevExpress.bat" Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/17469007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Clone or edit local Minimongo collection I'd like to clone a minimongo collection so I can do some calculations, get a result, then push those results back to the server. Assuming this is a suitable pattern, how best can I clone a minimongo collection? It appears that in the object no longer has a ._deepcopy (1.0.4), and attempting an EJSON.clone exceeds the callstack size for even tiny collections. Underscore's _.clone() only copies by reference. Alternatively, I could just edit the local collection via collection._collection.update. But if that's the case, what would happen if on the off chance the server updated or removed a doc while it was processing? I watched this video, but am still unclear on that scenario: https://www.eventedmind.com/feed/meteor-how-does-the-client-synchronize-writes-with-the-server A: The why behind your pattern escapes me but one solution could be to define a null collection, (docs) copy the records you need to that, do your work, and then copy back the results into the original collection for automatic sync back to the server. myLocalCollection = new Mongo.Collection(null);
{ "language": "en", "url": "https://stackoverflow.com/questions/29186524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Input field validation in angular using formControl I want to tag an error message when the user touches on that particular field and and then clicks outside without entering anything. I am not sure why the below code doesnt work . Guys Any inputs..I need some serious suggestions pls. <form [formGroup]="personalInfoForm" novalidate [ngClass]="{submitted: formSumitAttempt}"> <div class="row"> <div class="col-lg-6"> <label for="firstName" class="userID control-label">First Name</label> <input type="text" class="form-control" id="firstName" placeholder="Name" formControlName="firstName" [(ngModel)]="firstName" required> <div *ngIf ="firstName?.touched && firstName?.errors" class="alert alert-danger"> <div [hidden]="!firstName.errors.required"> Name is required </div> </div></div></div> A: in your component personalInfoForm=new formGroup({ firstname:new FormControl('',[Validators.required]) }) your HTML <form [formGroup]="personalInfoForm" novalidate [ngClass]="{submitted: formSumitAttempt}"> <div class="row"> <div class="col-lg-6"> <label for="firstName" class="userID control-label">First Name</label> <input type="text" class="form-control" id="firstName" placeholder="Name" formControlName="firstName" required> <div *ngIf ="personalInfoForm.controls['firstname'].hasError('required')" class="alert alert-danger"> Name is required </div> </div></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/50309252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook Share Link - Share To A Page On Mobile I am wondering if anyone has a solution to a small but major problem for me. I have coded a share button for Facebook using sharer.php, however, if the button is pressed on a mobile device Facebook isn't giving the user the option to share to a page or a group, it only will post to their personal profile. Unlike on desktop/laptop you get a drop down which gives the option, like in the attached images. So a) is there a way around this b) is there a way to set Share To A Page as default? You can see on the first image on my iPhone there is no option to change where it's shared.... A: to share a an url, website, in facebook u can use: https://www.facebook.com/sharer.php?u=URLHERE so, to get the thumbnail, title and the excerpt, to show properly in anywhere, u need to set in ur website as meta-tags inside head tags. like: <!-- FB Share --> <meta property="og:url" content="URLHERE" /> <meta property="og:type" content="website" /> <meta property="og:title" content="TITLE HERE" /> <meta property="og:description" content="DESC HERE" /> <meta property="og:image" content="URLIMAGE" /> <meta property="og:image:width" content="800" /> <meta property="og:image:height" content="600" /> <!-- FB Share -->
{ "language": "en", "url": "https://stackoverflow.com/questions/42439692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I retrieve a specific field from a map in Cloud Firestore using Android? This is a part of data saved in firebase Firestore: How can I get (fName) from (newFriend0) in Java? This is part of the code. It gave the entire map. I want just a specific field such as ("jem" for (fName)) Map<String, Object> map = document.getData(); for (Map.Entry<String, Object> entry : map.entrySet()){ if (entry.getKey().equals("Friends")){ f=document.getString("FName");////not worked Log.d("TAG", entry.getValue().toString()); } } A: Edit: July, 16th 2201 As a matter of fact, there is a simpler way of getting that data: * *How to map an array of objects from Cloud Firestore to a List of objects? Seeing that your code is in Java, please see the solution below: FirebaseFirestore.getInstance().collection("coll").document("9999").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document.exists()) { Map<String, Object> friendsMap = document.getData(); for (Map.Entry<String, Object> entry : friendsMap.entrySet()) { if (entry.getKey().equals("Friends")) { Map<String, Object> newFriend0Map = (Map<String, Object>) entry.getValue(); for (Map.Entry<String, Object> e : newFriend0Map.entrySet()) { if (e.getKey().equals("newFriend0")) { Map<String, Object> fNameMap = (Map<String, Object>) e.getValue(); for (Map.Entry<String, Object> dataEntry : fNameMap.entrySet()) { if (dataEntry.getKey().equals("fName")) { Log.d("TAG", dataEntry.getValue().toString()); } } } } } } } else { Log.d("TAG", "No such document"); } } else { Log.d("TAG", "get failed with ", task.getException()); } } }); The result in your logcat will be: jem Didn't see the name of your collection in the screenshot, so I named it simply coll but you should definitely change it to the correct one. A: Basically you need to perform 2 steps, retrieve the document data with one of the provided libraries and then manipulate the resulting map object with the means of your programming language. Here is a simple Nodejs example getting 'fName': let docRef = db.collection('<collection_name>').doc('9999'); docRef.get() .then(doc => { if (!doc.exists) { console.log('No such document!'); } else { console.log('Document data:', doc.data().Friends.newFriend0.fName); } }) .catch(err => { console.log('Error getting document', err); }); A: Firestore document is in JSON format thus we can just convert the documentSnapshot.getData() to String first then to JSON so it will be more easier to access the Map objects data without needing too many loops/iteration. Another way is to do it like this documentSnapshot.getData().get("get_only_map_key_to_be_converted_as_JSON") convert it to string then to JSON as well. The possible remaining problem is if you store url in your document's map object which will have a problem as those link needs to be unescaped to become a valid JSON though I haven't tried that scenario yet in Android Java.
{ "language": "en", "url": "https://stackoverflow.com/questions/60421605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Table in Markdown doesn't show I want to do a simple latex table in my markdown raport: --- title: "Title" output: html_document --- ## Table \begin{table}[ht] \centering \begin{tabular}{rrrr} \hline & chisq & df & p \\ \hline mu & 0.889 & 1 & 0.346 \\ sigma & 0.810 & 1 & 0.368 \\ Q & 0.663 & 1 & 0.415 \\ P & 0.663 & 1 & 0.415 \\ \hline \end{tabular} \end{table} but my table does not show up. There is no error so i don't know what i'm doing wrong. Do i need some brackets or sth like that?
{ "language": "en", "url": "https://stackoverflow.com/questions/61313598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Understanding source of connection time-out exception I'm trying to connect to some URL through proxy: Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("113.193.248.211", 3128)); HttpURLConnection conn = (HttpURLConnection) new URL(urlString).openConnection(proxy); But I'm getting exception: java.net.ConnectException: Connection timed out: connect How I can know what exactly throw this exception - connection to proxy server or connection to url defined in constructor of URL class?
{ "language": "en", "url": "https://stackoverflow.com/questions/30447005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How I can auto login with SwiftyDropbox? I have an app with SwiftyDropbox that function correctly, but I need to insert email and password for Dropbox every time that I use the app. The app it's only for my use, it's not a security problem if the app auto-login in my account. I don't find examples or documentation to make an auto-login with SwiftyDropbox. It's possible? A: While the Dropbox API was designed with the intention that each user would link their own Dropbox account, in order to interact with their own files, it is technically possible to connect to just one account. We generally don't recommend doing so, for various technical and security reasons, but those won't apply if you're the only user anyway. So, there are two ways to go about this: 1) Implement the normal app authorization flow as documented, and log in and authorize the app once per app installation. The SwiftyDropbox SDK will store the resulting access token for you, which you can programmatically re-use after that point each time using authorizedClient. 2) Manually retrieve an access token for your account and hard code it in to the app, using the DropboxClient constructor shown here under "Initialize with manually retrieved auth token".
{ "language": "en", "url": "https://stackoverflow.com/questions/51501107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL exact match acting like LIKE Got an interesting problem with a simple MySQL query. I'm trying to do an exact match on the id field. SELECT id FROM tablename WHERE id = '23' Returns id: 23 All is well and good until I do: SELECT id FROM repairs WHERE id = '23abcd' Returns id: 23 Why on earth would it do this?! id field is int(10) and the database is MyISAM utf8_general_ci. Any thoughts? A: Your database has int field it will truncate the characters and only consider the numbers that's why you are getting 23 as return id. A: You are quoting the number in your query, so MySQL must convert it from a string to a number. When it does that, it is using only the numeric part of the string. I don't think the behavior is completely appropriate ( "23abcd".ToInt() should be NULL, I think), but that's what it does. A: As Fakhruddin said that int field truncates the value of characters. That's right. But you can prevent wrong values from being inserted in the first place by setting the STRICT_ALL_TABLES mode mysql> SET sql_mode = 'STRICT_ALL_TABLES'; One more thing is that you need to store your id as character strings(VARCHAR) if they contain letters.
{ "language": "en", "url": "https://stackoverflow.com/questions/17504439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to filter an R data.table by index and condition Please have a look at the following sample code. DT <-data.table(1:15,0,rbinom(15,2,0.5)) I can filter by condition DT[V3 == 1,] or select rows by index DT[1:5,]. How can I do both? In the following code, the sequence of the indexed rows seems to by ignored: DT[V3 == 1 & 1:5] I could do DT[1:5,][V3 == 1], but then, for example, I wouldn't be able to modify the filtered rows: DT[1:5,][V3 == 1, V2 := 1] This only works with the following workaround: DT[V3 == 1 & DT[,.I <= 5], V2 := 1] However, this looks too data.frame-ish to me. Is there a more elegant way and why does DT[V3 == 1 & 1:5] not work? A: We can try DT[V3==1 & 1:.N %in% 1:5, V2 := 1] Or another option is DT[intersect(which(V3==1), 1:5), V2 := 1] Benchmarks set.seed(24) DT <- data.table(1:1e6, 0, rbinom(1e6, 2, 0.5)) DT1 <- copy(DT) DT2 <- copy(DT) OP's version system.time({ DT[V3 == 1 & DT[,.I <= 5], V2:= 1] }) #user system elapsed #0.08 0.00 0.08 Modified options system.time({ DT1[V3==1 & 1:.N %in% 1:5, V2 := 1] }) # user system elapsed # 0.14 0.00 0.14 system.time({ DT2[intersect(which(V3==1), 1:5), V2 := 1] }) # user system elapsed # 0.05 0.00 0.05 A: Here's a faster way for @akrun's example: set.seed(24) DT <- data.table(1:1e6, 0, rbinom(1e6, 2, 0.5)) DT1 <- copy(DT) DT2 <- copy(DT) library(microbenchmark) microbenchmark( DT1[which(V3[1:5]==1L), V2:= 1], DT2[intersect(which(V3==1), 1:5), V2 := 1] , times = 1, unit = "relative" ) # Unit: relative # expr min lq mean median uq max neval # sequential 1.00000 1.00000 1.00000 1.00000 1.00000 1.00000 1 # set_ops 55.43582 55.43582 55.43582 55.43582 55.43582 55.43582 1 It's "sequential" in the sense that we subset by index before evaluating the condition. The generalization is cond = quote(V3 == 1) indx = 1:5 DT[ DT[indx, indx[eval(cond)]], V2 := 1] # or set(DT, i = DT[indx, indx[eval(cond)]], j = "V2", v = 1)
{ "language": "en", "url": "https://stackoverflow.com/questions/35840406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: System.DirectoryServices.AccountManagement bootstrapping myself I'm trying to bootstrap myself up on the System.DirectoryServices.AccountManagement namespace in order to solve another issue I'm having. In net i want to toggle the "ChangePasswordOnNextLogon" flag in ad and this namespace made it look easy. So I tried using it with the same users and passwords that I use to login using the AdMembershipProvider. PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, "10.1.XXX.XXX", "DC=XXXXXXXX,DC=ORG", ContextOptions.SimpleBind, AUserThatWorks, APasswordThatWorks); UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, AdUserName); // we need to see if they can authenticate before changing password,so we have to turn this off manually. - EWB oUserPrincipal.RefreshExpiredPassword(); bool b = oPrincipalContext.ValidateCredentials( AdUserName, AdPassword ); if (!b) oUserPrincipal.ExpirePasswordNow(); return b; But when it gets to FindByIdentity I get a "bad user or password" error. Since the user works elsewhere, I figure it's gotta be one of the other parameters to get principal context. Anyone got any Hints for me? I tried putting LDAP infront of the URL but then it failed to connect. I'm stumped. Thanks, Cal- A: Try simplifying your PrincipalContext line: PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, "XXXXXX.org", AUserThatWorks, PasswordThatWorks); This assumes your domain is XXXXXXX.org. You can also try putting your domain in front of your username: "XXXXXX.org\username".
{ "language": "en", "url": "https://stackoverflow.com/questions/5587442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to send a string to url? I'm setting up a barcode reader app, got 3 tab bar item and one of them "SCAN" tab and another one of them is "WEBVIEW" tab. When user scan the barcode or qr, it's giving a string and going to webview's url. I want to send this string to url and open the webview tab. Can you help me with this problem ? if (metadataObjects.count > 0 && metadataObjects.first is AVMetadataMachineReadableCodeObject) { let scan = metadataObjects.first as! AVMetadataMachineReadableCodeObject let alertController = UIAlertController(title: "Barkod Tarandı", message: scan.stringValue, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "TAMAM", style: .default, handler:nil)) present(alertController, animated: true, completion: nil) if(scan.stringValue != nil) { if let aString = URL(string: "" + ("http://www.truebilisim.com/myiphone/true/mymagazaplus/barkod.php?barkod=\(scan.stringValue)")) { webalani.loadRequest(URLRequest(url: aString)) } } } A: Use the NSURL it must work. webalani.loadRequest(NSURLRequest(URL: NSURL(string: "aString")!)) And make sure your this line must be NSURL too if let aString = URL(string: "" + ("http://www.truebilisim.com/myiphone/true/mymagazaplus/barkod.php?barkod=\(scan.stringValue)")) {
{ "language": "en", "url": "https://stackoverflow.com/questions/55743237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to sanitize CSV input with one-space strings? So here's the situation: * *I'm reading CSV files where the majority of the time, empty cells are just empty strings. Some files that come in the same set, for whatever reason, have one-space strings in 'empty cells' instead of empty strings. *I'm using csv's DictReader to read from these files (with ',' as the delimiter) and it will automatically convert empty strings to None type values prior to my inserting them into a PostgreSQL db. *I tried registering a Dialect object that set skipinitialspace=True, but now they remain empty strings which, unlike None, is still an invalid input for SQL table columns that I have set to integer values (so I'm guessing DictReader converts empty strings to None prior to removing the leading whitespace). How can I get around this? Disclaimer: I could reach a solution by just converting all the one-space-strings to None types myself after I have read the values and have the row's dict from DictReader, but it seems clunky and I'd prefer a more elegant solution if possible. Example normal csv foo_id,foo_text,foo_value 1,'hello',4 3,,2 Example problem csv bar_id,bar_text,bar_value 1,'hello',4 3, ,2 Example csv read script with open('foo.txt') as csv_file: csv.register_dialect('example_dialect', delimiter=',', skipinitialspace=True) gtfsreader = DictReader(csv_file, dialect='example_dialect') for row in gtfsreader: print(row) A: Never figured out a way to deal configure DictReader to do this for me, but in the meantime, I did wind up just manually sanitizing each row with this helper function: def __sanitize__(row): for key, value in row.items(): if value in ('', ' '): row[key] = None return row Still hope someone can come along with a sexier answer!
{ "language": "en", "url": "https://stackoverflow.com/questions/32489686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Kubernetes rolling update for same image Document of kubernetes says to do rolling update for a updated docker image. In my case I need to do rolling update for my pods using the same image. Is it possible to do rolling update of a replication controller for a same docker image? A: In my experience, you cannot. If you try to (e.g., using the method George describes), you get the following error: error: must specify a matching key with non-equal value in Selector for api see 'kubectl rolling-update -h' for help. The above with kubernetes v1.1. A: Sure you can, Try this command: $ kubectl rolling-update <rc name> --image=<image-name>:<tag> If your image:tag has been used before, you may like to do following to make sure you get the latest image on kubernetes. $ docker pull <image-name>:<tag>
{ "language": "en", "url": "https://stackoverflow.com/questions/34035081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: incorrect output data after the second index So im doing this homework for my programming class, but the data output doesnt match with the theoretical data output that it shoud be printing and it gives me a big number. #include <stdio.h> #include <stdlib.h> #include <stdbool.h> void menu(int *); void CalculoVentas(float ventas[50][7], float ventasXproductos[50], int); void PromedioDiario(float promedioXdia[7], float ventas[50][7], int); int main() { char ciclos; int sel, cont = 0, i = 0; float ventas[50][7], ventasXproductos[50], promedioXdia[7]; bool lectura = false; while(sel != 5) { menu(&sel); system("cls"); switch(sel) { case 1: printf("Hay Productos?: S/N "); fflush(stdin); scanf("%c", &ciclos); while(ciclos == 's' || ciclos == 'S' && cont < 50) { for(i=0;i<7;i++) { do { printf("Teclea los ingresos generados por el producto %d el dia %d: ", cont+1, i+1); scanf("%f", &ventas[cont][i]); }while(ventas[cont][i] < 0); printf("\n\n"); } cont++; system("cls"); printf("Hay Productos?: S/N "); fflush(stdin); scanf("%c", &ciclos); lectura = true; } break; case 2: if(lectura == false) printf("Primero ingresa los datos del producto!!!\n"); else CalculoVentas(ventas, ventasXproductos, cont); break; case 3: if(lectura == false) printf("Primero ingresa los datos del producto!!!\n"); else PromedioDiario(promedioXdia, ventas, cont); break; case 4: if(lectura == false) printf("Primero ingresa los datos del producto!!!\n"); else printf("%35s\n", "Total de ventas"); for(i=0;i<cont;i++) printf("%d %.2f\n", i+1, ventasXproductos[i]); printf("\n\n\n\n"); printf("%35s\n", "Promedio de ventas por dia"); for(i=0;i<7;i++) printf("Dia %d: %.2f\n", i+1, promedioXdia[i]); printf("\n\n\n\n"); break; } } } void menu(int *seleccion) { printf("%20s\n%s\n%s\n%s\n%s\n%s\n", "Menu de opciones", "1.-lectura de datos", "2.-calculo de ventas por producto", "3.-promedio de ventas de cada dia", "4.-imprimir resultados", "5.-salir"); do{ printf("Seleccione una opcion: "); scanf("%d", &*seleccion); }while(*seleccion <= 0 || *seleccion > 5); } void CalculoVentas(float ventas[50][7], float ventasXproducto[50], int cont) { //realizar el calculo de ventas por productos, nada más es la suma de las ventas de todos los dias por producto int i,j; for (i = 0 ; i<cont ; i++) for (j = 0 ; j < 7 ; j++) ventasXproducto[i] = ventasXproducto[i] + ventas[i][j]; } void PromedioDiario(float promedioXdia[7], float ventas[50][7], int cont) { int i,j; for(i=0;i<7;i++) { for(j=0;j<cont; j++) promedioXdia[i] = promedioXdia[i] + ventas[j][i]; promedioXdia[i] = promedioXdia[i]/cont; } } the output is something like this, I try to type simple data so i can know easly if its wrong Total de ventas 1 70.00 2 5103881324019006800000000000000000.00 3 210.00 4 280.00 Promedio de ventas por dia Dia 1: 25.00 Dia 2: 25.00 Dia 3: 25.00 Dia 4: 1291386862541487300000000000000000.00 Dia 5: 25.00 Dia 6: -1.#R Dia 7: 25.00 when i was trying to get help someone told me that i might be not initializing correctly the variables but i couldnt find any issue with that A: When the program begins, sel is uninitialized and contains a garbage value. This garbage value is used in the while condition on its first iteration while(sel != 5) and as such invokes Undefined Behaviour. You must restructure your loop to not read this uninitialized value, or simply initialize sel (to something other than 5). Similarly, the contents of ventas, ventasXproductos, and promedioXdia are all uninitialized as well. This means statements such as ventasXproducto[i] = ventasXproducto[i] + ventas[i][j]; /* ... and ... */ promedioXdia[i] = promedioXdia[i]/cont; will be operating with garbage values to start. You can fix this by initializing your arrays: float ventas[50][7] = { 0 }, ventasXproductos[50] = { 0 }, promedioXdia[7] = { 0 }; You should not ignore the return value of scanf. You should always check that its return value is the expected number of successful conversions, otherwise you will find yourself operating on incomplete data. /* An example */ if (2 != scanf("%d%d", &num1, &num2)) { /* handle failure */ } (Better yet: avoid using scanf, and use fgets and sscanf to read and parse lines of input.) You should clarify this expression by adding more parenthesis, otherwise you will run into issues with operator precedence: while ((ciclos == 's' || ciclos == 'S') && cont < 50) case 4 of the switch has misleading indentation. Only the first statement with the call to printf is contained within the else block. It is read as: if(lectura == false) printf("Primero ingresa los datos del producto!!!\n"); else printf("%35s\n", "Total de ventas"); for(i=0;i<cont;i++) printf("%d %.2f\n", i+1, ventasXproductos[i]); /* ... */ Your lectura flag will not protect you from operating on incomplete data if this is selected. Enclose the code with curly braces: case 4: if(lectura == false) { printf("Primero ingresa los datos del producto!!!\n"); } else { printf("%35s\n", "Total de ventas"); for(i=0;i<cont;i++) printf("%d %.2f\n", i+1, ventasXproductos[i]); /* ... */ } break; Note that in &*seleccion, & and * balance each other out. This resolves to the same value as just writing seleccion would. Note that fflush(stdin); is also (technically) Undefined Behaviour, and should not be relied upon.
{ "language": "en", "url": "https://stackoverflow.com/questions/74176560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to close a window opened using browser.windows.create()? I cannot find any questions/answers that address this issue. Sorry if I have missed something. I am just getting started with WebExtensions. I have a form that is displayed in a window that I open in my background.js script using windows.create();. I cannot figure out how to close that window (other than manually clicking the close box). The window is created and correctly displays my form. I can even submit the form. But I cannot get the window to close. I have even tried injecting a content script into the form page - I cannot close it from there either. I have tried attaching a handler to the click event of a button, with no luck. It is my understanding that only the script that creates the window can close it. But I cannot figure out, or find by searching online, how I would do that in my browserAction background script (which is where the window is created)? I am running Firefox 51 on Debian. Here is the code that creates the window. background.js var formUrl = 'http://example.com/api/test' chrome.browserAction.onClicked.addListener( function(tab) { chrome.tabs.query({"active": true, "currentWindow": true}, function(tabs) { var target = tabs[0].url; if (target.substr(0,4) == 'http') { var encUrl = escape(target); var newUrl = formUrl + '?default=' + encUrl; w = chrome.windows.create({ url: newUrl, width: 775, height: 350, type: 'popup' }); } else { console.log("Only http(s) pages can be processed at this time."); } }); } ); A: The API call windows.remove() is specifically for closing a window. You will need the windowId, which is available as the id property within the windows.Window Object which is passed to the callback/resolve function for windows.create(). You do not need to call windows.remove() from the same script which opened the window. Any script with access to that API can close the window. A: You can remove a window created by an extension in Firefox from a "dismiss" button this way: GetEl('dismiss').addEventListener('click',function(e) { browser.windows.getCurrent().then(F2); }); function F2(info) { return browser.windows.remove(info.id); } // F2 (GetEl returns the element node for a given id string.)
{ "language": "en", "url": "https://stackoverflow.com/questions/42585856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Doesn't remove hide class after view render In my Rails 5 app I've got a registration form where user is able to chose registration_type from dropdown list. When selects the Caregiver option, an additional field is shown on the form - it's handled by below registrant.js file: $(document).on('focusout change', "#registrant_registration_attributes_registered_as", toggle_caregiver_fields_on_ready); function toggle_caregiver_fields_on_ready(){ var caregiverSectionElement = $("#registrant_registration_attributes_registrant_id"), register_as = $("#registrant_registration_attributes_registered_as"), caregiver = (register_as.val() == 'caregiver'); if (caregiver) { $('.patient-caregiver-section').removeClass('hidden'); $('#patient-search-results').removeClass('hidden'); } else { $('.patient-caregiver-section').addClass('hidden'); $('#patient-search-results').addClass('hidden'); } } It works pretty well until the form throws an error which causes render :new from the controller create action, like below: registrants_controller.rb def create @registrant = Registrant.new(parse_post_params) if @registrant.save! #some logic (...) @registrant.add_special_status_to_history(current_login.user) @caregiver_patient.save! if @patient.present? redirect_to registrant_path(@registrant), notice: 'Registrant Added' else render :new end end After the :new page was rendered, the JS file didn't seem to work - in chrome console I dropdown is selected: <select class="form-control required" aria-required="true" name="registrant[registration_attributes][registered_as]" id="registrant_registration_attributes_registered_as"><option value=""> Please select </option> <option selected="selected" value="caregiver">Caregiver</option> <option value="patient">Patient</option></select> But the class patient-caregiver-section still has a hidden value: <div class="patient-caregiver-section hidden"> <div id="add-patient"> <div class="form-group"><label class="non-bold-label pull-left" for="registrant_registration_attributes_patient_to_caregiver"> Patient Added to Caregiver </label> </div> </div> </div> How to force JS file to remove this class also when new action was rendered?
{ "language": "en", "url": "https://stackoverflow.com/questions/71566169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IOException was unhandled - Cannot locate resource app.xaml In one of my WPF projects I get this error when I open the solution and start it up when debugging it. If I rebuild the solution and start it again, the error goes away. I have implemented command line support for application by removing the StartUpUri in App.xaml using this: WPF Command Line How do I get rid of this annoying error? Using VS 2010 .net 4.0 System.IO.IOException was unhandled Message=Cannot locate resource 'app.xaml'. Source=PresentationFramework StackTrace: at MS.Internal.AppModel.ResourcePart.GetStreamCore(FileMode mode, FileAccess access) at System.IO.Packaging.PackagePart.GetStream(FileMode mode, FileAccess access) at System.IO.Packaging.PackagePart.GetStream() at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator) at ESPS3.ServerSchemaUtility.App.InitializeComponent() in e:\ESP3.0\InternalTools\ServerSchemaUtility\ServerSchemaUtility\App.xaml:line 1 at ESPS3.ServerSchemaUtility.App.Main() in E:\ESP3.0\InternalTools\ServerSchemaUtility\ServerSchemaUtility\obj\x86\Debug\App.g.cs:line 0 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: A: I have seen that error before, when porting from VS 2005 to 2008. Never seen in 2010. For some reason, the build settings for app.xaml were lost. So you can check the the properties of app.xaml. The correct settings are shown in the image attached. On the other hand, if you are working with MVVC, it can be a different cause, like explained here: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/39d7a4dd-9034-4ae8-843c-ccd4940ba51c/ A: I have the same situation as specified in question (VS2010). Yesterday, project worked without problems. Today, with no changes to the code, project reported error. In my case after Menu -> Build -> Clean Solution project run without error. A: Changing Windows 10 display language from English to German (the app was originally developed on a German system) fixed it for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7126147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Formatting Phone number with +1 with pandas.Series.replace I can't find a solution online and I know this should be easy but I can't figure out what is wrong with my regex: here is my code: df = pd.DataFrame({'Company phone number': ['+1-541-296-2271', '+1-542-296-2271', '+1-543-296-2271'], 'Contact phone number': ['15112962271', None,'15312962271'], 'num_specimen_seen': [10, 2,3]}, index=['falcon', 'dog','cat']) df['Contact phone number'] = df['Contact phone number'].str.replace('^\d{11}$', r'\+1-\d{3}-\d{3}-\d{4}') desired output of df['Contact phone number']: falcon +1-511-296-2271 dog None cat +1-531-296-2271 It is always 11 digits with no spaces or special characters. Thanks! A: You can use .str.extract, convert each row of results to a list, and then use .str.join (and of course concatenate a + at the beginning): df['Contact phone number'] = '+' + df['Contact phone number'].dropna().astype(str).str.extract(r'(\d)(\d{3})(\d{3})(\d{3})').apply(list, axis=1).str.join('-') Output: >>> df Company phone number Contact phone number num_specimen_seen falcon +1-541-296-2271 +1-511-296-227 10 dog +1-542-296-2271 NaN 2 cat +1-543-296-2271 +1-531-296-227 3 A: You can use df['Contact phone number'] = df['Contact phone number'].str.replace(r'^(\d)(\d{3})(\d{3})(\d+)$', r'+1-\1-\2-\3-\4', regex=True) Details: * *^ - a start of string *(\d) - Group 1 (\1): a digit *(\d{3}) - Group 2 (\2): three digits *(\d{3}) - Group 3 (\3): three digits *(\d+) - Group 4 (\4): any one or more digits (use \d{4} if you need to match exactly four next digits) *$ - end of string. Output: >>> df['Contact phone number'] falcon +1-1-511-296-2271 dog None cat +1-1-531-296-2271 See the regex demo.
{ "language": "en", "url": "https://stackoverflow.com/questions/71516642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to enable content security policy to selective http patterns in spring security My spring security config looks like: <http pattern="/*/yyy/**" security="none" /> <http pattern="/*/zzz/**" security="none"/> <http create-session="stateless" use-expressions="true"> <csrf disabled="true" /> <intercept-url method="GET" pattern="/*/api/products" access="xxxx" /> <http-basic entry-point-ref="customBasicAuthenticationEntryPoint" /> </http> Now, for the http pattern with security="none" above, I want to enable Content Security Policy (CSP) for that. As long as I keep it security="none", I don't think I can apply CSP to it. the header to enable CSP in spring security is like: <headers> <header name="Content-Security-Policy" value="default-src 'self'"/> </headers> Now, I want to apply this header only to the first two http patterns where I have security="none" right now and not to the rest of the URLS I have added in the next http block. I just could not find a way to do it. Is it possible? Can someone please suggest? I don't need to define entry-point-ref to these first two patterns. But, removing security="none" kind of forces me to define one for it. Please note that all I want is to be able to enable CSP for those selected patterns and that is all. Please help! Update: A: Using security="none" means that security is not applied to the URLs, so the statement of adding a Content Security Policy with Spring Security to URLs mapped with security="none" is contradictory. I'm guessing that you want to allow any user access to those URLs. If that is the case, you can easily use the permitAll expression. Then, you can specify which URLs are have the Content Security Policy set using DelegatingRequestMatcherHeaderWriter. For example, using Spring Security 4+ you can use: <http> <intercept-url pattern="/*/yyy/**" access="permitAll" /> <intercept-url pattern="/*/zzz/**" access="permitAll"/> <intercept-url method="GET" pattern="/*/api/products" access="xxxx" /> <headers> <header ref="headerWriter"/> </headers> <csrf disabled="true" /> <http-basic entry-point-ref="customBasicAuthenticationEntryPoint" /> <!-- ... --> </http> <beans:bean id="headerWriter" class="org.springframework.security.web.header.writers.DelegatingRequestMatcherHeaderWriter"> <beans:constructor-arg> <beans:bean class="org.springframework.security.web.util.matcher.OrRequestMatcher"> <beans:constructor-arg> <beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher" c:pattern="/*/yyy/**"/> <beans:bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher" c:pattern="/*/zzz/**"/> </beans:constructor-arg> </beans:bean> </beans:constructor-arg> <beans:constructor-arg> <beans:bean class="org.springframework.security.web.header.writers.StaticHeadersWriter" c:headerName="Content-Security-Policy" c:headerValues="default-src 'self'" /> </beans:constructor-arg> </beans:bean> Note that if you are using Spring Security 3, then you will need to explicitly list all the headers you want enabled (adding any explicit headers means only those headers are applied). For example: <headers> <cache-control /> <content-type-options /> <hsts /> <frame-options /> <xss-protection /> <header ref="headerWriter"/> </headers> You can find additional details on the differences in the migration guide.
{ "language": "en", "url": "https://stackoverflow.com/questions/34344840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Lock git branch : Bitbucket + hubot I have Bitbucket and using it I can lock git branches like so: https://confluence.atlassian.com/bitbucketserver/using-branch-permissions-776639807.html my question is how can I automate this task using Hubot script ? is there any API i can use? only found https://www.npmjs.com/package/hubot-bitbucket which can listen to pull and push requests A: found this url for managing branch permissions using API: https://developer.atlassian.com/static/rest/stash/2.12.1/stash-branch-permissions-rest.html
{ "language": "en", "url": "https://stackoverflow.com/questions/37374338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get a 1px border between columns? What is the preferred / cleanest method to draw a 1px border between two Susy grid items, in the center of the gutter? Susy creates a gutter by adding a margin-right to a grid item, so I can't simply add a border-right (like, for instance, you can do with Zen Grids, which creates gutters by applying half a gutter-width of padding on both sides). I guess it can be done using the with-grid-settings() mixin to define an alternative grid without gutters, but that feels like a messy solution. A: There isn't a great solution at the moment, but I hope to have one in the next major release. What you can do, is create your own math using the Susy functions (really the most powerful part of Susy). Something like this: .left-column { @include box-sizing(border-box); float: left; width: columns(2) + gutter()/2; padding-right: gutter()/2; margin-right: gutter()/2; border-right: 1px solid; }
{ "language": "en", "url": "https://stackoverflow.com/questions/14687838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are goals specified in the source code of a custom plugin? Are the permitted goals specified in the source code of a plugin? And can they be given any name we want as the developer of the plugin? Tried to find the goals supported by a plugin A: Yes, they are specified in the annotations in the source code.
{ "language": "en", "url": "https://stackoverflow.com/questions/57060000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MacOS Get trackpad pressure globally I'm trying to get MacBook Pro trackpad pressure with following code: CGEventRef eventTapCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef eventRef, void *refcon) { NSEvent *event = [NSEvent eventWithCGEvent:eventRef]; NSLog(@"%lld", (int64_t)CGEventGetIntegerValueField(eventRef, kCGMouseEventPressure)); // returns 0 NSLog(@"%lld", (int64_t)CGEventGetIntegerValueField(eventRef, kCGTabletEventPointPressure)); // returns 0 NSLog(@"%lld", (int64_t)CGEventGetIntegerValueField(eventRef, kCGTabletEventTangentialPressure)); // returns 0 NSLog(@"%f", [event pressure]); // Assertion failure return eventRef; } Do you have any idea how to do that? A: Pressure data is available if the device supports it (i.e. a force touch trackpads). Force touch trackpads have shipped on MacBooks since circa 2015. Force touch is also available on the Magic Trackpad. This blog post has a method for detecting force touch devices, although I didn't try it. My machine is a 2016 MacBook Pro with a force touch trackpad. I can get the pressure using this code: [self.window trackEventsMatchingMask:NSEventMaskPressure timeout:NSEventDurationForever mode:NSEventTrackingRunLoopMode handler:^(NSEvent * _Nonnull event, BOOL * _Nonnull stop) { NSLog(@"%f", event.pressure); }]; Output: 2018-02-09 18:16:10.986036-0800 forcetouch[4587:4164200] 0.437820 2018-02-09 18:16:10.993772-0800 forcetouch[4587:4164200] 0.457504 2018-02-09 18:16:11.001883-0800 forcetouch[4587:4164200] 0.476486 2018-02-09 18:16:11.010654-0800 forcetouch[4587:4164200] 0.494812 2018-02-09 18:16:11.017738-0800 forcetouch[4587:4164200] 0.512497 2018-02-09 18:16:11.028129-0800 forcetouch[4587:4164200] 0.529556 2018-02-09 18:16:11.033769-0800 forcetouch[4587:4164200] 0.546021 2018-02-09 18:16:11.042117-0800 forcetouch[4587:4164200] 0.561905 2018-02-09 18:16:11.049869-0800 forcetouch[4587:4164200] 0.577240 However, I see you are using an event tap. I tried your code, and when I check kCGMouseEventPressure I get 1. When I check event.pressure I also get 1. So I receive a value where you do not - I guess you do not have force touch hardware? But I do not receive the actual pressure value. I'm not sure how to get this using an event tap. This works for me on a 2016 MacBook Pro. Note that this machine has a force touch trackpad. I'm not sure what this will return on a machine without the force touch trackpad. However hopefully this gives you some more ideas. Force touch for developers NSEvent - pressure A: The snippet from the answer above: [self.window trackEventsMatchingMask:NSEventMaskPressure timeout:NSEventDurationForever mode:NSEventTrackingRunLoopMode handler:^(NSEvent * _Nonnull event, BOOL * _Nonnull stop) { NSLog(@"%f", event.pressure); }]; appears to be stopping the window from responding to any mouse events. I think it may be due to this quote from https://developer.apple.com/documentation/appkit/nswindow/1419727-trackevents Each event is removed from the event queue and then passed to the tracking handler I am not an expert in Cocoa's event architecture, but it occurs to me that trackEventsMachingTask intercepts the event. My workaround is this: NSEvent *(^monitor)(NSEvent *event) = ^NSEvent *(NSEvent *event) { NSLog(@"pressure = %f", event.pressure); return event; }; [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskPressure handler:monitor]; According to https://developer.apple.com/documentation/appkit/nsevent/1534971-addlocalmonitorforevents, addLocalMonitorForEventsMatchingMask's block argument is passed the pointer to the event, and as long as the block does not return nil, the event is dispatched regularly.
{ "language": "en", "url": "https://stackoverflow.com/questions/25803591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Whats wrong in this SPF syntax? I am not very familiar with SPF records so I need a bit of help setting up my SPF record correctly. Below is a record I created using online tutorials v=spf1 a mx ip4:192.186.236.104 include:_spf.google.com include:bmsend.com include:postbox.pidatacenters.com ~all when i check in http://mxtoolbox.com/SuperTool.aspx?action=spf%3apidatacenters.com%3a192.186.236.104&run=toolpage# it shows everything is right fraudmarc.com/spf-record-check/ in this website it shows an error like this enter image description here Give me the solutions Thanks in advance. A: A few things wrong here. The definitive SPF checker is Scott Kitterman's. It finds this error: PermError SPF Permanent Error: Unknown mechanism found: postbox.pidatacenters.com It's not clear why this is presented as this particular error because the syntax itself is valid, but you have a recursive definition - your SPF includes postbox.pidatacenters.com, but the SPF for that domain includes itself, which makes no sense. It also contains the google SPF, so you don't need to include that again. I suggest you set your SPF records to these. For pidatacenters.com: v=spf1 ip4:192.186.236.104 mx include:bmsend.com include:postbox.pidatacenters.com ~all you don't need the a clause in there because it resolves to the same IP as you already listed. It's polite to put ip clauses first as they are fastest to resolve for receivers, as they do not require DNS lookups. For postbox.pidatacenters.com: v=spf1 include:_spf.google.com ~all A: The reason why your getting the syntax error with that test is because any valid syntax checker authenticates the entire SPF Statement. Which means it has to test the SPF records of every included statement. When it checks the include for "postbox.pidatacenters.com" in the SPF syntax for pidatacenters.com, it will see this. v=spf1 include:_spf.google.com postbox.pidatacenters.com ~all Which is invalid. Anyway, you should follow Synchro's Advice and change the records to what he stated. Also testing with the site Synchro recommended is fine, but it relies on a lot of expert knowledge you might not have. You might think you're emailing one way, but you're really not. It's better to get a real live example using a reflector, just send an email to each of these and you'll get results back telling you if the SPF is correct, I always use multiple reflectors, to ensure things are accurate. mailtest@unlocktheinbox.com check-auth@verifier.port25.com
{ "language": "en", "url": "https://stackoverflow.com/questions/43176659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Keep Bootstrap Modal open when clicking on a link I have an Ajax Modal and have a number of links within the modal, however when I click on the links it will reload the page not the content within the Modal. How can I keep the Modal open? The code I am using: <div class="modal-header"> <a class="close" data-dismiss="modal">&times;</a> <h3>Modal header 2</h3> </div> <div class="modal-body"> //content <div class="modal-footer"> <a class="btn btn-primary" onclick="$('.modal-body > form').submit();">Save Changes</a> <a class="btn" data-dismiss="modal">Close</a> </div> $(document).ready(function() { // Support for AJAX loaded modal window. // Focuses on first input textbox after it loads the window. $('[data-toggle="modal"]').click(function(e) { e.preventDefault(); var url = $(this).attr('href'); if (url.indexOf('#') == 0) { $(url).modal('open'); } else { $.get(url, function(data) { $('<div class="modal hide fade">' + data + '</div>').modal(); }).success(function() { $('input:text:visible:first').focus(); }); } }); }); A: Chose to use an iFrame plugin https://github.com/Nikku/jquery-bootstrap-scripting/pull/69
{ "language": "en", "url": "https://stackoverflow.com/questions/16746454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Wait for next element in shared List in a C# concurrent producer / consumer pattern I have a List<object> listOfData; in C# that gets data every X minute from a getDataBackgroundWorker. I have another processDataBackgroundWorker that waits for the data from listOfData and processes it. How can I make sure that I only get unique data from listOfData ( new data is added always ) and how can I ask the processDataBackgroundWorker to pause when there is no new data in listOfData? A: List<> isn't a great choice in concurrency - there are out of the box alternatives, like ConcurrentBag, ConcurrentQueue which already have a lot of hard work done for you. Here's an implementation of a producer-consumer pattern, using a BlockingCollection implementation as per MSDN, * *The BlockingCollection is backed with a ConcurrentQueue, assuming that we are serially pull data in sequence on the consumer. *Methods which iterate over BlockingCollection block (with little overhead) until an item is available (i.e. your 'pause' is inherent - no need for a looped check with Thread.Sleeps on the consumer). *Termination is inherently built in, when the producer calls CompletedAdding *If you have more than one concurrent (competing) consumer, only one consumer will get an item, i.e. the duplication condition shouldn't be a concern (unless you mean the producer actually adds duplicates in the first place). var queue = new BlockingCollection<string>(new ConcurrentQueue<string>()); var producer = Task.Run(() => { // Produce some random messages, with delays in between queue.Add("Hello!"); Thread.Sleep(1000); queue.Add("World!"); Thread.Sleep(2000); Enumerable.Range(0, 100) .ToList() .ForEach(x => queue.Add(x.ToString())); queue.CompleteAdding(); }); var consumer = Task.Run(() => { while (!queue.IsCompleted) { try { Debug.WriteLine(queue.Take()); } catch (InvalidOperationException) { } } }); Task.WaitAll(producer, consumer);
{ "language": "en", "url": "https://stackoverflow.com/questions/23452872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery datepicker getMinDate '+1d' Once I have set the minDate property of a datepicker with the convenient string syntax $(elem).datepicker('option','minDate','+1d +3m'); how can I get the date object of the minDate? To help illustrate, there is a method $(elem).datepicker('getDate'); which returns the date that is entered in the input in the format of a date object. I would like the same thing but for datepicker('getMinDate'). There is an option like this $(elem).datepicker('option','minDate'); but this returns '+1d +3m' which is not helpful. I need the actual date object to compare with another date object. Any ideas? A: jQuery uses its _determineDate() function to calculate the minDate date object based on its attribute. I modified its behaviour and made a function. Note that it only deals with the "offset" type of values and nothing else. /* minDateAttr is the minDate option of the datepicker, eg '+1d +3m' */ function getMinDate(minDateAttr) { var minDate = new Date(); var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g; var matches = pattern.exec(minDateAttr); while (matches) { switch (matches[2] || 'd') { case 'd' : case 'D' : minDate.setDate(minDate.getDate() + parseInt(matches[1],10)); break; case 'w' : case 'W' : minDate.setDate(minDate.getDate() + parseInt(matches[1],10) * 7); break; case 'm' : case 'M' : minDate.setMonth(minDate.getMonth() + parseInt(matches[1],10)); break; case 'y': case 'Y' : minDate.setYear(minDate.getFullYear() + parseInt(matches[1],10)); break; } matches = pattern.exec(minDateAttr); } return minDate; } I originally planned on answering the following, but came up with a (better) solution - the one above. However, I'm going to include it, in case it's needed for debugging reasons etc. The _determineDate() function is technically availible for use, but it's not supposed to be used and may change in the future. Nevertheless, this would be how to use it: var minDateAttr = $(elem).datepicker("option", "minDate"); var inst = $(elem).data("datepicker"); var minDateObj = $.datepicker._determineDate(inst, minDateAttr, new Date()); A: This update fixes a few bugs surrounding month calculation bugs, hours and leap years. Big props to Simen for the first version which was the foundation. Also this version will allow for optional second param dateVal where you can pass a date to calculate from instead of using today's date. function determineDate(dateAttr, dateVal) { var date = dateVal === undefined ? new Date() : new Date(dateVal); var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g; var matches = pattern.exec(dateAttr); var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDate(); while (matches) { switch (matches[2] || 'd') { case 'd' : case 'D' : day += parseInt(matches[1],10); break; case 'w' : case 'W' : day += parseInt(matches[1],10) * 7; break; case 'm' : case 'M' : month += parseInt(matches[1],10); day = Math.min(day, getDaysInMonth(year, month)); break; case 'y': case 'Y' : year += parseInt(matches[1],10); day = Math.min(day, getDaysInMonth(year, month)); break; } matches = pattern.exec(dateAttr); } var newdate = new Date(year, month, day); newdate.setHours(0); newdate.setMinutes(0); newdate.setSeconds(0); newdate.setMilliseconds(0); return daylightSavingAdjust(newdate); } function daylightSavingAdjust(date){ if (!date){ return null; } date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; } function getDaysInMonth(year, month){ return 32 - daylightSavingAdjust(new Date(year, month, 32)).getDate(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/2885315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Java 8 Streams: Stream closed by intermediate operation I'm aware of the difference between intermediate and terminal stream operations. However when I came across the code example below, I could not quite figure out the reason, why the filter operation in line 2 closes the stream leading the following exception in line 3: java.lang.IllegalStateException: stream has already been operated upon or closed Why does the intermediate filter operation close the stream? Is this always the case when calling intermediate operations on a stream without terminal operation and/or without assigning it to a variable? Code example: Stream<Integer> stream = Stream.of(1, 2, 3); stream.filter(d -> d > 1); stream.filter(d -> d > 2).forEach(System.out::print); A: The point is that method filter returns new stream. The old one is terminated after filtering. /** * Returns a stream consisting of the elements of this stream that match * the given predicate. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to each element to determine if it * should be included * @return the new stream */ Stream<T> filter(Predicate<? super T> predicate);
{ "language": "en", "url": "https://stackoverflow.com/questions/54380641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Write a map with key as int to json in scala using json4s I am trying to write a Map in key as int to json string but I am not able to do so: import org.json4s._ import org.json4s.jackson.JsonMethods._ import org.json4s.JsonDSL._ object MyObject { def main(args: Array[String]) { // Works fine //val myMap = Map("a" -> List(3,4), "b" -> List(7,8)) // Does not work val myMap = Map(4 -> Map("a" -> 5)) val jsonString = pretty(render(myMap)) println(jsonString) } I am receiving the following error: [error] /my_stuff/my_file.scala:14: overloaded method value render with alternatives: [error] (value: org.json4s.JValue)org.json4s.JValue <and> [error] (value: org.json4s.JValue)(implicit formats: org.json4s.Formats)org.json4s.JValue [error] cannot be applied to (scala.collection.immutable.Map[Int,scala.collection.immutable.Map[String,Int]]) [error] val jsonString = pretty(render(myMap)) [error] ^ [error] one error found [error] (compile:compileIncremental) Compilation failed I vaguely understand the error message, it looks like render expects JValue as an input, and I am not providing it, but I don't the first case either, and the code works as I expect. How do I write such map to json string? Edit: My source of confusion I am mostly a python programmer, and in python In [1]: import json In [2]: wrong = {2: 5} In [3]: with open("wrong.json") as f: ...: json.dump(wrong, f) works perfectly fine, of course python stringifies the 2. A: I think it is an expected result. If you check the json specification you will see that you need to use strings for the names of the elements. So I am afraid you will need something like: val myMap = Map("4" -> Map("a" -> 5))
{ "language": "en", "url": "https://stackoverflow.com/questions/30262300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use Xon-Xoff protocol with Java? I try to development a code for print a fiscal ticket. I use Java (programmation language) an XON-XOFF with protocol to use to print ticket. So I have write this code: public SerialPortHandler(String portaCOM){ log = new MyLog4J(); try { this.connect(portaCOM); this.provaScontrino(); } catch (IOException e) { log.logStackTrace(e); } } public void connect(String portName) throws IOException { try { // Obtain a CommPortIdentifier object for the port you want to open CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName); log.information("apro porta seriale"); //System.out.println("apro porta seriale"); // Get serialPort = (SerialPort) portId.open("Demo application", 5000); // Set the parameters of the connection. setSerialPortParameters(); log.information("settaggio porta terminato"); } catch (NoSuchPortException e) { log.logStackTrace(e); throw new IOException(e.getMessage()); } catch (PortInUseException e) { log.logStackTrace(e); throw new IOException(e.getMessage()); } catch (IOException e) { log.logStackTrace(e); serialPort.close(); throw e; } } public void provaScontrino(){ try { outStream = serialPort.getOutputStream(); //inStream = serialPort.getInputStream(); log.information("output acquisito ora provo a stampare uno scontrino"); String messageString = "j"; outStream.write(messageString.getBytes()); //messageString = "'PANTALONE'10H1R"; //outStream.write(messageString.getBytes()); messageString = "\"MAGLIA\"3*100H1P"; outStream.write(messageString.getBytes()); messageString = "1T"; outStream.write(messageString.getBytes()); messageString = "J"; outStream.write(messageString.getBytes()); log.information("scontrino stampato ora apro il cassetto"); apriCassetto(); } catch (Exception e) { log.logStackTrace(e); } } So whit this code I think to have a non fiscal ticket with "3 MAGLIE" but I received a ticket like this: DITTA S.R.L. NAME OF CITY P.IVA EURO Operatore 12 Reparto 1 0,00 TOTALE EURO 0,00 CONTANTI 0,00 14/10/14 10:55 SF.4 Can we help me? Reguards
{ "language": "en", "url": "https://stackoverflow.com/questions/26356649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error when filtering a List with data that came from json data, the method where was called on null Hello I am new to Flutter , I have started an app that call the players and then filters the players by their role(Attacker, Midfielder, Defender, Goalkeeper) and i have faced a problem when i launched the application , the error says SplayerLab is null the method where was called on null Here what i have tried: import 'package:flutter/material.dart'; import 'package:fantazy/controller/player_lab.dart'; import 'package:fantazy/model/player.dart'; import 'package:fantazy/create_team_view.dart'; class PlayersCreationDetailsView extends StatefulWidget { final List<Player> selectedPlayers; final int playerIndex; const PlayersCreationDetailsView ({ Key key, @required this.selectedPlayers, @required this.playerIndex }) : super(key: key); @override _PlayersCreationDetailsViewState createState() => _PlayersCreationDetailsViewState(); } class _PlayersCreationDetailsViewState extends State<PlayersCreationDetailsView> { bool _sortAsc = false; int _sortColumnIndex = 0; double _columnWidth = 40.0; double _columnNameWidth = 60.0; PlayersDataSource _playersDataSource; List<Player> _players; int _rowsPerPage = 20; void _sort<T>(Comparable<T> getField(Player p), int columnIndex, bool ascending) { _playersDataSource._sort<T>(getField, ascending); setState(() { _sortColumnIndex = columnIndex; _sortAsc = ascending ; }); } @override void initState() { List<Player> players = PlayerLab.get().players; //filter out players by position if (widget.playerIndex < 2) { _players = List<Player>.from(players.where((player) => player.position=="GK")); } else if (widget.playerIndex < 7) { _players = List<Player>.from(players.where((player) => player.position=="DEF")); } else if (widget.playerIndex < 12) { _players = List<Player>.from(players.where((player) => player.position=="MID")); } else { _players = List<Player>.from(players.where((player) => player.position=="FWD")); } //filter out players who are already selected for (Player player in widget.selectedPlayers) { _players.remove(player); } _playersDataSource = PlayersDataSource(widget.playerIndex, widget.selectedPlayers, _players, context); super.initState(); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async => false, child: Scaffold( body: ListView( children: <Widget>[ PaginatedDataTable( columnSpacing: 1.0, horizontalMargin: 1.0, availableRowsPerPage: [10,20,50], rowsPerPage: _rowsPerPage, onRowsPerPageChanged: (int value) { setState(() { _rowsPerPage = value; }); }, sortColumnIndex: _sortColumnIndex, sortAscending: _sortAsc, header: Text("Players"), columns: <DataColumn>[ new DataColumn( label: new Container(width: _columnNameWidth , child: Text("First Name", softWrap: true,)), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<String>((Player p) => p.firstName, columnIndex, ascending) ), new DataColumn( label: new Container(width: _columnNameWidth , child: Text("Last Name", softWrap: true,)), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<String>((Player p) => p.lastName, columnIndex, ascending) ), new DataColumn( label: new Container(width: _columnWidth , child: new Text("Position")), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<String>((Player p) => p.position, columnIndex, ascending) ), new DataColumn( label: new Container(width: _columnWidth , child: new Text("Price")), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.price, columnIndex, ascending) ), new DataColumn( label: new Container(width: _columnWidth , child: new Text("Team")), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.team, columnIndex, ascending) ), /* new DataColumn( label: new Container(width: _columnWidth , child: new Text("Points")), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.points, columnIndex, ascending) ), new DataColumn( label: new Container(width: _columnWidth , child: new Text("Week Points")), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.pointsWeek, columnIndex, ascending) ),*/ /* new DataColumn( label: new Container(width: _columnWidth , child: new Text("Apps")), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.appearances, columnIndex, ascending) ), new DataColumn( label: new Container(width: _columnWidth , child: new Text("Sub Apps")), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.subAppearances, columnIndex, ascending) ),*/ new DataColumn( label: new Container(width: _columnWidth , child: new Text("Goals")), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.goals, columnIndex, ascending) ), new DataColumn( label: new Container(width: _columnWidth , child: new Text("Assists")), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.assists, columnIndex, ascending) ), new DataColumn( label: new Container(width: _columnWidth , child: new Text("Yellows")), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.yellowCards, columnIndex, ascending) ), new DataColumn( label: new Container(width: _columnWidth , child: new Text("Reds")), numeric: true, onSort: (int columnIndex, bool ascending) => _sort<num>((Player p) => p.redCards, columnIndex, ascending) ), ], source: _playersDataSource, ) ], ) ) ); } } class PlayersDataSource extends DataTableSource { PlayersDataSource(this._playerIndex, this._selectedPlayers, this._players, this.context); int _playerIndex; List<Player> _players; List<Player> _selectedPlayers; int _selectedCount = 0; var context; double _columnWidth = 40.0; double _columnNameWidth = 60.0; void _sort<T>(Comparable<T> getField(Player p), bool ascending) { _players.sort((Player a, Player b) { if (!ascending) { final Player c = a; a = b; b = c; } final Comparable<T> aValue = getField(a); final Comparable<T> bValue = getField(b); return Comparable.compare(aValue, bValue); }); notifyListeners(); } DataCell getCell(String text) { return DataCell(Container(width: _columnWidth, child: Text(text, overflow: TextOverflow.fade, softWrap: false,))); } @override DataRow getRow(int index) { assert(index >= 0); if (index >= _players.length) return null; final Player player = _players[index]; return DataRow.byIndex( onSelectChanged: (bool) { _players.removeAt(index); _selectedPlayers[_playerIndex] = player; Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) {return CreateTeamView(players: _players, selectedPlayers: _selectedPlayers,);})); }, index: index, cells: <DataCell>[ getCell(player.firstName), getCell(player.lastName), getCell(player.position), getCell('${player.price}'), // getCell('${player.isFresher}'), getCell('${player.team}'), //getCell('${player.points}'), // getCell('${player.pointsWeek}'), getCell('${player.appearances}'), // getCell('${player.subAppearances}'), getCell('${player.goals}'), getCell('${player.assists}'), getCell('${player.cleanSheets}'), // getCell('${player.motms}'), getCell('${player.yellowCards}'), getCell('${player.redCards}'), // getCell('${player.ownGoals}'), ] ); } @override int get rowCount => _players.length; @override bool get isRowCountApproximate => false; @override int get selectedRowCount => _selectedCount; } I am trying to fix the error and filter the list of players by their roles Here my PlayerLab model: import 'package:flutter_auth/Fantazyy/player%20copy.dart'; class PlayerLab { List<Playerr> _players = List(); static PlayerLab _sPlayerLab; static PlayerLab get() { if (_sPlayerLab == null) { throw "sPlayerLab is null"; } return _sPlayerLab; } void addPlayer(Playerr player) { _sPlayerLab.players.add(player); } Playerr getPlayer(int id) { for (Playerr player in _players) { if (player.playerID == id) { return player; } } return null; } PlayerLab(); PlayerLab.fromJson(List<dynamic> json) { _sPlayerLab = PlayerLab(); for (Map<String, dynamic> playerJson in json) { addPlayer(Playerr.fromJson(playerJson)); } } List<Playerr> get players => _players; } A: The error "where was called on null" implies, that players are null by the time you call it. I am assuming PlayerLab.get().players returns a Future so you should add the "await" keyword before the call: initState() async { List<Player> players = await PlayerLab.get().players .... }
{ "language": "en", "url": "https://stackoverflow.com/questions/67170942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing method having CompletableFuture.allOf using mockito I have a method called doParallelThings: public Dummy doParallelThings(Map<String, String> mapp) throws Exception { Dummy dummy = new Dummy(); CompletableFuture<Ans1> one = firstService.getOne(mapp.get("some1"), mapp); CompletableFuture<Ans2> two = secondService.getTwo(headersMap.get("some2"), mapp); CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(one, two); try { combinedFuture.get(); dummy.setOne(one.get()); dummy.setTwp(two.get()); } catch (Throwable e) { } return dummy; } Code works fine but when I'm trying to test it, combinedFuture.get(); goes to infinite loop. Unit test is as below: @Mock private CompletableFuture<Void> ans; @Test public void testDoParallelThings() throws Exception { PowerMockito.mockStatic(CompletableFuture.class); PowerMockito.when(CompletableFuture.allOf(any())).thenReturn(ans); when(ans.get()).thenReturn(null); Dummy dummy = dummyService. doParallelThings(mockMap); assertNotNull(dummy); } I have also added @RunWith(PowerMockRunner.class) @PrepareForTest({CompletableFuture.class}) above the test class. What am I missing? A: when(firstService.getOne(any(), any())).thenReturn(CompletableFuture.completedFuture(mockOne)); solved my problem
{ "language": "en", "url": "https://stackoverflow.com/questions/58073189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why can't ssh connect to any host inside a while loop? theIp="" #1 echo $theIp | while read ip; do ssh -tt root@$ip exit done #2 while read ip; do ssh root@$ip exit done < <(echo $theIp) #3 while true; do ssh root@$theIp exit done the above 3 way about connect any host in a while statement, but only the last one succeeded, why do the first two do nothing? A: ssh was eating up your loop's input. Probably in this case your ssh session exits when it gets EOF from it. That's the likely reason but some input may also cause it to exit. You have to redirect its input by specifying < /dev/null or use -n: ssh -n "root@$ip" ssh "root@$ip" < /dev/null That may also apply with -tt since somehow it's independent. Just try. If you're using Bash or similar shell that supports read -u, you can also specify a differ fd for your file. while read -u 4 ip; do ssh root@$ip exit done 4< <(echo $theIp)
{ "language": "en", "url": "https://stackoverflow.com/questions/24990134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how should I use the variable I'm watching inside the angularjs $watch() function I have been learning how to use directives in angularjs to include jQuery plugins using the tutorials here and here. I am trying to incorporate fullCalendar and I have successfully gotten the calendar initialized and displaying, but now I'm a little stuck. I am currently getting my data from a json file ( eventually will come from a factory and php get response) but I am unsure how I should reference the json data in my directive and need some guidance. currently I have the below, but what would be the correct/best approach to not hard coding and keeping it flexible. I know I could possibly put a $http.get() request within the directive but I feel that I shouldn't be making any requests from with my directive ( unless some one can convince me that this approach isn't bad practice) this is my current directive.js ( please not getJSON() is only for testing) angular.module('Directives', []) .directive('mycalendar', function () { getJSON = function () { return [{ "title": "Fitness", "start": "2013-08-01 06:30:00", "instructor": "3" }] } var linker = function (scope, element, attr) { scope.$watch('classesList', function () { /**/ element.fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, editable: true, events: getJSON() /**/ }); }); } return { restrict: 'A', link: linker } }); my controller: angular.module('Controllers', []) .controller('CalController', function ($scope, $http) { $scope.url = 'json/classes.json'; $scope.classesList = []; $scope.fetchClasses = function () { $http.get($scope.url) .then(function (result) { $scope.classesList = result.data; }); $scope.fetchClasses(); } }); my HTML: <div id="container" ng-controller="CalController"> <div id='calendar' mycalendar></div> </div> A: Same full calendar is available as Module @ https://github.com/angular-ui/ui-calendar Please look at it Or Check the below URL http://jsfiddle.net/joshkurz/xqjtw/59/ Check the controller part of above url: $scope.eventSource = { url: "http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic", className: 'gcal-event', // an option! currentTimezone: 'America/Chicago' // an option! }; Here "$scope.eventSource" is static you can make it dynamic by Create service function and use $http and inject service function in your controller below is the example for the same : app.factory('myService', function($http) { return { getList:function(params){ var promise= $http({url: 'ServerURL',method: "POST", params: params}).then(function(response,status){ return response.data; }); // Return the promise to the controller return promise; } } }); app.controller('MainCtrl', function($scope, myService) { myService.getList(function(data) { $scope.eventSource = data; }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/18312595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I safely access .env variables to make api requests in an app using React & Vite? How can I access env variables safely within React in a deployed App Service in Azure? I'm using vite as the build tool.
{ "language": "en", "url": "https://stackoverflow.com/questions/73816303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Send serialized form data and receive PHP Laravel redirect with form and session data I have a form on my page. After submission I am adding additional data to the form for submission. I can submit the serialized form data via ajax, however, I am unable to successfully process the response. The response is coming from Laravel and includes a redirect URL, a Session 'success' or 'error' message, and possible form data on a form error redirect. JS submit function function submit() { var formData = $('#form').serializeArray(); formData.push({ name: "additional_data", value: additional_data }); $.ajax({ type: "POST", url: "/submit_form_data", data: formData, success: function(data) { // response includes redirect url, session data ('success' or 'error' + message), form data (if form error) } }); } Laravel data submission route public function submitData(Request $request) { $data = $request->all(); // check for form error and redirect back with error message and form input $validator = Validator::make($data); if ($validator->fails()) { return redirect() ->back() ->withErrors($validator) ->withInput(); } // submit data and redirect with success message $this->createEntry($data); return redirect('/dashboard') ->with('success', "Data successfully submitted"); } I have tried submitting the data via XMLHttpRequest, but the form data and session data do not seem to be contained anywhere within the request response. function submit() { var formData = $('#form').serializeArray(); formData.push({ name: "additional_data", value: additional_data }); var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState == XMLHttpRequest.DONE) { // window redirects, but form data and session data are lost window.location.replace(request.responseURL); } } request.open("POST", '/submit_form_data'); request.send(formData); } If I submit the form via a simple $("#form").submit(), the form data and session data are all transferred intact, however, there does not seem to be any way to append form data when using this method and so my "additional_data" is lost. And one final point. If I redirect without waiting for XMLHttpRequest.DONE, the form and session data is retained. However, in this case I have no idea which URL I should be redirecting to. function submit() { var formData = $('#form').serializeArray(); formData.push({ name: "additional_data", value: additional_data }); var request = new XMLHttpRequest(); request.open("POST", '/submit_form_data'); request.send(formData); // session data will be intact, but I don't have a redirect URL window.location.replace('/dashboard'); } UPDATE: Using the suggestion from hppycoder, I was able to find a somewhat workable solution. The problem is that the values required on the frontend need to be set via PHP. This includes the $errors variable, which is set via redirect()->withErrors($validator), and the form input data which is set via redirect()->withInput(). However, I need to be able to read the php response in my JavaScript. I can do this if I return a response()->json() object, but then the $errors and form input data would not be set. The workaround is to combine the two approaches, although it feels less than elegant, as it requires that I make multiple calls to my POST method. Laravel submit route public function submitData(Request $request) { $data = $request->all(); // check for form error and redirect back with error message and form input $validator = Validator::make($data); if ($validator->fails()) { // this will set the necessary php values ($errors variable and form input data) // response cannot be read by ajax return redirect() ->back() ->withErrors($validator) ->withInput(); } // no form errors, submit data and return 'success' response $this->createEntry($data); // this response can be read by ajax, and the Session 'success' value is set Session::put('success', ("Data successfully submitted")); return response()->json([ 'success' => true ]); } JavaScript submit function function submit() { var formData = $('#form').serializeArray(); formData.push({ name: "additional_data", value: additional_data }); $.ajax({ type: "POST", url: "/submit_form_data", data: formData, success: function(data) { if (data.success) { // check for 'success' and redirect to dashboard window.location.replace("/dashboard"); } else { // if no success message, reload current page with form errors and data // if I call window.location.reload() here, the form data and $errors variable are not set // in order to set these I need to submit the data a second time via XMLHttpRequest var form = document.getElementById('form'); var formData = new FormData(form); formData.push({ name: "additional_data", value: additional_data }); var request = new XMLHttpRequest(); request.open("POST", '/submit_form_data'); request.send(formData); // now after reload, the form data and $errors varaible will be set window.location.reload(); } } }); } Additionally, below is my html, which shows how the php values are being rendered by the blade template. I should have included this in the original post to clarify why I needed the php values to be set. <body> @if (count($errors->all()) > 0) <div class="alert alert-danger alert-block"> <button type="button" class="close" data-dismiss="alert">&times;</button> <h4>Error</h4> Please check the form below for errors </div> @endif @if ($message = Session::get('success')) <div class="alert alert-success alert-block"> <button type="button" class="close" data-dismiss="alert">&times;</button> <h4>Success</h4> {{ $message }} </div> @endif <form id="form" class="form-horizontal" role="form" method="POST" enctype="multipart/form-data"> <div class="row form-group"> <label class="control-label">Some Data</label> <input class="form-control" name="some_data" value="{{ old('some_data') }}"> </div> <div class="row"> @if ($errors->has('some_data')) <span class="help-block"> <strong>{{ $errors->first('some_data') }}</strong> </span> @endif </div> </form> </body> A: I'm going to use the documentation I posted earlier to show. public function submitData(Request $request) { $data = $request->all(); // check for form error and redirect back with error message and form input $validator = Validator::make($data); if ($validator->fails()) { return redirect() ->back() ->withErrors($validator) ->withInput(); } // submit data and redirect with success message $this->createEntry($data); return response()->json([ 'success' => true, 'message' => 'Data successfully submitted', ]); } JS Submit: function submit() { var formData = $('#form').serializeArray(); formData.push({ name: "additional_data", value: additional_data }); $.ajax({ type: "POST", url: "/submit_form_data", data: formData, success: function(data) { console.log(data); // response includes redirect url, session data ('success' or 'error' + message), form data (if form error) } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/66858560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# Convert string to name of bool variable I trying to make something like that: // int counter; - this is changing in ther other parts of program bool abc1; bool abc2; bool abc3; bool abc4; if("abc" + counter == true) { //some code } Anyway, I need to convert string and int to bool name. How can I do this? A: Use an array instead: bool[] abc; // ... if (abc[counter] == true) { { // some code. }
{ "language": "en", "url": "https://stackoverflow.com/questions/31347546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Pyspark - add columns to dataframe based on values from different dataframe I have two dataframes. AA = +---+----+---+-----+-----+ | id1|id2| nr|cell1|cell2| +---+----+---+-----+-----+ | 1| 1| 0| ab2 | ac3 | | 1| 1| 1| dg6 | jf2 | | 2| 1| 1| 84d | kf6 | | 2| 2| 1| 89m | k34 | | 3| 1| 0| 5bd | nc4 | +---+----+---+-----+-----+ and a second dataframe BB, which looks like: BB = +---+----+---+-----+ | a | b|use|cell | +---+----+---+-----+ | 1| 1| x| ab2 | | 1| 1| a| dg6 | | 2| 1| b| 84d | | 2| 2| t| 89m | | 3| 1| d| 5bd | +---+----+---+-----+ where, in BB, the cell section, I have all possible cells that can appear in the AA cell1 and cell2 sections (cell1 - cell2 is an interval). I want to add two columns to BB, val1 and val2. The conditions are the following. val1 has 1 values when: id1 == id2 (in AA) , and cell (in B) == cell1 or cell2 (in AA) and nr = 1 in AA. and 0 otherwise. The other column is constructed according to: val 2 has 1 values when: id1 != id2 in (AA) and cell (in B) == cell1 or cell 2 in (AA) and nr = 1 in AA. it also has 0 values otherwise. My attempt: I tried to work with: from pyspark.sql.functions import when, col condition = col("id1") == col("id2") result = df.withColumn("val1", when(condition, 1) result.show() But it soon became apparent that this task is way over my pyspark skill level. EDIT: I am trying to run : condition1 = AA.id1 == AA.id2 condition2 = AA.nr == 1 condition3 = AA.cell1 == BB.cell | AA.cell2 == BB.cell result = BB.withColumn("val1", when(condition1 & condition2 & condition3, 1).otherwise(0) Gives an error inside a Zeppelin notebook: Traceback (most recent call last): File "/tmp/zeppelin_pyspark-4362.py", line 344, in <module> code = compile('\n'.join(final_code), '<stdin>', 'exec', ast.PyCF_ONLY_AST, 1) File "<stdin>", line 6 __zeppelin__._displayhook() ^ SyntaxError: invalid syntax EDIT2: Thanks for the correction, I was missing a closing bracket. However now I get ValueError: Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions. Which is awkward, since I am already using these operators. A: In my opinion the best way might be a join of the two dataframes and then you can model the conditions in the when clause. I think if you create a new column with withColumn it iterates over the values from the current dataframe, but I think you can not access values from another dataframe and expect it also iterates through the rows there. The following code should fulfill your request: df_aa = spark.createDataFrame([ (1,1,0,"ab2", "ac3"), (1,1,1,"dg6", "jf2"), (2,1,1,"84d", "kf6"), (2,2,1,"89m", "k34"), (3,1,0,"5bd", "nc4") ], ("id1", "id2","nr","cell1","cell2")) df_bb = spark.createDataFrame([ (1, 1, "x","ab2"), (1, 1, "a","dg6"), (2, 1, "b","84d"), (2, 2, "t","89m"), (3, 1, "d", "5bd") ], ("a", "b","use","cell")) cond = (df_bb.cell == df_aa.cell1)|(df_bb.cell == df_aa.cell2) df_bb.join(df_aa, cond, how="full").withColumn("val1", when((col("id1")==col("id2")) & ((col("cell")==col("cell1"))|(col("cell")==col("cell2"))) & (col("nr")==1), 1).otherwise(0)).withColumn("val2", when(~(col("id1")==col("id2")) & ((col("cell")==col("cell1"))|(col("cell")==col("cell2"))) & (col("nr")==1), 1).otherwise(0)).show() Result looks like: +---+---+---+----+---+---+---+-----+-----+----+----+ | a| b|use|cell|id1|id2| nr|cell1|cell2|val1|val2| +---+---+---+----+---+---+---+-----+-----+----+----+ | 1| 1| x| ab2| 1| 1| 0| ab2| ac3| 0| 0| | 1| 1| a| dg6| 1| 1| 1| dg6| jf2| 1| 0| | 2| 1| b| 84d| 2| 1| 1| 84d| kf6| 0| 1| | 2| 2| t| 89m| 2| 2| 1| 89m| k34| 1| 0| | 3| 1| d| 5bd| 3| 1| 0| 5bd| nc4| 0| 0| +---+---+---+----+---+---+---+-----+-----+----+----+ It could be that I do not even need to check for the condition cell==cell1|cell==cell2 since that is pretty much the join condition, but to make the when conditions similar to the requirements of you, I put it there
{ "language": "en", "url": "https://stackoverflow.com/questions/52850603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AIDL ERROR while trying to return custom class object I am trying to pass 'Response' class object using IPC in AIDL. I have made the class parcelable: public class Response implements Parcelable{ private long id; private String speechString; private List<String> responseString = new ArrayList<String>(); //set ... } //get ... public Response(Parcel in) { id = in.readLong(); speechString = in.readString(); if (in.readByte() == 0x01) { responseString = new ArrayList<String>(); in.readList(responseString, String.class.getClassLoader()); } else { responseString = null; } } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(id); dest.writeString(speechString); if (responseString == null) { dest.writeByte((byte) (0x00)); } else { dest.writeByte((byte) (0x01)); dest.writeList(responseString); } } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public Response createFromParcel(Parcel in) { return new Response(in); } public Response[] newArray(int size) { return new Response[size]; } }; } Defined Response.aidl: package com.example; parcelable Response; IappMain.aidl is used for IPC and is defined as following: package com.example; // Declare any non-default types here with import statements import com.example.Response; interface IOizuuMain { int app(String aString); Response getResponseByString(String string); } but upon building the project, it gives me the following error in IappMain.java: "error: incompatible types: Object cannot be converted to Response" at this line: _result = com.example.Response.CREATOR.createFromParcel(_reply); A: The error is being caused by this line: public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { Type parameters need to be added to both the return type and the object being created. The change to add type parameters is this: public static final Parcelable.Creator<Response> CREATOR = new Parcelable.Creator<Response>() { A: try to add public Response() {} above to the below mentioned code. public Response(Parcel in) { ..... .... } so it should look like public Response(){} public Response(Parcel in) { ..... .... }
{ "language": "en", "url": "https://stackoverflow.com/questions/30693983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Saving to a particular column in database I have a simple doubt.. I have a column named url in a table. And each row in a table is created using active admin. In that there is no provision to give url(It should be like that). It has got another column with Page_name. and with some calculations(shown below) i do have the required url in a variable. Now i want to update this column url in database with this variable as soon as it is created. this is what i have done so far. class CustomPage < ActiveRecord::Base after_create :custom def custom @custom_page = CustomPage.all p "---------------------------------------" p @custom_page.last.id url = "/custom_page/"+@custom_page.last.page_name.split(" ").join("_") CustomPage.where(:id => @custom_page.last.id).update(:url => url) end end and i'm getting some kind of error. Wrong Number of Arguments (1 for 2).. I hope this is something very small.. thanks in advance. A: This line should look like this CustomPage.where(:id => @custom_page.last.id).first.update(:url => url) Since where returns ActiveRecord::Relation which is in form of a array so you need to fetch the object out of the array A: You could pass the id to update method like this CustomPage.update(@custom_page.last.id, :url => url) But in this particular case, you can do @custom_page.last.update_attribute(:url, url) Please note that these methods doesn't invoke validations. To do that, call @custom_page.last.update_attributes(:url => url)
{ "language": "en", "url": "https://stackoverflow.com/questions/23601510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "An invalid or incomplete configuration was used while creating a SessionFactory” NHibernate I am getting this error while creating SessionFactory. Here is the code, if some can check this out. class NHibernateHelper { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null) { InitializeSessionFactory(); } return _sessionFactory; } } private static void InitializeSessionFactory() { _sessionFactory = Fluently.Configure(). Database(MsSqlConfiguration.MsSql2008.ConnectionString ("Server=tcp:z4m56fgh.database.windows.net,1433;Database=db;User ID=user;Password=xxxxx;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"). ShowSql()). Mappings(m => m.FluentMappings.AddFromAssemblyOf<House>()). ExposeConfiguration(cfg => new SchemaExport(cfg).Create(false, true)). BuildSessionFactory(); } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } Mappings: public class HouseMap : ClassMap<House> { public HouseMap() { Id(x => x.Id); References(x => x.Owner).Cascade.All(); References(x => x.Rooms).Cascade.All(); References(x => x.Consumptions).Cascade.All(); } } public class ConsumptionMap : ClassMap<Consumption> { public ConsumptionMap() { Id(x => x.Id); Map(x => x.Type); Map(x => x.AvgDay); Map(x => x.AvgMonth); Map(x => x.AvgYear); } } public class RoomMap : ClassMap<Room> { public RoomMap() { Id(x => x.Id); Map(x => x.Name); Map(x => x.Number); Component<TemperatureData>(x => x.TemperatureData, t => { t.Map(x => x.TemperatureCurrent, "Current"); t.Map(x => x.TemperatureSet, "Set"); }); Component<RoomFeatures>(x => x.Features, f => { f.Map(x => x.Shutters, "ShuttersUp"); f.Map(x => x.Lights, "LightsOn"); }); } } This exact class NHibernateHelper works with another Model, so it must be something wrong with my mappings. Also, it still does not work if i exclude everything from HouseMap, i.e. comment on the References. A: It is being a little difficult to realize what is the source of your problem without the classes, although, a guess would be at the Consumptions property. If it is a list (as it seems by its name) it should be mapped with HasMany instead of References. Besides, maybe you could attach the stack trace with the InnerException. This could give us a clue.
{ "language": "en", "url": "https://stackoverflow.com/questions/28248000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Amazon RDS Instance Password? I'll preface this with the statement that I hate using these Amazon servers. Ok what I need to know is how to find the password for a specific Amazon RDS instance. I have a live instance running my store and working on setting up a development copy. So I lauched a copy of the DB but can't seem to find the password for this new DB instance anywhere. I created a Snapshot, then restored from the snapshot just with a new instance identifier. So would the passwords be the same on both instances? Thanks! A: Yes, they should have the same password.
{ "language": "en", "url": "https://stackoverflow.com/questions/21170960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Stylus Iteration + Interpolation with nth-of-type I'm attempting to use the counter provided when looping thru a list of items like so: colors = red blue orange green yellow li for color, i in colors &:nth-of-type({i}n) background-color: color This example does not work, but the intended output I'm looking for is: li:nth-of-type(1n) { background-color: red; } li:nth-of-type(2n) { background-color: blue; } li:nth-of-type(3n) { background-color: orange; } ... Is this possible? A: Actually your example's output is almost correct. It starts with 0 and you need 1, so this should work: colors = red blue orange green yellow li for color, i in colors &:nth-of-type({i + 1}n) background-color: color
{ "language": "en", "url": "https://stackoverflow.com/questions/34410889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert a string of hex values to a string? Say I have a string like: string hex = "48656c6c6f"; Where every two characters correspond to the hex representation of their ASCII, value, eg: 0x48 0x65 0x6c 0x6c 0x6f = "Hello" So how can I get "hello" from "48656c6c6f" without having to create a lookup ASCII table? atoi() obviously won't work here. A: std::string str("48656c6c6f"); std::string res; res.reserve(str.size() / 2); for (int i = 0; i < str.size(); i += 2) { std::istringstream iss(str.substr(i, 2)); int temp; iss >> std::hex >> temp; res += static_cast<char>(temp); } std::cout << res; A: int len = hex.length(); std::string newString; for(int i=0; i< len; i+=2) { std::string byte = hex.substr(i,2); char chr = (char) (int)strtol(byte.c_str(), null, 16); newString.push_back(chr); } A: Hex digits are very easy to convert to binary: // C++98 guarantees that '0', '1', ... '9' are consecutive. // It only guarantees that 'a' ... 'f' and 'A' ... 'F' are // in increasing order, but the only two alternative encodings // of the basic source character set that are still used by // anyone today (ASCII and EBCDIC) make them consecutive. unsigned char hexval(unsigned char c) { if ('0' <= c && c <= '9') return c - '0'; else if ('a' <= c && c <= 'f') return c - 'a' + 10; else if ('A' <= c && c <= 'F') return c - 'A' + 10; else abort(); } So to do the whole string looks something like this: void hex2ascii(const string& in, string& out) { out.clear(); out.reserve(in.length() / 2); for (string::const_iterator p = in.begin(); p != in.end(); p++) { unsigned char c = hexval(*p); p++; if (p == in.end()) break; // incomplete last digit - should report error c = (c << 4) + hexval(*p); // + takes precedence over << out.push_back(c); } } You might reasonably ask why one would do it this way when there's strtol, and using it is significantly less code (as in James Curran's answer). Well, that approach is a full decimal order of magnitude slower, because it copies each two-byte chunk (possibly allocating heap memory to do so) and then invokes a general text-to-number conversion routine that cannot be written as efficiently as the specialized code above. Christian's approach (using istringstream) is five times slower than that. Here's a benchmark plot - you can tell the difference even with a tiny block of data to decode, and it becomes blatant as the differences get larger. (Note that both axes are on a log scale.) Is this premature optimization? Hell no. This is the kind of operation that gets shoved in a library routine, forgotten about, and then called thousands of times a second. It needs to scream. I worked on a project a few years back that made very heavy use of SHA1 checksums internally -- we got 10-20% speedups on common operations by storing them as raw bytes instead of hex, converting only when we had to show them to the user -- and that was with conversion functions that had already been tuned to death. One might honestly prefer brevity to performance here, depending on what the larger task is, but if so, why on earth are you coding in C++? Also, from a pedagogical perspective, I think it's useful to show hand-coded examples for this kind of problem; it reveals more about what the computer has to do. A: strtol should do the job if you add 0x to each hex digit pair.
{ "language": "en", "url": "https://stackoverflow.com/questions/3790613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Physics object passing through wall object in corona sdk I am hitting a ball with a force and there is a wall which is assigned a physics property and is static, but the ball is dynamic, the problem is when enough force is applied to the ball it passes through the wall, it is a type of table wall as in sample simple pool game. I have used ball.isBullet=true but same problem is there. Please suggest how to solve it.. thanks A: This is a fairly common issue when dealing with small, fast-moving objects. Typically, the best solution is to make the "walls" thicker, if that is possible within your game. Also, you may increase the velocity and position iterations (links below)... just remember that both of these (along with .isBullet=true) may result in a slight performance penalty, so the first approach is the best. http://docs.coronalabs.com/api/library/physics/setVelocityIterations.html http://docs.coronalabs.com/api/library/physics/setPositionIterations.html Brent Sorrentino
{ "language": "en", "url": "https://stackoverflow.com/questions/19229076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cannot Modify Header Information Session Cookie Create? Firstly I like to say this is not a duplicate I tried everything on google such as ob_functions and space not luck PHP should of made this simple but they haven't which is stupid.. Why am I getting this error for just starting a cookie in my script? I have commented the cookie start I am having the issue with and hope someone can help fix it I tried and now gave up wasting my time.. <!DOCTYPE html> <?php session_start(); ?> <html lang="en" class="no-js"> <head> <meta charset="utf-8"> <title>Welcome To Spud Gaming</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- CSS --> <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=PT+Sans:400,700'> <link rel="stylesheet" href="assets/css/reset.css"> <link rel="stylesheet" href="assets/css/supersized.css?vvssv"> <link rel="stylesheet" href="assets/css/style.css?v12"> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <?php require "../core/links.php"; if(isset($_SESSION['user'])) { die; } if(isset($_COOKIE['user'])) { die; } ?> <div class="page-container"> <br><br><br> <h1>Sign In</h1> <div style='color:black;'> <?php if((isset($_POST['username'])) && (isset($_POST['password']))) { require "../core/data_connect.php"; $username = mysqli_real_escape_string($connection,$_POST['username']); $password = mysqli_real_escape_string($connection,(sha1(md5($_POST['password'])))); if(($username) && ($password)){ $login_query_string = "SELECT * FROM spud_members WHERE ( username='$username' OR email = '$username') and password='$password'"; $login_query = mysqli_query($connection,$login_query_string); $login_rows = mysqli_num_rows($login_query); $login_array = mysqli_fetch_array($login_query); $mid_login = $login_array['mid']; $active_login = $login_array['active']; //if we found a user with that information then sign them in if($login_rows==1) { //if the user as not been suspended then start there session if($active_login==1) { //if the user has not checked the remember me box if($_POST['start_cookie_true_checked']!='on') { $_SESSION['user']=$mid_login; die; } else if($_POST['start_cookie_true_checked']=='on') { //otherwise if the remember me box has been checked then start a cookie instead $date_of_expiry = time() + 60 ; //THIS COOKIE HAS A ISSUE AND POPS UP THESE ERRORS!!!!!!!!!!!!!!!!!!!!!!!!! setcookie("user", 'Mark', time()+3600); die; } } else { echo "<b>Account Suspended</b><br> Your Account Has Been Suspended:<br> This May Be Because You Have Broken Our Terms Of Use Guidelines<br><br>"; } } else { echo "<b>Invalid Username/Email Or Password</b><br> The Username/Email Or Password That You Supplied Is Invalid<br> Please Try Again or <a href=''> Reset Your Password</a>"; } } else { echo "<b>Blank Username/Email And Password</b><br> You Haven't Entered A Username/Email And Password"; } } ?> </div> <form action='' method='post'> <input type='text' name='username' placeholder='Username Or Email' size='25' maxlength='30' /><br /> <input type='password' name='password' placeholder='Password' size='25' /> <input type='checkbox' name='start_cookie_true_checked'> <input type='hidden' name='action' value='do_login'> <input type='hidden' name='url' value='index.php' /> <br><br> <style> a { color:blue; text-decoration:none; } </style> <div> <a href='signup'> Need An Account? </a> | <a href='forgot'> Forgot Password?</a> </div> <button type="submit">Sign In</button> </form> </div> <!-- Javascript --> <script src="assets/js/jquery-1.8.2.min.js"></script> <script src="assets/js/supersized.3.2.7.min.js"></script> <script src="assets/js/supersized-init.js?ddsddfd"></script> <script src="assets/js/scripts.js"></script> </body> </html> Thanks :) A: Move HTML outpout after to session_start function. <?php session_start(); ?> <!DOCTYPE html> A: You can't try to set a cookie (which is done in response headers) after you have started to make output to the page (which starts on your first line of code).
{ "language": "en", "url": "https://stackoverflow.com/questions/28152157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Get the raw request using PHP I'm looking for a way to get, using native PHP, the raw HTTP request that my script received, including headers and body. Reading the PHP documentation I cant found a standard way to get the raw request, regardless the HTTP method used. For example, when the page test.php is requested, I want to get the complete request like: GET /test.php HTTP/1.1 Host:.... .... .... The same in case of POST, HEAD, etc... Seems very strange that there doesn't exist a method to access the raw request buffer! A: If you are on an Apache machine try this: function get_raw_http_request() { $request = "$_SERVER[REQUEST_METHOD] $_SERVER[REQUEST_URI] $_SERVER[SERVER_PROTOCOL]\r\n"; foreach (getallheaders() as $name => $value) { $request .= "$name: $value\r\n"; } $request .= "\r\n" . file_get_contents('php://input'); return $request; } http://php.net/manual/en/function.getallheaders.php A: Looking over the manual there doesn't seem to be an unparsed raw access to the request to match what you want, so I suspect you will need to re-build what you want from the $_SERVER variables. A quick search I found this class, made some small change to get the GET / HTTP/1.1, perhaps you will find it suits your needs. <?php /** * Access the HTTP Request * * Found on http://www.daniweb.com/web-development/php/code/216846/get-http-request-headers-and-body */ class http_request { /** additional HTTP headers not prefixed with HTTP_ in $_SERVER superglobal */ public $add_headers = array('CONTENT_TYPE', 'CONTENT_LENGTH'); /** * Construtor * Retrieve HTTP Body * @param Array Additional Headers to retrieve */ function http_request($add_headers = false) { $this->retrieve_headers($add_headers); $this->body = @file_get_contents('php://input'); } /** * Retrieve the HTTP request headers from the $_SERVER superglobal * @param Array Additional Headers to retrieve */ function retrieve_headers($add_headers = false) { if ($add_headers) { $this->add_headers = array_merge($this->add_headers, $add_headers); } if (isset($_SERVER['HTTP_METHOD'])) { $this->method = $_SERVER['HTTP_METHOD']; unset($_SERVER['HTTP_METHOD']); } else { $this->method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : false; } $this->protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : false; $this->request_method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : false; $this->headers = array(); foreach($_SERVER as $i=>$val) { if (strpos($i, 'HTTP_') === 0 || in_array($i, $this->add_headers)) { $name = str_replace(array('HTTP_', '_'), array('', '-'), $i); $this->headers[$name] = $val; } } } /** * Retrieve HTTP Method */ function method() { return $this->method; } /** * Retrieve HTTP Body */ function body() { return $this->body; } /** * Retrieve an HTTP Header * @param string Case-Insensitive HTTP Header Name (eg: "User-Agent") */ function header($name) { $name = strtoupper($name); return isset($this->headers[$name]) ? $this->headers[$name] : false; } /** * Retrieve all HTTP Headers * @return array HTTP Headers */ function headers() { return $this->headers; } /** * Return Raw HTTP Request (note: This is incomplete) * @param bool ReBuild the Raw HTTP Request */ function raw($refresh = false) { if (isset($this->raw) && !$refresh) { return $this->raw; // return cached } $headers = $this->headers(); $this->raw = "{$this->method} {$_SERVER['REQUEST_URI']} {$this->protocol}\r\n"; foreach($headers as $i=>$header) { $this->raw .= "$i: $header\r\n"; } $this->raw .= "\r\n{$this->body}"; return $this->raw; } } /** * Example Usage * Echos the HTTP Request back to the client/browser */ $http_request = new http_request(); $resp = $http_request->raw(); echo nl2br($resp); /* Result (less <br> tags) GET / HTTP/1.1 HOST: localhost:8080 USER-AGENT: Mozilla/5.0 ... ACCEPT: text/html,application/xhtml+xml,application/xml;... ACCEPT-LANGUAGE: en-US,en;q=0.5 ACCEPT-ENCODING: gzip, deflate DNT: 1 COOKIE: PHPSESSID=... CONNECTION: keep-alive */ ?> P.S: Dont forget to htmlentities() them values on output :) A: The raw request is not available to PHP, because the request has already been consumed by the time PHP starts. When PHP is running as an Apache module (mod_php), for instance, the request is received and parsed by Apache, and PHP is only invoked after Apache has parsed that request and determined that it refers to a file which should be processed by PHP. If PHP is running as a CGI or FastCGI handler, it never receives an HTTP request at all — it only sees the CGI form of the request, which is quite different.
{ "language": "en", "url": "https://stackoverflow.com/questions/23446989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: EF4 STE include-path....exclude-path? Context: Repository-pattern, WCF, WPF/SL In my Repository of self-tracking Entities i need to explicitly load some related properties in order to correctly process the query. Those are not the includes requested by the client and i would like to get rid of them in order to keep network traffic resonable. My solution so far is this: * *Receive Query *Load includes necessary to answer request *Execute Query *Create temporary IEnumerable *Iterate 4) and load all items again, this time with the include-path requested from the client-app only *return entities via WCF I would like to do this: * *Receive Query *Load all includes (infrastructure plus client-requested) *Execute Query *Unload "Infrastructure" includes *return entities via WCF What is the proper way to do this? Thanks, Armin A: How about lazy loading and proper DTO response objects ? * *WCF returns custom Order or GetOrderResponse (Contracts.Order) *Load Order from EntityModel through repository (just the order) *Use automapper for mapping EntityModel.Order => Contracts.Order Result : only the corresponding properties inside Contracts.Order are loaded: Ex. Contracts.Order Number OrderDetails (=> Only this property is loaded through lazy loading because it is mapped) If you are building a SOA or webservice, don't let the client specify load graphs. If it's necessary for the client to specify load graphs consider deploying the Model using WCF Data Services, works great. Perhaps you could build two systems .. one SOA and one (readonly) Data Service.
{ "language": "en", "url": "https://stackoverflow.com/questions/5068314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error: Could not find or load main class com.mysql.jdbc.DocsConnectionPropsHelper I am getting error when i load the driver,am i adding the driver correctly,Can someone help to resolve A: am i adding the driver correctly I don't think so. There is something very odd going on here. According to the official MySQL source code repo for Connector/J on Github, there is no com.mysql.jdbc.DocsConnectionPropsHelper class in Connector/J version 8.0.28. But this class does exist in Connector/J 5.1.x. So it looks like you must somehow be using Connector/J 5.x rather than 8.0.x as the IDE screenshot seems to suggest. Check the dependencies on the actual runtime classpath you are using to run this code. (Note that the screenshot shows the project's build classpath not its runtime classpath.) Certainly you should not be mixing the two generations of driver. Calling RegisterDriver with the (8.0.x) com.mysql.cj.jdbc.Driver class when you have the 5.x driver on the classpath is wrong. A: you can try like this Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
{ "language": "en", "url": "https://stackoverflow.com/questions/72028051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Failing Tictactoe in c++ I'm a beginner in c++, i'm trying to make a tictactoe. My program fails at the part acfter i enter input. When I enter an input, there is no next action from the program like i expected it to ("unvalid", check if win or loose, ask for input again). It only shows blank. like below: after I enter "1", nothing happens, and I can keep enter more input. terminal example photo I know it is a simple activity but I just ca't figure it out ToT. Thank you for helping! //tictactoe #include <iostream> #include <vector> using namespace std; //declared variables vector<char> out = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; int in = 2; char player_out; bool loose = false; char x; bool filled = false; bool end(){ //won yet? bool loose = false; //horizontal if (out[1] == out[2] && out[3] == out[2]){ loose = true; } else if (out[4] == out[5] && out[6] == out[5]){ loose = true; } else if (out[7] == out[8] && out[9] == out[8]){ loose = true; } //vertical else if (out[1] == out[4] && out[7] == out[1]){ loose = true; } else if (out[2] == out[5] && out[8] == out[2]){ loose = true; } else if (out[3] == out[6] && out[9] == out[3]){ loose = true; } else if (out[1] == out[5] && out[9] == out[5]){ loose = true; } else if (out[3] == out[5] && out[7] == out[5]){ loose = true; } else{ loose = false; } return loose; } void game_start_display(){ //display the board cout << "TIC TAC TOE\n"; cout << " | | \n"; cout << " " << out[1] << " | " << out[2] << " | " << out[3] << " \n"; cout << "______|______|______\n"; cout << " | | \n"; cout << " " << out[4] << " | " << out[5] << " | " << out[6] << " \n"; cout << "______|______|______\n"; cout << " | | \n"; cout << " " << out[7] << " | " << out[8] << " | " << out[9] << " \n"; cout << " | | \n\n"; } int change_player(){ //take turn 1st and 2nd player if (in == 1){ in++; } else{ in--; } return in; } bool filled_f() { //check if the spot is filled if (out[x] != 'X' and out[x] != 'O'){ filled = true; out[x] = player_out; //fill the input into the spot } else if (out[x] == 'X' or out[x] == 'O') cout << "The square has already been used!\n"; filled = false; return filled; } char player_out_f(){ //change output sign for each players (X, O) if (in == 1){ player_out = 'X'; } else if (in == 2){ player_out = 'O'; } return player_out; } void c_player_display(){ //tell players to enter a number cout << "Player " << in << "'s turn, please enter a number:\n"; } int main(){ //intro int loose = false; game_start_display(); while(loose == false){ //when the game is still happening change_player(); //change player (player start is set 2 so this comes first and change it to 1) player_out_f(); //change player output sign (X, O) c_player_display(); //print the line to ask for input while(filled == false){ //when the there is no input yet (the spot is not filled) cin >> x; // input if (x > 0 && x < 10){ //check if input is in range 1-9 filled_f(); //check if the spot is occupied } else if(x < 0 && x > 10) { //if input is out of range cout << "Invalid! Enter again!\n"; filled = false; //repeat the asking input circle (the while) } } game_start_display(); //output the board again with new char (X or O) end(); //check if anyone's won yet, if no, repeat the circle } cout << "Player " << in << " won! GG"; } A: You have infinite loop at while (filled == false) { ... }, because filled_f always sets filled to false (and the else if branch of the condition inside this loop as well does so). It's because you most likely missed figure brackets when writing else if block in filled_f. Your indentation hints that you wanted 2 statements to be in that block, but as of now, only the first is executed conditionally, and the second (filled = false;) is executed after the branch. In other words, with intuitive indentation this function looks like this: bool filled_f() { //check if the spot is filled if (out[x] != 'X' and out[x] != 'O') { filled = true; out[x] = player_out; //fill the input into the spot } else if (out[x] == 'X' or out[x] == 'O') cout << "The square has already been used!\n"; filled = false; return filled; } It sets filled = false; in any case, since if/else execute (depending on condition) the statement immediately following one of them (see here), and indentation is ignored (unlike in, e.g., Python, where indentation alone determines boundaries of conditions, loops, function etc), so only cout << ... is conditionally executed. To do what you want put figure brackets around appropriate statements the same way you already did for the first if branch to create compound statement (block) from them, which is a statement itself and does what you want - groups several other statements within it, executed in sequence: bool filled_f() { //check if the spot is filled if (out[x] != 'X' and out[x] != 'O') { filled = true; out[x] = player_out; //fill the input into the spot } else if (out[x] == 'X' or out[x] == 'O') { cout << "The square has already been used!\n"; filled = false; } return filled; } Additional remarks Note that logically it's not needed to have if condition in else since if the first if condition is dissatisfied, else if condition is definitely satisfied (look De Morgan's Laws) and you can just write else: // ... else { cout << "The square has already been used!\n"; filled = false; } // ... Also in your main loop, you use this: if (x > 0 && x < 10){ //check if input is in range 1-9 filled_f(); //check if the spot is occupied } else if(x < 0 && x > 10) { //if input is out of range cout << "Invalid! Enter again!\n"; filled = false; //repeat the asking input circle (the while) } to test whether x is within range, but your condition in else if is wrong (should be x <= 0 || x >= 10 instead of x < 0 && x > 10) and can be omitted altogether (again see De Morgan's Laws) by using just else.
{ "language": "en", "url": "https://stackoverflow.com/questions/72900938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to call Groovy script from Scala? <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <facts> <fact id="ItemPrice" displayName="Item Price"> <defaultValue>0</defaultValue> <script><![CDATA[ Double Value_Sales= 500; Double Unit_Sales= 10; Double res=Value_Sales/Unit_Sales; return res; ]]></script> </fact> </facts> Above is the sample groovy script written in xml file for finding item price. Java code for processing Groovy: List<Fact> factList = NREUtils.readXml("/SampleDictionary.xml") //cutome API GroovyShell shell = new GroovyShell(); String scriptStr = factList.get(0).getScript(); Script groovyScript = shell.parse(scriptStr); // return "ItemPrice" script Binding binding = new Binding(); groovyScript.setBinding(binding); Object val = groovyScript.run(); // **Result will be 50** I would like the corresponding Scala code for the same. A: Without further information on your problem, and being both languages (scala and groovy) executed over the JVM, I would suggest you just to compile your groovy code and include the jar in the classpath of the JVM running your scala code. Here you have some ideas about how to turn groovy code into usable bytecode: http://docs.groovy-lang.org/latest/html/documentation/tools-groovyc.html Then do just do as you would with any java library that you would like to call from scala: Using Java libraries in Scala
{ "language": "en", "url": "https://stackoverflow.com/questions/49645009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Multiple root modules on angular application I am developing a website in Angular. This app is divided into two parts: the client's part and the administrator's part. The latter is accessible via a login screen. The core of this mechanism is done with these two files: main.ts: import {enableProdMode} from '@angular/core'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {AppModule} from './app/app.module'; import {environment} from './environments/environment'; import {AdministrationModule} from "./administration/administration.module"; if (environment.production) { enableProdMode(); } if (window.location.href.indexOf("admin") != -1) { platformBrowserDynamic().bootstrapModule(AdministrationModule); } else { platformBrowserDynamic().bootstrapModule(AppModule); } index.html: <!doctype html> <html lang="it"> <head> <meta charset="utf-8"> <title>MyWebsite</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="icon.ico"> </head> <body> <app-root></app-root> <app-administration></app-administration> </body> </html> Basically if I point to the website normally http://mywebsite.com, I will upload the client part, while with http://mywebsite.com/admin I load the administration part with the login screen. My problem is that if I compile the app with these commands everything works correctly: ng build or ng serve while when I compile it for production it doesn't work: ng build --prod I've two questions now: is this an angular bug? Is it reliable to go into production simply with the ng build instead the ng build --prod command? I've tested with ng build (in production) and all works fine. Ah, one thing: during compilation the following warning appear: WARNING in Lazy routes discovery is not enabled. Because there is neither an entryModule nor a statically analyzable bootstrap code in the main file. A: You can have multiple applications in your angular project, it is how I solved a similar situation. https://angular.io/cli/generate#application-command This guide helped me get started. And here is another guide with some excellent examples. A: This is not a bug. When you run ng build --prod you run it with AOT compilation on. It means it compiles the app before the build to make sure everything set correctly. It seems like you are loading different Modules while bootstrapping your app and I'm not sure AOT compilation will agree to that. You can change to use Lazy Loaded modules and separate your apps to 2 different modules. If you really want then try ng build --prod --aot=false or ng build --prod --aot false. Since it seems like a scaling application, I think the best solution for you will be to use MonoRepo patterns. you'll have multiple apps with libraries and they both will sit under the same project. You could leverage a lot of re-usability and maintenance will be easier. Check Nrwl/Nx for Angular Here they provide great tooling for this. It supports angular cli by using schematics. I think it will help you a lot. maybe you would need to deploy your apps to different places or having some different environments to use for each app, and this monorepo is a perfect fit to achieve that IMHO. More about monorepos from Wikipedia: Advantages There are a number of potential advantages to a monorepo over individual repositories: * *Ease of code reuse – Similar functionality or communication protocols can be abstracted into shared libraries and directly included by projects, without the need of a dependency package manager. *Simplified dependency management – In a multiple repository environment where multiple projects depend on a third-party dependency, that dependency might be downloaded or built multiple times. In a monorepo the build can be easily optimized, as referenced dependencies all exist in the same codebase. *Atomic commits – When projects that work together are contained in separate repositories, releases need to sync which versions of one project work with the other. And in large enough projects, managing compatible versions between dependencies can become dependency hell.[5] In a monorepo this problem can be negated, since developers may change multiple projects atomically. *Large-scale code refactoring – Since developers have access to the entire project, refactors can ensure that every piece of the project continues to function after a refactor. *Collaboration across teams – In a monorepo that uses source dependencies (dependencies that are compiled from source), teams can improve projects being worked on by other teams. This leads to flexible code ownership. Limitations and disadvantages * *Loss of version information – Although not required, some monorepo builds use one version number across all projects in the repository. This leads to a loss of per-project semantic versioning. *Lack of per-project security – With split repositories, access to a repository can be granted based upon need. A monorepo allows read access to all software in the project, possibly presenting new security issues. Hope it'll help you
{ "language": "en", "url": "https://stackoverflow.com/questions/55538438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to read any local file by chunks using JavaScript? How can I read any large file(greater than 1 gigabytes) locally by chunks(2kb or more),and then convert the chunk to a string, process the string and then get the next chunk and so on until the end of the file? I'm only able to read small files and convert it to string, as you can see from the code I don't know how to read the file by chunks. The browser freezes if I try it with a file greater than 10mb. <html> <head> <title>Read File</title> </head> <body> <input type="file" id="myFile"> <hr> <textarea style="width:500px;height: 400px" id="output"></textarea> <script> var input = document.getElementById("myFile"); var output = document.getElementById("output"); input.addEventListener("change", function () { if (this.files && this.files[0]) { var myFile = this.files[0]; var reader = new FileReader(); reader.addEventListener('load', function (e) { output.textContent = e.target.result; }); reader.readAsBinaryString(myFile); } }); </script> </body> </html> Below are the links and answers I found on StackOverflow whilst researching on how to accomplish it, but it didn't solve my question. 1: This question was asking about how to do it using UniversalXPConnect, and only in Firefox, which is why i found the answer there to be irrelevant, because I use Chrome and don't know what UniversalXPConnect is. How to read a local file by chunks in JavaScript 2: This question was asking about how to read text files only, but I want to be able to read any file not just text, and also by chunks, which makes the answers there irrelevant, but i liked how short the code of the answer was. Reading local text file into a JavaScript array [duplicate] 3: This also is about text files and doesn't show how to read files by chunks How to read a local text file. I know a little bit of Java, which you can easily do it by; char[] myBuffer = new char[512]; int bytesRead = 0; BufferedReader in = new BufferedReader(new FileReader("foo.mp4")); while ((bytesRead = in.read(myBuffer,0,512)) != -1){ ... } but I'm new to javascript A: I was able to solve it by slicing the file by specifying attributes of where to begin the slice and where to end which will be the chunk, I then enclosed it in a while loop so that for each loop chunk position will shift according to the desired chunk size until the end of the file. But after running it, I end up getting the last value of the chunk in the text area, so to display all the binary string i concatenate the output on each iteration. <html> <head> <title>Read File</title> </head> <body> <input type="file" id="myFile"> <hr> <textarea style="width:500px;height: 400px" id="output"></textarea> <script> var input = document.getElementById("myFile"); var output = document.getElementById("output"); var chunk_size = 2048; var offset = 0; input.addEventListener("change", function () { if (this.files && this.files[0]) { var myFile = this.files[0]; var size = myFile.size; //getting the file size so that we can use it for loop statement var i=0; while( i<size){ var blob = myFile.slice(offset, offset + chunk_size); //slice the file by specifying the index(chunk size) var reader = new FileReader(); reader.addEventListener('load', function (e) { output.textContent += e.target.result; //concatenate the output on each iteration. }); reader.readAsBinaryString(blob); offset += chunk_size; // Increment the index position(chunk) i += chunk_size; // Keeping track of when to exit, by incrementing till we reach file size(end of file). } } }); </script> </body> </html> A: So the issue isn't with FileReader, it's with : output.textContent = e.target.result; Because you are trying to dump 10MB+ worth of string into that textarea all at once. I'm not even sure there is a "right" way to do what you are wanting, since even if you did have it in chunks, it would still have to concat the previous value of output.textContent on each loop through those chunks, so that as it gets closer to the end, it would start slowing down in the same way (worse, really, because it would be doing the slow memory hogging business on every loop). So I think part of the looping process is going to have to be adding a new element (like a new textarea to push the current chunk to (so it doesn't have to do any concatenation to preserve what has already been output). I haven't worked that part out yet, but here's what I've got so far: var input = document.getElementById("myFile"); var output = document.getElementById("output"); var chunk_length = 2048; //2KB as you mentioned var chunker = new RegExp('[^]{1,' + chunk_length + '}', 'g'); var chunked_results; input.addEventListener("change", function () { if (this.files && this.files[0]) { var myFile = this.files[0]; var reader = new FileReader(); reader.addEventListener('load', function (e) { chunked_results = e.target.result.match(chunker); output.textContent = chunked_results[0]; }); reader.readAsBinaryString(myFile); } }); This is just outputting the first string in the array of 2KB chunks. You would want to do your thing as far as adding a new element/node in the DOM document for outputting all the other chunks. Using RegExp and match for the actual chunking was lifted from a clever gist I found. A: You can do that using fs.createReadStream(), The amount of data potentially buffered depends on the highWaterMark option passed into the streams constructor. So you would do it like this: var read = fs.createReadStream('/something/something', { highWaterMark: 64 }); here's an example : var fs = require('fs') var read = fs.createReadStream('readfile.txt',{highWaterMark:64}) var write = fs.createWriteStream('written.txt') read.on('open', function () { read.pipe(write); }); see how it reads 64 bytes at a time (Very Slow), you can view it on explorer in a fun way, but make sure you have a large text file to test it not a gigabyte but at least 17 megabytes like I did "fill it with any dummy text" make the file view to "details" and keep refreshing the destination in windows explorer, you will see the size increase on every refresh. I assumed you know about the pipe method if you don't, no problem! it's very simple, here is a link: https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options or a quick explanation : readable.pipe(writable) The pipe() function reads data from a readable stream as it becomes available and writes it to a destination writable stream.
{ "language": "en", "url": "https://stackoverflow.com/questions/50254537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Bash on cygwin: No such file or directory commonMongo=s:/programs/mongodb/ dbpath=$commonMongo"data/" logFile=$commonMongo"log.txt" mongoProg=s:/programs/mongodb/mongodb/ mongoBin=$mongoProg"bin/" mongod=$mongoBin"mongod.exe" a=$1 if [ "$a" == "start" ];then "${mongod} --logpath ${logFile} --logappend --dbpath ${dbpath} &" elif [ "$a" == "repair" ];then "${mongod} --dbpath ${dbpath} --repair" else echo "Incorrect usage" fi ./init.sh: line 11: s:/programs/mongodb/mongodb/bin/mongod.exe --dbpath s:/programs/mongodb/data/ --repair: No such file or directory Calling the printed command works fine: s:/programs/mongodb/mongodb/bin/mongod.exe --dbpath s:/programs/mongodb/data/ --repair A: Cygwin will actually do magic for you if you put your DOS paths in quotes, for example cd "C:\Program Files\" A: Cygwin does not recognize Windows drive letters such as s:, use /cygdrive/s instead. Your cygwin command should look like this: /cygdrive/s/programs/mongodb/mongodb/bin/mongod.exe --dbpath s:/programs/mongodb/data/ --repair Notice that the path like parameters you pass to the executable are in windows format as mongod.exe is not a Cygwin binary. To make it easier, you could add mongod.exe your path, then you do not need to specify the directory it is in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Save related Object Symfony 2 I have User and Posts. One To Many //user.php /** * @ORM\OneToMany(targetEntity="Post", mappedBy="posts") */ private $posts; public function __construct () { $this->posts = new ArrayCollection(); } post.php /** * @ORM\ManyToOne(targetEntity="User", inversedBy="posts") * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */ private $posts; controller $post->setPosts($this->getUser()); $em->persist($post); $em->flush(); I have to use setPosts for persist related user? Can I save with cascade or something of this? I know that There are two kinds of cascades in Doctrine: 1) ORM level 2) Database level But I don't understand when use cascade={"persist"}) My questions are: * *How can I save user related from post object? *When and Why use cascade={"persist"})? update I tried //user /** * @ORM\OneToMany(targetEntity="Post", mappedBy="posts",cascade={"persist"}) */ private $posts; controller $user = $this->getUser(); $user->addPost($post); $em->persist($user); $em->flush(); But doesn't works, the field user_id in database is empty A: Your entities should look like this : User.php class User { /** * @ORM\OneToMany(targetEntity="Post", mappedBy="user", cascade={"persist"}) */ private $posts; public function addPost(Post $post) { $post->setUser($this); // Call Post's setter here $this->$posts[] = $post; // Add post to the collection } } Post.php class Post { /** * @ORM\ManyToOne(targetEntity="User", inversedBy="posts") */ private $user; public function setUser(User $user) { $this->user = $user; // Set post's author } } In that case, you could use cascade if you are creating the user and its posts at the same time : you want to persist both the user and the posts, and attach the posts to the user. If the user already exists at time you're persisting the post, you just have to set the post's author and persist the latter : Controller.php public function editPostAction() { // ... $post->setUser($this->getUser()); $em->persist($post); $em->flush(); // ... } By the way, in a One-To-Many relation, the owning side is the Many side, Post in this case. A: /** * @ORM\OneToMany(targetEntity="Post", mappedBy="posts", cascade={"persist"}) */ private $posts; So all $em->persist($user); does is tell the entity manager that it should be managing $user. An entity being managed just means that when you call $em->flush() it will save that entity in its current state to the database, either by creating a new row in all the tables required, or updating the existing ones. So to actually answer your question. By adding the cascade={"persist"} to this annotation, the entity manager knows that if this User object is being managed, when a flush call is made, it will also need to perform whatever cascade operations you have defined for all Post objects associated with this User, and save their changes (or create new rows as required) to the database (or delete if you have cascade delete and remove a post from this user's post collection).
{ "language": "en", "url": "https://stackoverflow.com/questions/27512469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Devise authenticate_user! not working properly Here is my custom Registrations controller: class RegistrationsController < Devise::RegistrationsController def create build_resource if resource.valid? && resource.save_with_subscription set_flash_message :notice, :signed_up if is_navigational_format? sign_in resource_name, resource WelcomeMailerWorker.perform_async(resource.id) return render json: { success: true, path: after_sign_up_path_for(resource) } else clean_up_passwords(resource) return render json: { success: false, errors: resource.errors.full_messages.to_sentence } end end def destroy current_user.soft_delete Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name) set_flash_message :notice, :destroyed if is_navigational_format? respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) } end def after_sign_up_path_for(resource) return finalize_profile_path if resource.athlete? return root_path if resource.college_coach? end def check_username @user = User.find_by_username(params[:username]) return render text: @user.nil? end end Routes: devise_for :users, skip: :registrations, controllers: { sessions: "sessions", passwords: "passwords" } devise_for :athletes, skip: [:sessions, :passwords], controllers: { registrations: "registrations" } devise_for :coaches, skip: [:sessions, :passwords], controllers: { registrations: "registrations" } When the user is redirected to finalize_profile_path, the authenticate_user! method returns a 401 unauthorized for some reason I did some further debugging and it appears that Devise is not signing in the user at all after registration
{ "language": "en", "url": "https://stackoverflow.com/questions/17953638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: doxygen and graphviz doesn't generate map files I am trying Graphviz and doxygen on a rather large C++ library to generate UML. It generates the .dot files but then says it can't open the .map files. I am running doxygen 1.8.3 and 2.30.1 installed via the msi on Windows 7 64bit. I also manually set the path to the Graphviz bin folder. Errors look like: error: problems opening map file /inherit_graph_11.map for inclusion in the docs! A: Because I had simmilar problems and needed a lot of time to fix it, I will summarize the important facts for getting it running: * *Install doxygen AND graphviz *Add the bin directory of graphviz to your windows path variable (e.g. C:\Program Files (x86)\Graphviz2.38\bin) *In the Settings.ini located in the graphviz bin directory, also set the path (e.g. binPath=C:\Program Files (x86)\Graphviz2.38\bin) *In doxygen, under the tab "Expert" -> Dot check "HAVE_DOT" *In doxygen, under the tab "Expert" -> Dot set "DOT_PATH" to your graphviz bin directory like above These steps did it to make it working for me. A: I know you found your solution, but for the sake of people like myself coming from Google, I'd like to make this as easy as possible for everyone. If you're on Windows, and have installed both Doxygen and Graphviz, or if you're on Linux and have used apt-get install doxygen graphviz, the next step is to make sure that you're able to run the dot command from the command prompt/terminal. You can do this by making sure that the Graphviz/bin folder is appended to your PATH file. Refer to this answer (removed by SO so here is a archive.org link) if you need more details on how to properly set up Doxygen/Graphviz for visualizations A: On Windows 10 in 2017, I needed to: * *Install graphviz from http://graphviz.org/ *In the Dot heading under the Doxygen expert tab, populate DOT_PATH with "C:\Program Files (x86)\Graphviz2.38\bin" *In the Diagrams heading under the Doxygen Wizard tab, select "Use dot tool from the GraphVizPackage" A: * *Go to Control Panel and search for Edit System Environment Variables *Go to System Properties -> Environment settings -> Path *Add the path to your Graphviz bin folder at the end of the Path variables. They are separated with a semicolon ";" See example below, where I added: ; C:\Program Files (x86)\Graphviz2.38\bin Alternatively you can use the Setx command from the command window.
{ "language": "en", "url": "https://stackoverflow.com/questions/17936283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }