text
stringlengths
14
21.4M
Q: Mage Secret Duplicate interaction with AoE damage Let's take for example, enemy mage has Dr Boom at 2 health, and some other minions also at 2 health. She has a duplicate secret up. If I consecrate (deal 2 damage to all enemies) and kill all the enemy minions simulataneously, which minion would get duplicated? A: The secret will give the mage two copies of the minion that dies first. The order in which they die is determined by the order in which they were played. So if the opponent dropped his other minions before Dr Boom, then one of them will get duplicated; if he dropped Dr Boom first, then it will be duplicated. The Boom Bots that are summoned with Dr Boom are "played" part of his Battlecry effect, so (if they're still alive when you use Consecration) they will die after him in your scenario. The Duplicate gamepedia page also has a note on this: When multiple friendly minions are killed simultaneously, Duplicate will copy the minion that was put into play earliest.
Q: Dynamodb GetBatchItem vs query Currently I use table.query to get items by matching partition key and sorted by sorting key. Now the new requirement is to handle batch query - a couple of hundred partition keys match and hopefully still sorted by sorting key in each partition key result. I find GetBatchItem that can handle up to 100 items per one query, but look like no sorting. Is one item here one row in DDB or all rows in one partition key? From performance(query speed) and price perspective which one should I use? And do i have to do sorting for the result by myself if I use GetBatchItem? Ideally I like a solution of fast, cost effective and result sorted by sorting key in each partition key, but the first two are top priority and I can do sorting if I have to. Thanks A: Query() is cheaper... BatchGetItem() runs as individual GetItem() each costing 1 RCU (assuming your item is less than 400K). Lets say you're item is 10K, Query() can return 40 of them for 1 RCU whereas returning 40 via BatchGetItem() will cost 40 RCU.
Q: Missing architecture when adding framework to AIR Native Extension (ANE) Currently I'm working on a Native Extension for AIR. I already got it working perfectly for android and I'm now taking on iOS. So far I've got it running and I have every method do some basic things, like showing an alert message. So I know the ANE is building and working fine by itself. But now the problem I'm facing. I try to add some frameworks. One I build myself and is working in native apps and some third party ones. The ANE is still building fine, but when I add it to a testproject and run it, it says it's ignoring my file for missing the right architecture. ld: warning: ignoring file /var/folders/zn/r6p91gln37n2323yj8rw1q6c0000gp/T/0bd78fa0-1b71- 4371-a6c5-a4ad3073df62/libcom.mycompany.myproduct.a, missing required architecture armv7 in file /var/folders/zn/r6p91gln37n2323yj8rw1q6c0000gp/T/0bd78fa0-1b71-4371-a6c5-a4ad3073df62/libom.mycompany.myproduct.a (2 slices) ld: file too small for architecture armv7 Compilation failed while executing : ld64 I have them added in my platform options: <platform xmlns="http://ns.adobe.com/air/extension/3.8"> <sdkVersion>6.0</sdkVersion> <linkerOptions> <option>-ios_version_min 6.0</option> <option>-framework coreTelephony</option> <option>-framework EventKit</option> <option>-framework MediaPlayer</option> <option>-framework MessageUI</option> <option>-framework SystemConfiguration</option> <option>-framework AdSupport</option> </linkerOptions> <packagedDependencies> <packagedDependency>ios/myproduct.framework</packagedDependency> </packagedDependencies> </platform> And I package it int the build command. adt -package -target ane myproduct.ane extension.xml -swc myproduct.swc -platform Android-ARM -C android . -platform iPhone-ARM -platformoptions iosoptions.xml ios/myproduct.framework -C ios . -platform default -C default .; So can someone explain why it is correctly building the ane, but it cannot be run? And perhaps you can put me on the right track to solve this. Thanks in advance. A: I have figured it out. I was pointed in the wrong direction. It was the ANE itself that caused the problem. It was not properly build for armv7, the build target for the native library was set to the simulator. I changed it to iOS device and it worked. Of course I'm going to make it compile for both the simulator and real devices soon. If anyone stumbles upon this problem, feel free to send me a message and perhaps I can help. A: It's from the Xcode Menu (on the right of the build button), you choose iOS device instead of the iOS simulator and then press the build button.
Q: Define the location of Java fatal error log in runtime is there any way to define the location of the fatal error logs in Java (hs_err_*.pid.log) in the runtime? I know from [1] that I can set the location as parameter, but I want to change it in runtime. Philip [1] http://java.sun.com/javase/6/webnotes/trouble/TSG-Desktop/html/felog.html A: From http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp: "Options that are specified with -XX are not stable and are not recommended for casual use. These options are subject to change without notice." From the same page, there is indication that that the ErrorFile option is not manageable through JConsole, so I wouldn't expect it to be modifiable through any other means.
Q: how to pass java script value to php variable function myfun(){ var texteld= document.getElementById('texteld').value; <?php $id = "<script>texteld</script>"; } This PHP and JavaScript code does not working. i want to pass java script texteld value to PHP $id A: To pass a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible) var variableToSend = 'foo'; $.post('file.php', {variable: variableToSend}); On your server, you would need to receive the variable sent in the post: $variable = $_POST['variable']; Or use This function myJavascript() { var texteld = document.getElementById('texteld').value; window.location.href = "test2.php?name=" + texteld; } In php file get variable like these code <?php if(isset($_GET['name'])){ $name= $_GET['name']; echo $name; } ?> A: To Answer your question, you need to understand how a page loads: * *Request to server. *Server Processes request, load pages, run php, whatever needs to be done. *Server outputs html,css,javascript, whatever the process from 2 tells it to. *Finally, your browser interprets all the data and gives you a layout. So, as you can see, php is run before javascript is even sent to the browser to be run. What you want to do is go backwards in the process, this is not possible. After the page loads and the browser has some data, you can send data back to php. This is not the same as your attempt though. You may need to rethink your strategy.
Q: My React app's proxy not working in docker container When I working without docker(just run React and Django in 2 sep. terminals) all works fine, but when use docker-compose, proxy not working and I got this error: Proxy error: Could not proxy request /doc from localhost:3000 to http://127.0.0.1:8000. See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED). The work is complicated by the fact that each time after changing package.json, you need to delete node_modules and package-lock.json, and then reinstall by npm install (because of the cache, proxy changes in package.json are not applied to the container). I have already tried specifying these proxy options: "proxy": "http://localhost:8000/", "proxy": "http://localhost:8000", "proxy": "http://127.0.0.1:8000/", "proxy": "http://0.0.0.0:8000/", "proxy": "http://<my_ip>:8000/", "proxy": "http://backend:8000/", - django image name Nothing helps, the proxy only works when running without a container, so I conclude that the problem is in the docker settings. I saw some solution with nginx image, it doesn't work for me, at the development stage I don't need nginx and accompanying million additional problems associated with it, there must be a way to solve the problem without nginx. docker-compose.yml: version: "3.8" services: backend: build: ./monkey_site container_name: backend command: python manage.py runserver 127.0.0.1:8000 volumes: - ./monkey_site:/usr/src/monkey_site ports: - "8000:8000" environment: - DEBUG=1 - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 depends_on: - redis networks: - proj_network frontend: build: ./frontend container_name: frontend ports: - "3000:3000" command: npm start volumes: - ./frontend:/usr/src/frontend - ./monkey_site/static:/usr/src/frontend/src/static depends_on: - backend networks: - proj_network celery: build: ./monkey_site command: celery -A monkey_site worker --loglevel=INFO volumes: - ./monkey_site:/usr/src/monkey_site/ depends_on: - backend - redis redis: image: "redis:alpine" networks: proj_network: React Dockerfile: FROM node:18-alpine WORKDIR /usr/src/frontend COPY package.json . RUN npm install EXPOSE 3000 Django Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /usr/src/monkey_site COPY requirements.txt ./ RUN pip install -r requirements.txt package.json: { "name": "frontend", "version": "0.1.0", "private": true, "proxy": "http://127.0.0.1:8000", "dependencies": { ... In Django I have django-cors-headers and all settings like: CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'http://127.0.0.1:3000', ] Does anyone have any ideas how to solve this problem?
Q: Proving That A Sequence Does Not Obey The Weak Law Of Large Numbers I have a sequence $f_n$ of random variables such that $\mu( \{ f_n = n \}) = \mu( \{f_n = -n \}) = \frac{1}{2}$, and need to prove that it doesn't satisfy WLLN. Clearly, $E(f_n) = 0$, so I have to disprove that $$ \frac{1}{n} \sum_{j=1}^n f_j (\omega) \to 0$$ in measure. In other words, $$\lim_{n \to \infty} \mu \left( \omega: | \frac{1}{n} \sum_{j=1}^n f_j (\omega)| \ge \delta \right) \ne 0$$ $\forall \delta > 0.$ In my textbook, I haven't really learned much about how to do these types of questions. As a hint, I was told to show that if $\frac{1}{n} \sum_{j=1}^n f_j \to 0$ in measure $\mu$, then also $\frac{1}{n} \sum_{j=1}^{n-1} f_j \to 0$ in measure $\mu$. However, I dont know how to show this and even if I were able to, I don't see why that means $f_n$ doesn't obey the Weak Law of Large Numbers. I would gladly appreciate any help. A: If $$\frac{1}{n} \sum_{j=1}^n f_j \to 0 \quad (1) $$ in measure then (changing indices $n \mapsto n-1$) also $$\frac{1}{n-1} \sum_{j=1}^{n-1} f_j \to 0 $$ in measure. Multiply by $ (n-1)/n$ to get $$\frac{1}{n} \sum_{j=1}^{n-1} f_j \to 0 \,$$ in measure. Subtract this from (1) and obtain $$\frac{1}{n} f_n \to 0 $$ in measure, which contradicts the given law of $f_n$. A: Take the difference, i.e., $$ \frac{1}{n}\sum_{i=1}^n f_i-\frac{1}{n}\sum_{i=1}^{n-1} f_i=\frac{f_n}{n}. $$ The LHS converges to $0$ (in $\mu$-measure). Thus, $f_n/n$ must converge to $0$ as well. However, $$ \mu(|f_n/n|>1/2)=1 $$ for each $n$. The observation in the hint follows from the fact that if $\sum_{i=1}^n f_i/n\to 0$, then $$ \frac{1}{n}\sum_{i=1}^{n-1}f_i=\frac{n-1}{n}\times \frac{1}{n-1}\sum_{i=1}^{n-1}f_i\to 0 $$ in $\mu$-measure.
Q: Odoo v11, Error: "res.users, Operation: read None", while creating a new user and assign to new company I have a problem creating a new user on Odoo and assign to a company that I created v. 11. First on companies I created a new company name "XXXX". Then I created a new user "YYY" and on the multicompany field I assigned on "allowed companies" the company "XXXX", and on "Current Company" I assigned the company "XXXX". The problem is that when i try to save the new user created I received this error: "Error while validating constraint The requested operation cannot be completed due to security restrictions. Please contact your system administrator. (Document type: res.users, Operation: read) None " The only way i can save the new user is by selecting on the field "Allowed Companies" the default company created from the system. Is there something I did wrong while creating the new company "XXXX" or is there some relation and/or rights that are particular important between user and company?
Q: Pointer to class object in overloading prefix and postfix operators I overloaded prefix and postfix increment/decrement operators in a class. #include <iostream> using namespace std; class X { public: X() { cout << "X" << endl;} ~X() { cout << "~X" << endl; } X& operator++() { X *x = new X; return *x; } X operator++(int) { X *x = new X; return *x; } X& operator--() { X *x = new X; return *x; } X operator--(int) { X *x = new X; return *x; } }; int main() { X p; cout << endl; ++p; cout << endl; p++; cout << endl; return 0; } Output is: X X X ~X ~X It seems that when using postfix increment, object gets instantiated and deleted, but when using prefix increment it doesn't get deleted. What is the cause of this behaviour? A: Your postfix operators return by value, so the object you created with new is copied, and since you don't bind it to anything the copy gets destroyed at the end of the postfix expression in main. By also having the copy constructor output something you can observe this behavior, see for example here. You prefix operators on the other hand just return a reference to the object you allocated with new, so at the end of the expression in main just the reference is destroyed. In both cases you're leaking the memory allocated by new. A: The postfix version returns an instance of X, not a reference to an instance, so the destructor of this copy is called. Anyway, you should not have to use new in your operators: X& operator++() { return *this; } X operator++(int) { X x; return x; }
Q: Right way to use gapi.client.drive in chrome extension I'm trying to use drive to save data from chrome extension. First, I set needed options to manifest.json "oauth2": { "client_id": "999999.apps.googleusercontent.com", "scopes": [ "https://www.googleapis.com/auth/drive.appdata" ] }, Then try to get list of files: $.getScript("https://apis.google.com/js/client.js", function () { gapi.load('client', function () { console.log("gapi.client is loaded") gapi.client.load('drive', 'v3', function () { console.log("gapi.client.drive is loaded"); chrome.identity.getAuthToken({'interactive': true}, function (token) { gapi.client.setToken({access_token: token}); console.log("token :", token); gapi.client.drive.files.list().then(function (list) { console.log(list) }) }); }); }); }); Console said: gapi.client is loaded gapi.client.drive is loaded token : [TOKEN] And the error is like that: "code": 403, "message": "The granted scopes do not give access to all of the requested spaces." A: The error indicates that you are trying to access unauthorized spaces. Your scope only allows you to use the "appDataFolder" space. Therefore, you have to change gapi.client.drive.files.list() for gapi.client.drive.files.list({spaces:"appDataFolder"}).
Q: Using "have" or "had" for an ongoing relationship What would be the proper grammar for this sentence when using have and had? Which is correct (it's about relationship that is still existing for 28 years until now): * *It's the best relationship I ever have. *It's the best relationship I ever had. A: I believe your answer is a mix of both. It shows it's your favourite and on-going: "It's the best relationship I have ever had"
Q: Why does the StringBuffer class uses an Array as it's underlying data structure instead of a LinkedList? The StringBuffer/StringBuilder classes in Java are primarily used to modify String values without having to initialize a new String object everytime. Is there a specific reason, it doesn't use a LinkedList instead of an Char Array as it's underlying data structure? Inserting a char into a Array will always result in a O(n) time to copy all elements to the next index, where as that that be done in O(1) time in case of a LinkedList. A: Random access StringBuilder has random access operations such as charAt or substring, which would be extremely slow with a linked list. Insertions In fact, array lists aren't particularly slower than linked lists even when it comes to other operations like insertion. Typically StringBuilder won't be used to create strings of a million characters so it's unlikely that we need to resize the buffer too many times. * *At the end I have to correct you that insertion at the end always requires a O(n) copy of elements. The worst-case is indeed O(n) but the amortized complexity is O(1) because we don't just allocate one element at a time. When the array isn't big enough to make another insertion, most implementations double the size of the array. * *In the middle Insertions in the middle always require the copy of elements at the right of the insertion, so yes it is pretty slow but it's not a typical use-case for a StringBuilder where most insertions happen at the end. Also, linked lists have the same average complexity on insertions in the middle since they first have to reach the right node by iterating the list. Data locality Another advantage of arrays compared to linked list is data locality. Array lists are faster to iterate than linked lists because when the processor loads a piece of memory around an element of an array, it will also cache some of the neighbours of this element which will therefore be returned faster. On the other hand, all elements of a linked list may live in very distant memory locations, which is not cache-friendly. Memory footprint Because we double the size of the array of every resize, dynamic arrays can have a pretty big memory footprint (but at least we won't need to copy elements too often). Linked lists also have a fairly large memory footprint since they require one additional reference and a pointer for each element while elements are compactly stored in an array. On average, I'd say a typical array list will have a smaller memory footprint than a linked list but I may be wrong. This is particularly the case for primitive types - such as char - because linked lists require wrapper objects (at least in Java since there are no pointers) whereas we can use much more compact primitive arrays. Last notes Finally, I used StringBuilder in my answer instead of StringBuffer because this is the recommended implementation for most use-cases. StringBuffer is only preferrable when thread-safety is a hard requirement. Otherwise, StringBuilder will have better performance. PS: Python's most prominent data structure is list and guess what... it's implemented with a dynamic array! Resizable arrays are very often a better choice than linked lists. The only case in which a linked list is notably more performant is when the application focuses on elements close to the head of the list and makes frequent insertions or deletions in this area.
Q: regular user to admin user in linux? i've got a regular user i want to turn into admin group so he can have same privileges as a root. should i just change the GID in /etc/passwd and /etc/group or should i use usermod/groupmod? A: You do not want to make this user EXACTLY the same as root. Don't change uid and gid. You have a few options: * *Use sudo. sudo lets a user execute a command or start a shell as root, without needing the root password. However, the admin of the computer can tightly control which commands a user can "sudo". Read up the man page. But if you want an easy "let this user run any thing with sudo", put this user in the /etc/sudoers file. Even better, put this user in the admin group then add the line %admin ALL=(ALL) ALL to /etc/sudoers. On Ubuntu, this is probably your best option as sudo is installed by default. *Put this user in the wheel or admin group. This user won't be root, but will have the same access to files as everyone else in wheel or admin. *Give the user the root password and make this user use su <cmd>. This is a bad idea. On recent versions of Ubuntu, the root account can't login by default so you can't do this. A: Your best bet under ubuntu is to add the person to the sudoers file. You should use visudo to edit this file. If you hate vi, you can set the EDITOR shell variable to use your preferred editor. You have many choices when adding a peson as a sudoer. You don't have to give them blanket root access if you don't want to. In general the lines in /etc/sudoers looks like: usernames/group servername = (usernames command can be run as) command There are some general guidelines when editing this file: * *Groups are the same as user groups and are differentiated from regular users by a % at the beginning. The Linux user group "users" would be represented by %users. *You can have multiple usernames per line separated by commas. *Multiple commands also can be separated by commas. Spaces are considered part of the command. *The keyword ALL can mean all usernames, groups, commands and servers. *If you run out of space on a line, you can end it with a back slash () and continue on the next line. *sudo assumes that the sudoers file will be used network wide, and therefore offers the option to specify the names of servers which will be using it in the servername position in Table 9-1. In most cases, the file is used by only one server and the keyword ALL suffices for the server name. *The NOPASSWD keyword provides access without prompting for your password. You can use /etc/sudoers to grant specific access to specifc people for any or all applications. This site includes some decent examples. A: In a default Ubuntu installation, you can simply add the user to the "admin" group: adduser USERNAME admin.
Q: query to fetch record without duplication MS-access query : group by name and age, and get the detail without duplicate data(name and age) please find below the detail table schema: id: integer name: varchar(100) age: integer city: varchar(100) records in table: ------------------------------------ id| name | age | city ------------------------------------ 1 | ram | 25 | bhopal 2 | brajesh | 30 | indore 3 | ram | 25 | indore 4 | ram | 26 | bhopal 5 | ram | 27 | mumbai 6 | brajesh | 30 | mumbai 7 | brajesh | 26 | dehli ------------------------------------ Expected result : ------------------------------------ name | age | city | city ------------------------------------ ram | 25 | bhopal | indore brajesh | 30 | indore | mumbai ------------------------------------ Other format of Expected output : Expected result : ------------------------------------ name | age | city ------------------------------------ ram | 25 | bhopal, indore brajesh | 30 | indore, mumbai ------------------------------------ A: This will do the trick : select distinct d1.name, d1.age, concat(d1.city, ' , ' ,d2.city) AS city from Details d1 join Details d2 on d1.name = d2.name and d1.age = d2.age and d1.city != d2.city and d1.id < d2.id Here is the SQLFiddle Also note that for this to work id must be unique. A: Unfortunately it is impossible to get first output by query, due to need spawning columns for every distinct city. This is how to get second variant in ms-access, but it is not optimal: define sfunction public function SitiesOf(Name as String,Age as long) as String dim rst as recordset SitiesOf = ", " set rst = currentdb.Openrecordset("SELECT [city] FROM [Table] WHERE [name]='" & Name & "' AND [age]=" & Age & ";") while not rs.eof SitiesOf = SitiesOf & rst![city] & ", " rst.MoveNext wend rst.close set rst=Nothing SitiesOf = left(SitiesOf , len(SitiesOf)-2) end function Write query SELECT [name] , [age] , SitiesOf([name],[age]) FROM [Table] GROUP BY [name] , [age]
Q: Parsing DNS Response I am having some trouble with parsing DNS Response. Following is my code. The following are the structures. I'm getting a segmentation fault in the printf(), where im trying to print QNAME. I'm pretty amateur when it comes to C programming, so im not really sure where im going wrong. Any helps/hints or link to useful resources/tutorials, will be appreciated. The function verfify_header() works correctly. I'm not sure why HEADER is properly extracted using memcpy(). and other fields are not. struct HEADER{ unsigned short ID; unsigned char RD:1; unsigned char TC:1; unsigned char AA:1; unsigned char Opcode:4; unsigned char QR:1; unsigned char RCODE:4; unsigned char Z:3; unsigned char RA:1; unsigned short QDCOUNT; unsigned short ANCOUNT; unsigned short NSCOUNT; unsigned short ARCOUNT; }; struct REQ_DATA{ unsigned short qtype; unsigned short qclass; }; struct QUESTION{ char* qname; struct REQ_DATA field; }; struct RES_DATA{ unsigned short type; unsigned short class; unsigned int ttl; unsigned short rdlength; }; struct RESPONSE{ char* name; struct RES_DATA field; char* rdata; }; The following is the function that parses the dns response. void parse_response(char *recvbuf, struct result *res) { struct HEADER *rechd = (struct HEADER*) malloc(sizeof(struct HEADER)); struct QUESTION qst; struct RESPONSE *rp = (struct RESPONSE*) malloc(sizeof(struct RESPONSE)); struct RES_DATA fld; char* rname = (char*)malloc(sizeof(char)); int hlen,qlen,rlen; hlen = sizeof(struct HEADER); memcpy(rechd,recvbuf,hlen); verify_header(rechd); //This function works correctly qlen = sizeof(struct QUESTION); //RESPONSE is after QUESTION and HEADER rlen = sizeof(struct RESPONSE); int length = hlen + qlen; rp = (struct RESPONSE*)(recvbuf + length); //memcpy(rp, recbbuf + length, sizeof(struct RESPONSE)); memcpy(rname, rp, strlen(rname) + 1); printf("QNAME: %s\n", *rname); //Segmentation Fault occurs over here!!!!! } Thanks, Chander A: The problem is that you're trying to use C structures to parse data from over the network. If your machine is big endian and your compiler happens to order bitfields the way you want them ordered, this might work okay (until you get to the pointer fields...), but it's very fragile. You should be parsing packets as an array of unsigned char. Now, look at this: struct QUESTION{ char* qname; struct REQ_DATA field; }; This is a structure that's 8 or 16 bytes (depending on your platform), nothing like the variable-length field in the actual DNS packet. And there's certainly no way you're going to get a valid pointer (which would be local to your own machine and process's address space) out of the data off the network.
Q: Using MrVector with Butter Knife The app I'm working uses vector images, and I'm trying to implement pre-API 21 support for them using MrVector. I'm aware that variables can't be passed into @InjectView() - is there any way of working around this?
Q: How to make a flash object render NOT in top z-level? I have a webpage with DHTML navigation menu. On the page also have an embedded flash object. Currently when I activated a DHTML menu, the opened menu items list appear below the flash. How could I make the DHTML menu items to appear on top of the flash object. I reckon that there will be an attribute that we could use while writing or tag for the flash object. I hope the solution will work across all major browser (Firefox3, IE6, IE7, IE8, Chrome, and Safari). Thanks. A: Flash objects are by default placed over top of DHTML. To make a Flash object rendered as part of the DOM and obey the appropriate z-index you need to set the wmode attribute to transparent as follows: <div class="flashthingy"> <object width="295" height="248"> <param name="wmode" value="transparent"></param> <embed src="http://www.foobar.com/" type="application/x-shockwave-flash" wmode="transparent" width="295" height="248"></embed> </object> </div> Now you can set the appropriate z-index and the Flash object should obey.
Q: Can't open .apk file on android device I created a mobile application using kivy, but after having it installed on android device, it does not launch. Below is the buildozer.spec file. title=Translator package.domain=org.test source.dir=. source.include_exts = py,png,jpg,kv,atlas version=0.1 requirements=python3,kivy,requests,bs4 #I used requests and bs4 libraries for webscraping purposes, I'm not completely sure that I do not need any other requirements for internet connection. orientation=all osx.python_version=3 osx.kivy_version=2.0.0 fullscreen=0 android.arch=arm64-v8a android.allow_backup=True #then some ios speceific settings which I think are not important as my device is android. [buildozer] log_level=2 warn_on_root = 1 I created the apk file, installed it on my android device, but when I click on it, it just does not launch. I dont really understand why, I was thinking that I didn't pass requirements that enable the app to use internet connection, or that it does not launch because of my phone settings. How can I solve this issue? Any help is appreciated a lot. UPDATE I actually tried to install another python/kivy program on android phone not involved with web scraping, and it worked. So I guess I put wrong wrong requirements in the buildozer.spec. But I wonder if there are some requirements that MUST be included besides the module names that are used to build the app. Any help? UPDATE ON UPDATE I found this line in the buildozer.spec file: #android.permissions = INTERNET and I put that line out of comment. But still that did not help any way. After installing the app on my phone, it just won't launch. Now I have no idea what I can do to solve this issue. Any ideas or advices?
Q: $.emit is not a function on ng-select change/ngModelChange event I'm having an issue understanding what is happening in my code (Angular 13). When I use the (change) or the (ngModelChange) of the ng-select component to call the function selectPlan(), I get this error : ERROR TypeError: this.planSelected.emit is not a function. Also, whatever value I put in the emit function, it does not work so I don't think the issue is coming from the value I emit. When I call selectPlan() in every other way possible, the EventEmitter is emitting correctly (with (click) for example) and I'm receiving the Plan in the parent component. I'm using Output() and EventEmitter everywhere on my project, and it's the first time something like this happens. Here is my component.html : <div class="dropdown-with-add-button"> <ng-select class="custom-ng-select" notFoundText="{{ 'labelNoResultAfterResearch' | translate }}" id="dropdown-list-groups" [clearable]="false" [(ngModel)]="planSelected" (change)="selectPlan()" > <ng-container *ngIf="plansSidebar"> <ng-option *ngFor="let plan of plansSidebar.plans"> <div class="plan-container"> <div class="image-container"> <img class="plan-item-image" src="{{ plan.imageChaine }}" /> </div> <div class="text-container"> <p class="plan-item-libelle">{{ plan.libelle }}</p> </div> </div> </ng-option> </ng-container> </ng-select> </div> And here is my component.ts : export class PlanChildComponent implements OnInit { _plansSidebar: PlansSidebar; get plansSidebar(): PlansSidebar { return this._plansSidebar; } @Input() set plansSidebar(value: PlansSidebar) { if (value) { this._plansSidebar = value; this._plansSidebar.plans.sort( (x, y) => x.ordreAffichage - y.ordreAffichage ); if (this._plansSidebar.plans.length > 0) { this.selectedPlan = this._plansSidebar.plans[0]; } } } @Input() idSelectedPlan: number; @Input() loading: boolean; @Output() planSelected: EventEmitter<PlanWithImage> = new EventEmitter<PlanWithImage>(); selectedPlan: PlanWithImage; constructor() {} ngOnInit(): void {} public selectPlan() { this.planSelected.emit(this.selectedPlan); } } If anyone has an idea of what's happening, thank you for letting me know !
Q: convert a dict into a (const) tuple of tuples I want to convert a dict to a tuple of tuples from typing import Dict, Tuple class Data: def __init__(self, d: Dict[int, str]) -> None: self.data: Tuple[Tuple[int, str], ...] = () for k, v in d.items(): self.data += ((k, v),) d = Data({5: "five", 4: "four"}) print(d.data) This is somewhat similar to this question, but not identical. The reason I prefer a tuple of tuples is for const-ness. Is there a better way (or more pythonic) to achieve this? A: You could do tuple(d.items()). A: Try this: myDict = {5:"five",4:"four"} def dictToTuple(d): return tuple(d.items()) print(dictToTuple(myDict)) A: It seems that this question is probably a duplicate of this, and the fourth answer there (@Tom) states it's fastest to do tuple construction of list comprehension: self.data: Tuple[Tuple[int, str], ...] = tuple([(k, v) for k, v in d.items()])
Q: golang, read contents from file, and send as body data in HTTP request //read data from a file config.json //the contents of config.json is //{"key1":"...Z-DAaFpGT0t...","key2":"..."} client := &http.Client{} dat, err := ioutil.ReadFile("/config.json") req, err := http.NewRequest("PUT", url, bytes.NewBuffer(dat)) resp, err := client.Do(req) Then I will get error from server saying "400 Bad Request", " "invalid character 'ï' looking for beginning of value"". It seems the data is not properly decoded. While code below works client := &http.Client{} //dat, err := ioutil.ReadFile("/config.json") var dat = []byte(`{"key1":"...Z-DAaFpGT0t...","key2":"..."}`) req, err := http.NewRequest("PUT", url, bytes.NewBuffer(dat)) resp, err := client.Do(req) A: please check content-type your server required, and build the body as content-type required. as your content-type is application/json; charset=utf-8, you try to set it manully req.Header.Set("Content-Type", "application/json; charset=utf-8") if it still not work, make a http load capture please.
Q: Differentiate Amazon Linux 2 and Amazon Linux AMI 2018.03.0 in Ansible Script In ansible script, I want to differentiate between Amazon Linux 2 and Amazon Linux AMI 2018.03.0 using conditions. Like we use ansible_os_family condition, is there any condition function in ansible that I can use to differentiate these two. My Objective is to run different commands(using ansible script) based on the difference of os (especially between Amazon Linux 2 and Amazon Linux 2018.03.0). A: The ansible_distribution_major_version fact is set to "2" and "2018" respectively for Amazon Linux 2 vs 2018.03.0 so you can use that for your conditionals like the following: when: ansible_distribution_major_version == "2018" A: you can use following ansible fact for this, {{ hostvars[inventory_hostname].ansible_distribution }} And for running different tasks based on condition, do like this - name: <Task name goes here> import_tasks: yourtask.yml when: hostvars[inventory_hostname].ansible_distribution | lower == 'amazon linux 2'
Q: jQuery find link that matches current page I have the following code that is trying to find a link that matches the current url: $item = $('ul#ui-ajax-tabs li a').attr('href', $(location).attr('pathname')); but instead it changes all the links to the current url :P Can anyone help me fix it. Cheers A: Use this query. Your code changes all href attributes of the selected links, rather than returning a selection of links with a matching href attribute: $("a[href*='" + location.pathname + "']") The [href*=..] selector returns a list of elements whose href attribute contains the current pathname. Another method, return all elements whose href contains the current pathname. prop() is used instead of attr(), so that relative URLs are also correctly interpreted. $item = $('ul#ui-ajax-tabs li a').filter(function(){ return $(this).prop('href').indexOf(location.pathname) != -1; }); A: Where URL format might change in Production like ASP.NET :/ this might work better if you ignore the end slash of URLs. $('.mdl-navigation').find("a").filter(function () { return this.href.replace(/\/+$/, '') === window.location.href.replace(/\/+$/, ''); }).addClass('current-active-page-url'); A: That's because your CSS selector ul#ui-ajax-tabs li a matches more than one thing. Try being more specific with your selector, such as ul#ui-ajax-tabs li:first-child a.
Q: search for non-whitespace-correct strings in PHP I'm have a project where I need to find occurrences of a string in a large body of text. The search string is known to be present in the larger text, however for reasons beyond my control they are not white-space correct, in that they are missing spaces between some of the words. For example I the string to find is (not the lack of space between brown and fox: quick brownfox jumps And I need to find this in: The quick brown fox jumps over the lazy dog. I need to be able to modify the haystack to wrap the found terms with an identifying tag so I'll end up with something like: The <span class="found">quick brown fox jumps</span> over the lazy dog. I've looked into using regex in free-spacing mode which seems to not quite do what I need, I considered stripping all white space from the search terms and adding \s* between each character but thought this might have a horrendous effect on performance (can any regex experts could confirm or deny that?). Are there any possible non-regex solutions to look into. Thanks A: The best way in this case would be to remove all the whitespaces in the search string, and the target string. And then check if the string is present or not: $haystack = 'The quick brown fox jumps over the lazy dog.'; $needle = 'quick brownfox jumps'; $haystack = preg_replace("\s+", "", $haystack); $needle = preg_replace("\s+", "", $needle); if (strpos($haystack, $needle) !== false) { echo 'true'; } A: You can't just strip the whitespace from the haystack like others are saying. Your search string, even though its whitespace is unreliable, is still a series of discrete words. If we assume that the whitespace is correct in your haystack, that means your string to find will be be surrounded by non-word characters in the haystack. By stripping it of whitespace, you are losing the ability to check for that and you'll get unnecessary false positives. Something like \Ws\W*t\W*r\W*i\W*n\W*g\W would work, but it isn't very clean. If you want to implement a solution without using regular expressions, you could iterate over every word in the haystack and compare it to the first n characters of your search string, then try to match proceeding words with the rest of the search string. Once you get to a character that doesn't match, you skip the rest of the word and start checking the next one. It only returns a complete match if your search string's last character matches with the end of a word in your haystack.
Q: How to use Google Code I use openlike (openlike.org) but the site seems to be temporarily down. I would normally use something like this: <script type="text/javascript" src="http://openlike.org/v1/openlike.js"></script> <script type="text/javascript">OPENLIKE.Widget()</script> But that isn't working. I've found the project on google code, I was wondering how I implement exactly the same thing, but from Google? Is Google code completely different from the google cdn? I.e. I can't just change the URL of that javascript file? Google code project: http://code.google.com/p/openlike/source/browse/#svn%2Ftrunk%2Fv1%253Fstate%253Dclosed Thanks for any help, Dave A: From the link posted, if you click on "openlike.js" and then "View raw file" you'll get exactly that: http://openlike.googlecode.com/svn/trunk/v1/openlike.js You can certainly link to this file. Here's what I tried and it worked fine: <script type="text/javascript" src="http://openlike.googlecode.com/svn/trunk/v1/openlike.js" ></script> <script type="text/javascript" > console.log(OPENLIKE); </script> I don't know enough about google code and svn to tell you if that file will be there forever and won't change. I doubt that it's intended to be used a CDN. But it's probably good enough to use while openlike.org is down temporarily.
Q: HTML/CSS: Probleme with full width I've created this test-page: http://uploads.dennismadsen.com/width.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="da-DK"> <head> <title></title> </head> <body style="background-color:#e0e0e0;"> <div style="width:1500px;background-color:#ff0000;">Container width a width of 1500px</div> <div style="width:100%;background-color:#000;height:100px;"></div> </body> </html> The red div is 1500px and the black to 100%. When the browser window is smaller than 1500px, for instance 1000px, the black box will only be as width as the window. I would like it to fill as much as the above content. Please note that the red box has a dynamic width. Therefore I cannot set a min-width=1500px etc. on the black box. A: All you have to do is wrap the black div with the red one: <body style="background-color:#e0e0e0;"> <div style="width:1500px;background-color:#ff0000;"> Container width a width of 1500px<!--this is where you closed your div--> <div style="width:100%;background-color:#000;height:100px;"> </div> </div><!--this is where you should close it to make it work--> </body> A: Put them both in another div. Then that div will be pushed to the width of whatever is in it (the red div) and something with a width of 100% will match it A: To achieve such a thing, you need an absolute container. A markup that will work is for example <div style="position:absolute"> <div style="width:1500px;background-color:#ff0000;">Container width a width of 1500px</div> <div style="width:100%;background-color:#000;height:100px;"></div> </div> EDIT: you can also put the absolute on the body if needed.
Q: Delphi 10.1 Berlin Firemonkey TComboBox StyledSettings, Excluding the styles I want to exclude one TComboBox from styles. This one is a part of component and have another visual suit (manually painted with OnPaint event), but the main style of form has an influence on this TComboBox. Especially one parameter: FixedHeight - it causes that my TComboBox can't change the height... How to do it? The TComboBox has no StyledSettings property... A: The way that I found was to use another style... If there are some combobox-es with a fixed height, then I should create a copy of their style, but with fixed height equal zero.
Q: create table in hive I am trying to create hive table with this syntax : create table table_name as orc as select * from table1 partitioned by (Acc_date date). I am getting error. My requirement is to create table using select statement and append the table when the next load happens. I am trying to replicate this spark command: df1.distinct().repartition("acc_date").write.mode("append").partitionBy("acc_date").format("parquet").saveAsTable("schema.table_name") A: Make it a two step process. * *Create the partition table as you want. *Insert data into it. Details 1.sql may be like this - create table if not exists table_name (Col1 int, col2...) partition (acc_date date) Stored as orc ; *Insert will be like below. Make sure partition column is the last column in select clause. set hive.exec.dynamic.partition=true; set hive.exec.dynamic.partition.mode=nonstrict; Insert into table_name partition (Acc_date ) Select col1,col2... acc_date from table1 ;
Q: difference in CPU time for two similar lines There is a while loop in my program, where IterZNext, IterZ are pointers to nodes in a list. The nodes in the list are of type struct with a field called "Index". double xx = 20.0; double yy = 10000.0; double zz; while (IterZNext!=NULL && NextIndex<=NewIndex) { IterZ=IterZNext; IterZNext = IterZ->Next; if (IterZNext!=NULL) { zz = xx + yy; NextIndex1 = IterZNext->Index; // line (*) NextIndex = IterZNext->Index; // line (**) IterZNext->Index; } } When I profiled my program, I found the line (*) NextIndex1 = IterZNext->Index; consumes most of CPU time (2.193s), while the line (**) NextIndex = IterZNext->Index; which is all most the same with the line (*) only uses 0.093s. I used the Intel VTune Amplifier to see the assembly of these two lines, which is as follows: Address Line Assembly CPU Time Instructions Retired Line (*): 0x1666 561 mov eax, dword ptr [ebp-0x44] 0.015s 50,000,000 0x1669 561 mov ecx, dword ptr [eax+0x8] 0x166c 561 mov dword ptr [ebp-0x68], ecx 2.178s 1,614,000,000 Line (**): 0x166f 562 mov byte ptr [ebp-0x155], 0x1 0.039s 80,000,000 0x1676 562 mov eax, dword ptr [ebp-0x44] 0.027s 44,000,000 0x1679 562 mov ecx, dword ptr [eax+0x8] 0x167c 562 mov dword ptr [ebp-0x5c], ecx 0.026s 94,000,000 If I change the order of the line () and the line (*), then the program changes to double xx = 20.0; double yy = 10000.0; double zz; while (IterZNext!=NULL && NextIndex<=NewIndex) { IterZ=IterZNext; IterZNext = IterZ->Next; if (IterZNext!=NULL) { zz = xx + yy; NextIndex = IterZNext->Index; // line (**) NextIndex1 = IterZNext->Index; // line (*) IterZNext->Index; } } and the result for assembly changes to Address Line Assembly CPU Time Instructions Retired Line (**): 0x1666 560 mov byte ptr [ebp-0x155], 0x1 0.044s 84,000,000 0x166d 560 mov eax, dword ptr [ebp-0x44] 0.006s 2,000,000 0x1670 560 mov ecx, dword ptr [eax+0x8] 0.001s 4,000,000 0x1673 560 mov dword ptr [ebp-0x5c], ecx 1.193s 1,536,000,000 Line (*): 0x1676 561 mov eax, dword ptr [ebp-0x44] 0.052s 128,000,000 0x1679 561 mov ecx, dword ptr [eax+0x8] 0x167c 561 mov dword ptr [ebp-0x68], ecx 0.034s 112,000,000 In this case, line (*) uses most of CPU time (1.245s) while line () only uses 0.086s. Could someone tell me: (1) Why does it take so long to make the first assignment? Notice that the line zz=xx+yy only uses 0.058s. Is this related to the cache misses? since all nodes in the list are dynamically genereated. (2) Why is there huge difference in CPU time between this two lines? Thanks! A: All modern CPUs are superscaler & out-of-order - which means that instructions are not actually executed in the order of the assembly, and there isn't really such thing as the current PC - there are many 10s of instructions in flight and executing at once. Therefore any sampling information a CPU reports is just a rough area the CPU was executing - it was executing the instruction it indicated when the sampling interrupt went off; but it was also executing all the other in-flight ones! However people have got used to (and expect) profiling tools to tell them exactly which individual instruction the CPU is currently running - so when the sampling interrupt triggers the CPU essentially picks one of the many active instructions to be the 'current' one. A: CPU line caching is probably the reason. accessing [ebp-0x5c] also brings into the cache [ebp-0x68], which then will be fetched much faster (for the second case, vice versa for the first). A: It is definitly due to the cache miss. Then bigger miss then more performance penalty will be introduced by processor. Actually in the modern world CPU performs much faster then memory. If nowadays processor can have clock frequency in about 4GHz, memory still run with frequency ~0.3GHz. It is great performance gap that is still continue to grow. Cache introduction was driven by desire to hide this gap. Without cache using modern processor will spend huge amount of time waiting data from the memory and doing nothing at that time. In addition to the performance gap, each memory access incurrs additional latencies related to posible concurrency on memory bus with other CPUs and DMA devices and times required for memory access request processing and routing on the side of the processor memory management logic (checking of the caches of all levels, virtual-to-physical address translation that can involve TLB miss with additional access to memory, request pushing to the memory bus etc.)and memory controller(request routing from the CPU-controller to the controller memory bus, possible waiting for memory bank refresh cycle complition etc.). So, to summarize, raw access to the memory have really big cost in comparision to the L1 cache hit or register access. The difference in cost comparable to the difference in cost to access data in memory and in secondary storage (HDD). Furthermore, the cost of memory access will grow with moving from the processor to the memory. L2 access will provide bigger penalty then L1 or CPU registers access, L3 access will provide penalty bigger then L2 access and, finally, memory access will provide penalty bigger then memory access. For example, you can compare cost of data access on different levels of memory hierarchy in the next table (captured from http://www.anandtech.com/show/4955/the-bulldozer-review-amd-fx8150-tested/6) Cache/Memory Latency Comparison ----------------------------------------------------------- | |L1| L2| L3| Main Memory | ----------------------------------------------------------- |AMD FX-8150 (3.6GHz) | 4| 21| 65| 195 | ----------------------------------------------------------- |AMD Phenom II X4 975 BE (3.6GHz)| 3| 15| 59| 182 | ----------------------------------------------------------- |AMD Phenom II X6 1100T (3.3GHz) | 3| 14| 55| 157 | ----------------------------------------------------------- |Intel Core i5 2500K (3.3GHz) | 4| 11| 25| 148 | ----------------------------------------------------------- In regard to your particular case: 0x1669 561 mov ecx, dword ptr [eax+0x8] 0x166c 561 mov dword ptr [ebp-0x68], ecx 2.178s 1,614,000,000 0x1670 560 mov ecx, dword ptr [eax+0x8] 0.001s 4,000,000 /* confusing and looks like wrong report for me*/ 0x1673 560 mov dword ptr [ebp-0x5c], ecx 1.193s 1,536,000,000 You have penalty on dereferencing of the Index value in the code line. mov ecx, dword ptr [eax+0x8] Note that it is first access to the data in each subsequent node of you list, up to this moment you manipulate only by node address, but the data of that address and due to this haven't memory access. You stated, that you use dynamical list, and this is bad from cache hit rate point of vies. In addition, I suppose that you have big enough list that mean that you will have cache fluded by the previously accessed data (list nodes accessed on previous iterations)and almost always will have cache miss or cache hit only on L3 cache during the accessing Index on each new iteration. But note, that during first access to the Index on each involving cache miss on each new iteration data returned from the memory will be stored in the L1 cache. And when you access Index on the second time during the same cycle iteration, you will have low cost L1 cache hit! So I hope I provide you detailed answer on both your questions. In regard to the correctness of the VTune report correctness. I want to advocate Intel VTune developers. Of course, modern processors are very complex devices with number of ILP improving technologies on the board including pipelining, superscalaring, Out-Of-Order execution, branch prediction etc, and of cource this make detailed instruction level performance analysis harder and more precious. But such tools like VTune is developed with that processor features in the mind, and I belive that they are not so stupied to develop and provide the tool or feature that haven't any sence. Furthermore it looks like the developers from the Intel like no another have access to the full understanding of the all processor features details and as no another can take this details into account during profiler designing and development.
Q: Tkinter tkFileDialog doesn't exist I'm trying to show a open file dialog using Tkinter in Python. Every example I find seems very easy to use, but they all start with the line: import tkFileDialog This line throws an error for me, saying No module named 'tkFileDialog' It seems my Python doesn't have tkFileDialog. So I tried searching for it, but it seems that you don't "download" Tkinter, it just comes with Python. Why is my Tkinter missing tkFileDialog? Is there somewhere I can acquire it so that I can use it? Another thing I thought is that maybe it has changed names since the examples I've read were written. Is there a different way to import tkFileDialog in Python 3? I'm running Windows 7 64-bit, Python version 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] Any help would be greatly appreciated! A: That code would have worked fine in Python 2.x, but it is no longer valid. In Python 3.x, tkFileDialog was renamed to filedialog and placed inside the Tkinter package. Nowadays, you import it like so: import tkinter.filedialog # or from tkinter import filedialog
Q: React/date-fns - error in component 'Objects are not valid as a React child' when using 'addSuffix' I've created a component that uses date-fns and the formatDistanceToNow method. It works fine but when I want use the addSuffix option, React throws the following error: Unhandled Runtime Error Error: Objects are not valid as a React child (found: object with keys {addSuffix}). If you meant to render a collection of children, use an array instead. import * as React from 'react' import { format, parseISO, formatDistanceToNow } from 'date-fns'; function DateDistance({ text, dateString }) { const date = parseISO(dateString); return ( <> <div className="text-xs font-medium text-gray-700"> <span>{text}</span> <time> {(formatDistanceToNow(date), { addSuffix: true })} </time> </div> </> ); } function BlogPost({ post }) { return ( <> <h2>Hello World!</h2> <p>This will be the subheader and below will be the published and updated date values.</p> <DateDistance text="and was updated " dateString={post.updated_at} /> </> ) } A: formatDistanceToNow(date, [options]) <time>{formatDistanceToNow(date, { addSuffix: true })}</time>
Q: onCreate is not called after switching back from preferences My app only has two activities: main and preferences In the PreferenceActivity (or in my case SettingsActivity), the user can change some stuff, that affects the MainActivity. This is my SettingsActivity: public class SettingsActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } public static class SettingsFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener { @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } @Override public boolean onPreferenceChange(Preference preference, Object value) { return false; } } } Now I have two issue: * *When the user presses the HomeButton the main screen does not seem to call the onCreate so the changed preferences are not loaded in the main activity. What do I need to change, to tell android to call the onCreate function? *Since android nougat there are these "activity-change-animations", so when switching to a new activity, the new screen kind of slides in. But when the user presses the HomeButton the expected animation would be slide out, but it is also slide in. How can I fix that? A: Explanation for the first issue: There's a difference between onCreate and onResume onCreate: Activity launched for the first time. Here is where you may initialize your stuff. onResume: User returns to the activity after another activity goes to the background. (onPause is called on the other activity) For the second issue, try this: Intent intent = NavUtils.getParentActivityIntent(this); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); NavUtils.navigateUpTo(this, intent); Instead of NavUtils.navigateUpFromSameTask(this);
Q: How do I restrict a Django model to just one of several possible relationships? Given these models, how do I prevent a FinancialTransaction from being assigned to more than one Thing? In other words, if ThingOne has a FinancialTransaction, ThingTwo or ThingThree cannot have a relationship to it. How do I enforce this in the admin? I can of course get Thing* in the SomeThing admin with Inlines, but that allows me to set more than one Thing*. My first inclination is that my modeling is wrong and that all Things should be represented by one model, but they're definitely different types of Things. from django.db import models class ThingOne(models.Model): name = models.CharField(max_length=20) some_things = models.ForeignKey('FinancialTransaction', blank = True, null = True) class ThingTwo(models.Model): name = models.CharField(max_length=20) some_things = models.ForeignKey('FinancialTransaction', blank = True, null = True) thingone = models.ForeignKey(ThingOne) class ThingThree(models.Model): name = models.CharField(max_length=20) some_things = models.ForeignKey('FinancialTransaction', blank = True, null = True) thingtwo = models.ForeignKey(ThingTwo) class FinancialTransaction(models.Model): value = models.IntegerField() A: You could have the relationship on the FinancialTransaction using a Generic foreign key. https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1 from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class FinatialTransation(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') Then the relationship exists in one place and there can only be 1. Then from the FinancialTransaction you check the object ID and the objects ContentType and look it up accordingly. ft = FinancialTransaction.objects.get(...) thing = ft.content_type.get_object_for_this_type(id=ft.object_id) Additionally you can then limit the GenericForeignKey to certain content types with: class FinatialTransation(models.Model): limit = models.Q( models.Q(app_label='yourappsname', model='ThingOne') | models.Q(app_label='yourappsname', model='ThingTwo') | models.Q(app_label='yourappsname', model='ThingThree') ) content_type = models.ForeignKey(ContentType, limit_choices_to=limit) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id')
Q: Why are all my Angular modules failing to load? I'm getting some variation of the following, for every single Angular module (animate, resource, route, touch etc): Module 'ngResource' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. I'm relatively new to Angular. I read the docs on the error but I'm not sure how to apply them. Thoughts? Here is the code where I declare the modules: angular .module('juddfeudApp', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch' ]) .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html' }) .when('/about', { templateUrl: 'views/about.html' }) .when('/admin', { templateUrl: 'views/admin.html', controller: 'AdminCtrl' }) .otherwise({ redirectTo: '/' }); }); HTML: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body ng-app="juddfeudApp"> <!-- all angular resources are concatenated by Gulp in lib.js--> <script src="build/lib/lib.js" type="text/javascript"></script> <script src="build/main.js" type="text/javascript"></script> </body> </html> A: You need to reference them in your html file. So add <script src="filename.js"></script> for each module/file you want to load. A: did you add this <script src="angular-resource.js"> ? A: When you get an error like this, it's likely that you aren't successfully loading the Angular module scripts in your HTML file. Some answers here suggest making sure you've referenced the scripts somewhere in your HTML file. That is, if you're trying to add multiple Angular modules, you should have several scripts being loaded before your own JS, like this: <script src="../bower_components/angular/angular.js"></script> <script src="../bower_components/angular-resource/angular-resource.js"></script> <script src="../bower_components/angular-cookies/angular-cookies.js"></script> <script src="../bower_components/angular-sanitize/angular-sanitize.js"></script> <script src="../bower_components/angular-animate/angular-animate.js"></script> <script src="../bower_components/angular-touch/angular-touch.js"></script> <script src="../bower_components/angular-route/angular-route.js"></script> <script src="myMainJsFile.js"></script> That may fix the problem. You might also consider checking to make sure your scripts actually exist in the place you are referencing them -- for me, bower had not properly installed them all on the first time around, so they weren't being picked up by gulp-concat -- or ensuring that your task-runner of choice (Gulp/Grunt) is configured properly.
Q: How to get the values from list of objects in c# I have Called a Json Web Service and got the result in c#.The Json Web service data is available in format: { "Count": 9862, "Items": [ { "Admin": { "S": "false" }, "UserId": { "S": "e9633477-978e-4956-ab34-cc4b8bbe4adf" }, "Age": { "N": "76.24807963806055" }, "Promoted": { "S": "true" }, "UserName": { "S": "e9633477" }, "Registered": { "S": "true" } }, { "Admin": { "S": "false" }, "UserId": { "S": "acf3eff7-36d6-4c3f-81dd-76f3a8071bcf" }, "Age": { "N": "64.79224276370684" }, "Promoted": { "S": "true" }, "UserName": { "S": "acf3eff7" }, "Registered": { "S": "true" } }, I have got the Response like this in c#: HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8000/userdetails"); try { WebResponse response = request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); return reader.ReadToEnd(); } } after finally successfully get the response i have got all the Data in string. and then parse this string in list of objects .Now I have list of objects where it showing the count in debugging.Now I want to access the values like UserId:acf3eff7-36d6-4c3f-81dd-76f3a8071bcf like properties.I dont know how to do it.Please help me and any help will be appreciated. A: You can use the following code to get the values from json as: JObject obj = JObject.Parse(json); int count = (int)obj["Count"]; var Items = obj["Items"]; foreach (var item in Items) var admin = item["Admin"]; A: Quick and dirty way: //deserialize your string json using json.net dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json); //get value of UserId in first Item var UserId = jsonObj["Items"][0]["UserId"]["S"]; //OR get the value of UserId for each Item in Items //foreach(dynamic item in jsonObj["Items"]) //item["UserId"]["S"]; Advice is to use c# objects as mentioned by @yousuf A: To be able to access Json property like common C# object property, you need to deserialize json string to strongly typed object (you can use, for example, JSON.NET to do deserialization). Another handy tool is http://json2csharp.com/. Paste your Json there then you can generate classes definitions that suitable to map the Json automatically : //RootObject class definition generated using json2csharp.com //the rest of class definition removed for brevity. public class RootObject { public int Count { get; set; } public List<Item> Items { get; set; } } ........ ........ //in main method var jsonString = .....; //deserialize json to strongly-typed object RootObject result = JsonConvert.DeserializeObject<RootObject>(jsonString); foreach(var item in result.Items) { //then you can access Json property like common object property Console.WriteLine(item.UserId.S); } A: you are deserializing string to c# object. you will need to create object that reperesents the json . For example - public class Admin { public string S { get; set; } } public class UserId { public string S { get; set; } } public class Age { public string N { get; set; } } public class Promoted { public string S { get; set; } } public class UserName { public string S { get; set; } } public class Registered { public string S { get; set; } } public class RootObject { public Admin Admin { get; set; } public UserId UserId { get; set; } public Age Age { get; set; } public Promoted Promoted { get; set; } public UserName UserName { get; set; } public Registered Registered { get; set; } } Then deserialize json string to object using jsonSerializer JavaScriptSerializer serializer = new JavaScriptSerializer(); var result = (RootObject)serializer .DeserializeObject("Json String") A: string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }"; JObject o = JObject.Parse(json); //This will be "Apple" string name = (string)o["Name"];
Q: Redux-Persist Secure Encryption i am trying to learn how to securely save my redux state in my react-native app. i am using redux-persist-transform-encrypt as per the documentation: https://github.com/maxdeviant/redux-persist-transform-encrypt import { persistReducer } from 'redux-persist' import createEncryptor from 'redux-persist-transform-encrypt' const encryptor = createEncryptor({ secretKey: 'my-super-secret-key' }) const reducer = persistReducer( { transforms: [encryptor] }, baseReducer ) but i dont not how to securely set the secretKey string 'my-super-secret-key'? when the js is compiled, wouldn't the value of the string be visible in the bundle? A: Yes, the keys would be visible in the JS bundle.To overcome this problem you need to either set nested persisted states, in the redux-persist and store the keys to a secured-db or keystore in some way or use this package as mentioned here. const mainPersistConfig = { key: "main", storage: AsyncStorage, blacklist: ["yourKeyReducer"] }; const tokenPersistConfig = { key: "token", storage: sensitiveStorage }; Since it provides with creation of the sensitive storage, the security issue is overcome.
Q: How to pivot a dataframe in Pandas? I have a table in csv format that looks like this. I would like to transpose the table so that the values in the indicator name column are the new columns, Indicator Country Year Value 1 Angola 2005 6 2 Angola 2005 13 3 Angola 2005 10 4 Angola 2005 11 5 Angola 2005 5 1 Angola 2006 3 2 Angola 2006 2 3 Angola 2006 7 4 Angola 2006 3 5 Angola 2006 6 I would like the end result to like like this: Country Year 1 2 3 4 5 Angola 2005 6 13 10 11 5 Angola 2006 3 2 7 3 6 I have tried using a pandas data frame with not much success. print(df.pivot(columns = 'Country', 'Year', 'Indicator', values = 'Value')) Any thoughts on how to accomplish this? A: You can use pivot_table: pd.pivot_table(df, values = 'Value', index=['Country','Year'], columns = 'Indicator').reset_index() this outputs: Indicator Country Year 1 2 3 4 5 0 Angola 2005 6 13 10 11 5 1 Angola 2006 3 2 7 3 6 A: This is a guess: it's not a ".csv" file, but a Pandas DataFrame imported from a '.csv'. To pivot this table you want three arguments in your Pandas "pivot". e.g., if df is your dataframe: table = df.pivot(index='Country',columns='Year',values='Value') print (table) This should should give the desired output.
Q: Como saber a rota antes de redirecionar no Angular 4 Tenho o seguinte trecho de código que redireciona para uma página 404 caso o path não esteja definido dentro da aplicação. { path: '**', redirectTo: 'paginas/pagina404' } Mas gostaria de mostrar na página 404 o caminho que tentaram acessar, tem alguma forma de fazer isso? Desde já agradeço! A: Sugiro criar um evento para escutar a alteração de rotas em seu componente principal relativo ao <router-outlet> e publicar as modificações em um serviço capturando-as na sua página de 404. Exemplo de como escutar: urlAtual: string = ''; urlAnterior: string = ''; ngOnInit() { this.router.events.subscribe((e: any) => { if (e instanceof NavigationEnd) { this.urlAnterior = this.urlAtual; this.urlAtual = e.url; } }); } Após capturar as modificações você publica em seu serviço/gerenciamento de estado.
Q: Not able to submit form using ajax, php and jquery I am trying to submit a form using ajax. In the backend part, i am trying to print the values of "fname", "location" and "image" in order to check if the data is reaching there or not But when I am trying to do console.log to check for response, I get the following message for dataString filename=girl.jpgfname=johnlocation=Richmond, Virginia for fname Severity: Notice Message: Undefined index: fname for image No response I am not able to fetch the data at the backend, can anyone please help me with this Form <form class="form-inline" id="form_add" enctype="multipart/form-data"> <input type="file" id="file-input" name="file-input" accept="image/*" > <input type="text" class="form-control name" id="fname" placeholder="First Name" > <select class="location" id="location" > <option value="">Location</option> <?php foreach($location as $loc): ?> <option value="<?php echo $loc->city.', '.$loc->state;?>" ><?php echo $loc->city.', '.$loc->state;?></option> <?php endforeach; ?> </select> <button type="submit" class="save_btn" id="submit" > <img src="save.png" class="Save"> </button> </form> Script <script> $("#submit").click(function() { event.preventDefault(); var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, ''); var fname = $("#fname").val(); var location = $("#location").val(); var dataString = 'filename='+ filename + 'fname='+ fname + 'location='+ location; if(filename != "" || fname != "" || location != "") { $.ajax({ type: "POST", url: "Data/add_data", data: dataString, cache: false, success: function(result){ console.log(result); console.log(dataString); }}); } }); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> On backend $config['upload_path'] = './assets/client_img/.'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = 1024 * 8; $config['encrypt_name'] = TRUE; $this->load->library('upload', $config); $data = $this->upload->data(); echo $img_name = $data['file-input']; echo $_POST['fname']; The selected values in the form was: name of the file = girl.jpg first name(fname) = John value i had select from location dropdown = Richmond, Virginia A: { $.ajax({ type: "POST", url: "Data/add_data", data: { filename : filename, fname:fname, location:location }, cache: false, success: function(result){ console.log(result); console.log(dataString); }}); } for image only keep this var filename = $('input[type=file]').val() as codeignitor will show only the name in controller, no need to replace or ci wont be able to figure the path A: the problem lies in your dataString you can do this: var dataString='filename=' + filename + '|fname=' + fname + '|location=' + location; so when you receive dataString in the backend (php) , you can split the dataString using: $dataString=explode('|', $dataReceived); so you can get each part by doing this: $filename=$dataString[0]; $fname=$dataString[1]; $location=$dataString[2]; hope it helps A: Your dataString must be a JavaScript Object. var data = {filename: filename, fname: fname, location: location};
Q: Need a Relay For to reverse a thermostat This should be a simple question for someone who knows what he's doing. Unfortunately, I don't, so I've been researching like crazy and am stuck on where to go from here. I am trying to modify a mini fridgerator for as cheap as possible to allow me to control the temperature from 55 to 90 degrees. I stumbled across several simple bimetal thermostat switches that have a pretty good range in them, but they are heating thermostats. I need to reverse these to cooling so that the fridge will activate at a certain warm temperature and turn off once it reaches set cooling. Thus, when the thermostat is open, I need the fridge running. When the thermostat is closed, I need to fridge to stop running. I think I've narrowed it down to either a SPST NC relay or a SPDT relay, but I'm stumbling heavily on the exact values I'm looking for. The normal fridge would accept 110 volt AC from the wall and output 110 volt AC into the unit. Normal operating amperage of these I beliefe is 3 - 5 amps, and most suggest the start up should provide 1.5 times that ammount. So my first question is, I guess I am looking for a 110v AC relay that can handle 5 - 7 AMPs? If I'm on the right track, then my next concern is cost. I can find these in expensive electronics catalogs. I've looked on ebay, and they have some fairly simple and cost effective relays, but they are made for China outputting 240V capacity. Does this affect me, or because it's more than the 110 I should be ok? Does anyone have better suggestions? Again, only looking to reverse this thermostat from heating to cooling. Shouldn't be this complicated! :) A: Some thoughts: * *Yes, your calculations for relay power are correct: you probably want some head room for the compressor startup. 2x the power rating is probably even better. *Whether 240V is OK depends on the relay. Some types of solid state relays (SSRs) require a particular type of AC. Most likely, however, the relays you are looking at are 240V maximum, in which case it is fine. I would ask the Ebay seller for specifics, when in doublt (choosing for the "Capt'n Obvios" badge here). If the relays are mechanical then it is definitely fine: those would be the maximum ratings. Coupld of more points: * *If this is for temperature control, you want to think about your relay lifetime, if you are using a mechanical relay. If, for example, it is rated for 10,000 cycles, and you turn it on and off once a minute, the relay will last for only six days. So you'd want to figure out how often the relay cycles: but this is going to be partly dependent on the hysterisis of your thermostat. Note that solid state relays are much more longer lasting than mechanical relays because there are no moving parts. *On the other hand, the cheap Chinese Ebay SSR have been claimed to be of inferior quality. If you search the internets you will find claims where such relays have self-destructed: this is, of course, a fire hazard, so you want to be careful with those. Anindo Ghosh recommends Omron SSRs from Ebay, something like this or this. Note that the output on these is 24-240VAC, so 110/120VAC is going to be perfectly fine. Anindo Ghosh says that he had units like this tested by Omron and they said they were genuine. And if you buy it and your house burns down, you can come and live with him :)
Q: LINQ to entities slow query I have a huge problem with Sql Server query execution time which I've debugged for a long time with no success. Basically I'm generating a report where 'Order' statistics are grouped by order and shown to the user. The problem is, that most of the time the query execution is reasonably fast, but occasionally it plummets and causes timeouts on the server. What I've gotten myself from it is that the occasional poor query performance seems to be caused by parameter sniffing in the SQL Server. My relations have very mixed amount of related rows; some relation might have 10 000 rows for one parent row but the next row could have only 1 related row. I think this causes the Query optimizer in some cases to ignore indexes completely and cause really poor performance. Basically I have no idea how to approach with a fix to this problem. I either have to optimize my query below somehow OR come up with some way to force the query optimizer to use indexes every time. Stored procedures are not an option in this project, unfortunately. What I've tried is to create independent requests for every 'Order', but as theres over 1000 orders in the system, that causes massive slowness and really isn't an option. The closest I've gotten to get it to run within a reasonable execution time is the query below which in turn seems to suffer from the parameter sniffing problem. result = (from ord in db.Orders join comm in db.Comments.Where(i => i.UserId == userId && i.Created >= startDate && i.Created < endDate && i.UserGroupId == channelId && i.Campaign.CampaignCountryId == countryId && (i.CommentStatus.Name == CommentStatus.Approved || i.CommentStatus.Name == CommentStatus.Pending)) on ord.OrderId equals comm.OrderId into Comments join motif in db.Motifs.Where(i => i.UserId == userId && i.Created > startDate && i.Created < endDate && i.UserGroupId == channelId && i.Campaign.CampaignCountryId == countryId) on ord.OrderId equals motif.OrderId into Motifs where ord.EndDate > startDate select new ReportRow() { OrderName = ord.Name, OrderId = ord.OrderId, ChannelId = channelId, Comments = Comments.Count(c => c.CommentStatus.Name == CommentStatus.Approved), PendingComments = Comments.Count(c => c.CommentStatu.Name == CommentStatus.Pending), Motifs = Motifs.Count(), UniqueMotifs = Motifs.GroupBy(c => c.Uin).Count(), ApprovedValue = ((decimal?)Motifs.GroupBy(c => c.Uin).Select(c => c.FirstOrDefault()).Sum(c => c.Value) ?? 0) + ((decimal?)Comments.Where(c => c.Commentstatu.Name == Commentstatus.Approved).Sum(c => c.Value) ?? 0), PendingValue = ((decimal?)Comments.Where(c => c.Commentstatu.Name == Commentstatus.Pending).Sum(c => c.Value) ?? 0) }).ToList(); return result; Any help and ideas about how to make my reporting run reasonably fast every time would be greatly appreciated - no matter if it's query optimizing itself or some awesome ideas for reporting in SQL in general. I'm using Azure SQL if that makes any difference. Also note that when I'm running the generated query from the LINQ above in SSMS I get good query execution time on every single run so the DB design shouldn't be a problem here albeit it might not be the most efficient solution anyway. A: Maybe not an answer for your, just a thought. You could create a view for your report, and then query the view to get your results. This would ensure that the query runs fine in SQL every time, from what you are saying. You use them similar to tables, and can make any queries on them. Check this post for some tips on consuming views in EF.
Q: Request to Jetty Jersey app terminated after 1 minute I have a java jetty + jersey app that has some rest endpoints that return streaming output. A request may run several minutes. When I run it locally, long-running requests work fine. When I deploy the app to a Google Compute Engine VM, the requests always fail after 30s: $ time curl -s 'https://[redacted]' -H [redacted] -iv > /dev/null * Trying [redacted]... * Connected to [redacted] port 443 (#0) * TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA * Server certificate: [redacted] * Server certificate: thawte SSL CA - G2 > GET /[redacted] HTTP/1.1 > Host: [redacted] > User-Agent: curl/7.43.0 > Accept: */* > [redacted] > < HTTP/1.1 200 OK < Content-Type: application/octet-stream < Access-Control-Allow-Origin: * < Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS < Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept,MaxDataServiceVersion,AuthorizationFlow,Authorization < Access-Control-Allow-Credentials: true < Transfer-Encoding: chunked < Server: Jetty(9.1.z-SNAPSHOT) < Via: 1.1 google < Date: Fri, 27 May 2016 13:31:05 GMT < { [932 bytes data] * SSLRead() return error -9806 * Closing connection 0 real 0m30.133s user 0m0.194s sys 0m0.188s From the server log: May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi org.eclipse.jetty.io.EofException May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.io.ChannelEndPoint.flush(ChannelEndPoint.java:189) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.io.WriteFlusher.write(WriteFlusher.java:335) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.io.AbstractEndPoint.write(AbstractEndPoint.java:125) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpConnection$ContentCallback.process(HttpConnection.java:680) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.util.IteratingCallback.processIterations(IteratingCallback.java:166) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.util.IteratingCallback.iterate(IteratingCallback.java:126) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpConnection.send(HttpConnection.java:303) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpChannel.sendResponse(HttpChannel.java:720) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpChannel.write(HttpChannel.java:751) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:130) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:124) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:328) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.servlet.internal.ResponseWriter$NonCloseableOutputStreamWrapper.write(ResponseWriter.java:325) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.CommittingOutputStream.write(CommittingOutputStream.java:229) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$UnCloseableOutputStream.write(WriterInterceptorExecutor.java:299) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:282) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at java.io.BufferedWriter.write(BufferedWriter.java:230) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at java.io.Writer.write(Writer.java:157) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at com.tie.flow.bqapi.bigquery.BigQueryTableReaderService$1.write(BigQueryTableReaderService.java:62) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.StreamingOutputProvider.writeTo(StreamingOutputProvider.java:78) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.StreamingOutputProvider.writeTo(StreamingOutputProvider.java:60) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.filter.LoggingFilter.aroundWriteTo(LoggingFilter.java:311) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:711) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:444) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:434) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:329) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.internal.Errors.process(Errors.java:315) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.internal.Errors.process(Errors.java:297) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.internal.Errors.process(Errors.java:267) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:711) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:552) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:568) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1114) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:479) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1046) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.Server.handle(Server.java:462) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:281) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:232) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.io.AbstractConnection$1.run(AbstractConnection.java:505) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:607) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:536) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at java.lang.Thread.run(Thread.java:745) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi Caused by: java.io.IOException: Broken pipe May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.ch.FileDispatcherImpl.writev0(Native Method) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.ch.SocketDispatcher.writev(SocketDispatcher.java:51) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.ch.IOUtil.write(IOUtil.java:148) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:504) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.io.ChannelEndPoint.flush(ChannelEndPoint.java:169) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011... 67 more May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi May 27, 2016 1:38:00 PM org.glassfish.jersey.server.ServerRuntime$Responder writeResponse May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi SEVERE: An I/O error has occurred while writing a response message entity to the container output stream. May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi javax.ws.rs.WebApplicationException: HTTP 500 Internal Server Error May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at com.tie.flow.bqapi.bigquery.BigQueryTableReaderService$1.write(BigQueryTableReaderService.java:68) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.StreamingOutputProvider.writeTo(StreamingOutputProvider.java:78) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.StreamingOutputProvider.writeTo(StreamingOutputProvider.java:60) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.filter.LoggingFilter.aroundWriteTo(LoggingFilter.java:311) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:711) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:444) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:434) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:329) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.internal.Errors.process(Errors.java:315) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.internal.Errors.process(Errors.java:297) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.internal.Errors.process(Errors.java:267) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:711) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:552) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:568) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1114) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:479) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1046) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.Server.handle(Server.java:462) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:281) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:232) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.io.AbstractConnection$1.run(AbstractConnection.java:505) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:607) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:536) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at java.lang.Thread.run(Thread.java:745) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi Caused by: org.eclipse.jetty.io.EofException May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.io.ChannelEndPoint.flush(ChannelEndPoint.java:189) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.io.WriteFlusher.write(WriteFlusher.java:335) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.io.AbstractEndPoint.write(AbstractEndPoint.java:125) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpConnection$ContentCallback.process(HttpConnection.java:680) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.util.IteratingCallback.processIterations(IteratingCallback.java:166) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.util.IteratingCallback.iterate(IteratingCallback.java:126) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpConnection.send(HttpConnection.java:303) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpChannel.sendResponse(HttpChannel.java:720) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpChannel.write(HttpChannel.java:751) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:130) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:124) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.server.HttpOutput.write(HttpOutput.java:328) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.servlet.internal.ResponseWriter$NonCloseableOutputStreamWrapper.write(ResponseWriter.java:325) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.CommittingOutputStream.write(CommittingOutputStream.java:229) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$UnCloseableOutputStream.write(WriterInterceptorExecutor.java:299) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:282) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at java.io.BufferedWriter.write(BufferedWriter.java:230) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at java.io.Writer.write(Writer.java:157) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at com.tie.flow.bqapi.bigquery.BigQueryTableReaderService$1.write(BigQueryTableReaderService.java:62) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011... 45 more May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi Caused by: java.io.IOException: Broken pipe May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.ch.FileDispatcherImpl.writev0(Native Method) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.ch.SocketDispatcher.writev(SocketDispatcher.java:51) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.ch.IOUtil.write(IOUtil.java:148) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:504) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011at org.eclipse.jetty.io.ChannelEndPoint.flush(ChannelEndPoint.java:169) May 27 13:38:00 bqapi-grp-fa7g supervisord: bqapi #011... 67 more What could be the reason? A: Looks like you had : * *a low level java.io.IOException: Broken pipe *which Jetty detected and reported as a org.eclipse.jetty.io.EofException *which Jersey detected and attempted to report as an error 500 on the response, but couldn't as the response was already dead. At first blush, this seems to be a bug in Jersey attempting to write a an error response on a response that has been committed already (that's a servlet spec violation). But there's likely something else going on, as you said it seems to happen at the 1 minute mark. This points to a configuration on your socket, or firewall, or something outside of Jetty terminating the connection after some period of time. The part where we see ... Server: Jetty(9.1.z-SNAPSHOT) Via: 1.1 google points to some interesting questions. First, why are you running an unstable SNAPSHOT release of an old Jetty? And the Via: 1.1 google could indicate a GCE / GKE / GAE environment, if that's the case, what are the networking limits present on the environment you have deployed your server on?
Q: Recommended component to use in aws to connect to on-premise services I have tried to search relevant info but couldn't find anything relevant. Please point me to some links on this. I would like to know what is the best way to: Connect to on-premise SOAP services from AWS cloud on-premise Java RMI services on-premise FTP to exchange files Thanks A: Connecting to SOAP, Java RMI or FTP service on-premise is something that will part of your application logic implementation. Which infrastructure you choose to deploy your application is a matter of choice depending on factors like what knowledge you have, what other application requirements you have and so on. Provided that you have configured your on-premise servers so that they are available on the public internet, you can choose to deploy your application using any server hosting option. For AWS specifically, EC2, Elastic Beanstalk and container options EKS and ECS comes to mind in addition to Lambda.
Q: Issue with alias in bash I am facing a problem with alias command in bash. I created .bashrc in my home directory and added an alias as below: test() { "test_command_$1"; } alias au=test But when I open a new terminal and try to execute the command through alias like au arg1 it complains: bash: test_command_arg1: command not found But if I execute aliased command manually in the same terminal as test_command_arg1 it is working fine. I checked the PATH variable and it's fine. Can somebody help me to fix this? P.S: test_command_ is just an example. It is not the actual command being tried. A: You are getting the "command not found" error because of what your test() function does. test() { "test_command_$1"; } When you call this with an argument, $1 is replaced with that argument (I guess you knew this bit). So if you call au arg1, what your function is trying to do is this: "test_command_arg1" The shell is trying to execute it as a command. test_command_arg1 isn't a recognised command, so you get an error. Try changing your test function: test() { echo "test_command_$1"; }
Q: Editing a job in At command Trying here to modify a job from at command. Any idea on how to do it? Already managed to list it, delete, and execute, but can't modify it. A: If you just need to fix a typo in the shell language itself, look for your job in directory /var/spool/cron/atjobs: # type -p date | at 1430 warning: commands will be executed using /bin/sh job 2 at Fri Aug 23 14:30:00 2019 # atq 2 Fri Aug 23 14:30:00 2019 a root # ls /var/spool/cron/atjobs/ a00002018e67ea* # cat /var/spool/cron/atjobs/a00002018e67ea #!/bin/sh # atrun uid=0 gid=0 # mail root 0 umask 22 LESSCLOSE=/usr/bin/lesspipe\ %s\ %s; export LESSCLOSE LANG=en_US.UTF-8; export LANG LESS=-X; export LESS EDITOR=/usr/bin/vi; export EDITOR USER=root; export USER PAGER=/usr/bin/less; export PAGER PWD=/root; export PWD HOME=/root; export HOME XDG_DATA_DIRS=/usr/local/share:/usr/share:/var/lib/snapd/desktop; export XDG_DATA_DIRS MAIL=/var/mail/root; export MAIL SHLVL=1; export SHLVL LOGNAME=root; export LOGNAME XDG_RUNTIME_DIR=/run/user/0; export XDG_RUNTIME_DIR PATH=/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/root/bin; export PATH LESSOPEN=\|\ /usr/bin/lesspipe\ %s; export LESSOPEN cd /root || { echo 'Execution directory inaccessible' >&2 exit 1 } /bin/date Regarding modifying the date/time the job is to run, that is encoded into the filename for the job. If we suppose: # ls -ltr /var/spool/cron/atjobs/ total 12 -rwx------ 1 root daemon 1054 Aug 23 13:58 a00002018e67ea* -rwx------ 1 root daemon 1054 Aug 23 14:03 a00003018e67eb* -rwx------ 1 root daemon 1054 Aug 23 14:03 a00004018e67e9* # atq 2 Fri Aug 23 14:30:00 2019 a root 3 Fri Aug 23 14:31:00 2019 a root 4 Fri Aug 23 14:29:00 2019 a root Then the filename a00003018e67eb within the /var/spool/cron/atjobs directory is constructed thus: * *a is the "queue identifier" (the a in the atq listing) *00003 is a (hex) representation of the job number, 3 *018e67eb is the hex representation of the time the job is to run The hex value 018e67eb is 26109931 in decimal. That appears to be minutes past the epoch since 26109931 * 60 = 1566595860 and 1566595860 seconds past the epoch is Friday, August 23, 2019 2:31:00 PM here in my time zone.
Q: JQuery Mobile Icon Pack Squished on IPhone There seems to be a current bug with JQueryMobile's FA Icon Pack where, if you roll a custom JQueryMobile theme then all of JQueryMobile's original icons appear squished when you view it on an actual iPhone. The suggested work around is to use FA Icon names instead of the original ones but this doesn't fix the problems with the listview and check box icons being squished. Because of JQuery Mobile's popularity, I'm hoping someone has come across this and threw a quick fix together. A: There's actually an incredibly easy fix for this, as I have experienced the same problem. Just make sure your custom theme rolled CSS file is injected into your HTML BEFORE your FA Icon pack CSS.
Q: INSERT a SET into cassandra by passing through a variable INSERT INTO devices (id,dataformat,device_type_id,protocol_id,tags) VALUES ('asd','asdas','sad','asdas',{'asd','as'}); This one works perfectly while passing the SET in the CQL but while passing the SET using the code below it shows Invalid value Set(asd, assd) of type unknown to the query builder Code that i used, val statement: Statement = (QueryBuilder.insertInto("devices")).value("id",model.deviceId) .value("device_type_id",model.deviceType).value("protocol_id",model.protocol) .value("dataformat",model.dataFormat).value("tags",model.tag) client.executeQuery(statement) client.close() The model is of case class AddDeviceRequestModel(deviceId: String, deviceType: String, protocol: String, dataFormat: String, tag: Set[String]) A: If I am not mistaken, you are using Datastax's JavaDriver QueryBuilder. If that is the case, then you are using a Java library which expects Java types in its interface. For atomic types, that is all your fields except tag's type, it works because atomic type Scala-Java interoperability. However it isn't that easy for collection classes such as Set. You need to use Scala Java Conversion's setAsJavaSet in order to pass the set value: import scala.collection.JavaConversions.setAsJavaSet val statement: Statement =(QueryBuilder.insertInto("devices")).value("id",model.deviceId) .value("device_type_id",model.deviceType).value("protocol_id",model.protocol) .value("dataformat",model.dataFormat).value("tags",setAsJavaSet(model.tag)) client.executeQuery(statement) client.close()
Q: c# asp.net check if column in database contains string In my database, the column is stored as 'Here is jurong', I want to read out the database row if the column contains the word jurong. I tried using like but it cant work Here is the code, please help cmd = new SqlCommand("Select * from Thread WHERE (Delete_Status='No') AND (Thread_Location = '" + searchTB.Text + "' OR Thread_Title = '" + searchTB.Text + "' OR Thread_Description LIKE '%' + @Thread_Description + '%') ORDER BY ThreadID DESC ", con); cmd.Parameters.Add("@Thread_Description", SqlDbType.VarChar).Value = searchTB.Text; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); reptater.DataSource = ds; reptater.DataBind(); A: Does that SQL statement return rows when you run it in the database? Also, I'd be careful of SQL injection attacks when passing values not through parameters. Should your 'reptater' bind to a DataTable rather than a DataSet? cmd = new SqlCommand("SELECT * FROM Thread WHERE (Delete_Status='No') AND (Thread_Location = @SearchTxt OR Thread_Title = @SearchTxt OR Thread_Description LIKE '%' + @SearchTxt + '%') ORDER BY ThreadID DESC ", con); cmd.Parameters.Add("@SearchTxt", SqlDbType.VarChar); cmd.Parameters["@SearchTxt"].Value = searchTB.Text; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); reptater.DataSource = ds; //ds.Tables[0]; ? reptater.DataBind();
Q: MySQL query for row sequences Is there a way to express the following query in MySQL: Let a table have types of rows A, B, C, D, E ... Z and each row represents an event. Find the timestamps and ids of all event sequences A, .. , B, ... , C ordered by timestamp so that timestamp(C) - timestamp(A) < Thresh. For example consider the following table | type | timestamp | id | |------+-----------+-----| | Z | 19:00 | 20 | | A | 19:01 | 21 | | | | | | . | ... | .. | | | | | | A | 20:13 | 50 | * | B | 20:14 | 51 | * | D | 20:17 | 52 | | C | 20:19 | 53 | * | | | | | . | ... | .. | | | | | | A | 22:13 | 80 | * | D | 22:14 | 81 | | B | 22:15 | 82 | * | K | 22:16 | 83 | | J | 22:17 | 84 | | C | 22:19 | 85 | * | | | | | . | ... | .. | | | | | | A | 23:13 | 100 | | B | 23:14 | 101 | | C | 23:50 | 102 | The rows that the query with Thresh = 10mins should yield something along the lines of: | A_id | B_id | C_id | |------+------+------| | 50 | 51 | 53 | | 80 | 82 | 85 | See how the last triplet of A, B and C is not present. The time distance between the last A event and the last C event is more that Thresh. I suspect that the answer would be something along the lines of "MySQL is not the right tool if you need to ask this kind of question". In that case the followup is, which database is a good candidate to handle this kind of task? Edit: provided an example A: I think you can express this using a self join: SELECT A.id as A_id, B.id as B_id, C.id as C_id FROM ( SELECT * FROM the_table WHERE type = 'A' ) A JOIN ( SELECT * FROM the_table WHERE type = 'B' ) B JOIN ( SELECT * FROM the_table WHERE type = 'C' ) C ON ( (C.timestamp - A.timestamp) < 10 -- threshold here AND B.timestamp BETWEEN A.timestamp AND C.timestamp )
Q: Eclipse PDT 3.0 URL generation in debug missing? In Eclipse PDT 2.2 debug settings there was an URL settings input. I'm using this URL to manipulate the desired page to debug. In Eclipse PDT 3.0 debug settings this setting is missing. Currently, when debugging in 3.0, the URL is auto-generated to map targeted debug file: localhost/__project/path/to/index.php, but it should be targeting an arbitrary page localhost/__site-example/contact-page. Any ideas how can I get the URL independent of targeted debugged file? Or perhaps I should change the way I'm configuring the targeted debug URL? Thanks for suggestions. A: There seems to be a bug in PDT 3.0 which not just disables the function to edit the path but also disables the box for displaying path and option. By default key="auto_generated_url" value="true" , so by default you never have the possibility to edit URL. As a workaround search for the configuration-file in your workspace f.e. /workspace/.metadata/.plugins/org.eclipse.debug.core/.launches/New_configuration.launch and there you have to change the key mentioned above from true to false . Then the URL-Box should show up again. (But don't dare to switch on auto generation again! .... ) A: To mention, I think the issue/bug also involves 'Break On First Line' I have disabled that option, in the individual debug configuration, and in the global debug preferences, but the debug still breaks on first line. Your post helped me find that setting in the same file, and now the break on first line is gone/fixed. Thank you. A: I found it useful to change the stringAttribute key="base_url" value="http://xxxx to your desired url in the launch configuration (/workspace/.metadata/.plugins/org.eclipse.debug.core/.launches/xxx.launch) to launch the debug directly as required. This helped me get rid of a pesky double slash when using rewrite for codeigniter due to the autogenerated
Q: Using While condition inside of Thread's run() method I am not sure if while True: condition specified inside of run() method is necessarily. I've executed this code with and without while condition and it works fine. But I still would like to know the purpose of using it. Any ideas why it should or should not be used? from PyQt4 import QtCore, QtGui import Queue as queue app = QtGui.QApplication([]) theQueue = queue.Queue() class TheThread(QtCore.QThread): def __init__(self, theQueue, parent=None): QtCore.QThread.__init__(self, parent) self.theQueue = theQueue def run(self): while True: task = self.theQueue.get() self.sleep(1) self.theQueue.task_done() threads=[] for i in range(1, 3): thread = TheThread(theQueue) threads.append(thread) thread.start() for i in range(len(threads)): theQueue.put(i) A: The while True loop means that your thread will continue to run forever (in theory), blocking on the task = self.theQueue.get() call. If you were using threading.Thread objects, this would make your program hang and fail to exit, because Python threads will keep the main thread alive as long as they're running, unless you set the daemon attribute to True prior to starting the thread. However, because you're using QThreads, the program will exit while the threads are still running. You'll end up getting a warning when you do this though: QThread: Destroyed while thread is still running QThread: Destroyed while thread is still running I would recommend not using a while True loop, since your threads are only designed to get a single message from the main thread, and call wait (similar to threading.Thread.join) on each thread object before exiting your main program, to ensure they complete prior to the main thread exiting: class TheThread(QtCore.QThread): def __init__(self, theQueue, parent=None): QtCore.QThread.__init__(self, parent) self.theQueue = theQueue def run(self): task = self.theQueue.get() self.sleep(1) print(task) self.theQueue.task_done() threads=[] for i in range(1, 3): thread = TheThread(theQueue) threads.append(thread) thread.start() for i in range(len(threads)): theQueue.put(i) for t in threads: t.wait() If you do need the while True loop for some reason, use a sentinel to signal to the threads that they should exit: class TheThread(QtCore.QThread): def __init__(self, theQueue, parent=None): QtCore.QThread.__init__(self, parent) self.theQueue = theQueue def run(self): for task in iter(self.theQueue.get, None): # None means time to exit self.sleep(1) print(task) self.theQueue.task_done() self.theQueue.task_done() threads=[] for i in range(1, 3): thread = TheThread(theQueue) threads.append(thread) thread.start() for i in range(len(threads)): theQueue.put(i) # Time to quit for t in threads: theQueue.put(None) for t in threads: t.wait()
Q: Replacing ALAssertLibrary to get the filename Im using the following code to access filename of the image that I gotta upload. I need both filename alongside the file path and size. ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset) { ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation]; NSLog(@"[imageRep filename] : %@", [imageRep filename]); [_imageNameArray addObject:[imageRep filename]]; }; [_uploadTbleView reloadData]; ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init]; [assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil]; The problem that Im facing is, * *Xcode throws a warning message that ALAssetsLibraryAssetForURLResultBlock is deprecated. How can I replace the above code to get the filename ? *I tried using PHAsset but every time when Im selecting the file, it has got the same file name called asset.jpg for all image files. A: You can try this: PHAsset *asset = nil; PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init]; fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]]; PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions]; if (fetchResult != nil && fetchResult.count > 0) { // get last photo from Photos asset = [fetchResult lastObject]; } if (asset) { // get photo info from this asset PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init]; imageRequestOptions.synchronous = YES; [[PHImageManager defaultManager] requestImageDataForAsset:asset options:imageRequestOptions resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) { NSLog(@"info = %@", info); if ([info objectForKey:@"PHImageFileURLKey"]) { // path looks like this - // file:///var/mobile/Media/DCIM/###APPLE/IMG_####.JPG NSURL *path = [info objectForKey:@"PHImageFileURLKey"]; } }]; }
Q: How to provision an Azure IoT device from a mobile app My requirement is to develop a mobile app which itself register the mobile device in an IoT hub using provisioning services. I am developing a mobile application using react native and Azure IoT Java SDK. It is to send telemetry data to Azure IoT hub. However I don't want to hard code the IoT connection details of each and every mobile devices. There I met the IoT provision services which can be used to register the devices programmatically. My plan was to register device upon the installation or at the first boot up of the app. But the online help sources mentions that all the security attestation should be done by the manufacturer. It seems I should store an x.509 intermediate certificate in the app and generate a leaf certificate to register the device. I feel this is a bad idea. What is the proper method to handle my situation? A: You can consider using symmetric key to provision via the Device Provisioning Service. Here are some links for your reference: * *Documentation on Symmetric Key *Commit in the Java SDK that added symmetric key support You can also use X.509 certificate. If you have the leaf certificate on the device, you can register the signing cert with the Device Provisioning Service and use enrollment group.
Q: Plotly Animation: Adding play buttons to animate every nth frame I am trying to create a plotly animation with multiple play buttons. * *One button that plays every frame *One button that plays every other frame *One button that plays every 5th frame The below example sort of works but ideally I want all three play buttons to work with one pause button and one slider. Additionally, the below example is suboptimal because it makes the size of the html file twice as big. Each button stores their list of frames separately within the html file. I'd prefer each frame is stored once in the html code. import plotly.graph_objects as go list_of_frames = [] for x in range(-50,50): plot = go.Figure() this_frame = plot.add_trace(go.Scatter3d(x=[x/20, x/20+1], y=[-x/20, -x/20-1], z=[1,6], line=dict(color='red', width=8))) list_of_frames.append(go.Frame(name="{:.3f}".format(x), data=this_frame['data'], layout=this_frame['layout'])) fig = go.Figure(data=list_of_frames[0]['data'], frames=list_of_frames) def frame_args(duration): return {"frame": {"duration": duration}, "mode": "immediate", "fromcurrent": True, "transition": {"duration": 0},} sliders = [ {"steps": [{"args": [[f.name], frame_args(0)], "label": str(k), "method": "animate",} for k, f in enumerate(fig.frames)],}] fig.update_layout( scene=dict( xaxis=dict(range=[-6, 6], showgrid=False, showspikes=False, showbackground=True, showaxeslabels=True), yaxis=dict(range=[-6, 6], showgrid=False, showspikes=False, showbackground=True,showaxeslabels=True), zaxis=dict(range=[0, 8], showgrid=False, showspikes=False, showbackground=True, showaxeslabels=True)), transition=dict(duration=0), updatemenus=[{"buttons": [ { "args": [None, frame_args(0.000001)], "label": "PLAY", # play symbol "method": "animate",}, { "args": [list_of_frames[::2], frame_args(0.000001)], "label": "PLAY 2X", # play symbol "method": "animate",}, { "args": [list_of_frames[::5], frame_args(0.000001)], "label": "PLAY 5X", # play symbol "method": "animate",}, { "args": [[None], {"frame": {"duration": 0}, "mode": "immediate", "transition": {"duration": 0}}], "label": "PAUSE", # pause symbol "method": "animate",},], "type": "buttons",}], sliders=sliders) fig.show() Any help is greatly appreciated!
Q: Update global variable from while loop Having trouble updating my global variable in this shell script. I have read that the variables inside the loops run on a sub shell. Can someone clarify how this works and what steps I should take. USER_NonRecursiveSum=0.0 while [ $lineCount -le $(($USER_Num)) ] do thisTime="$STimeDuration.$NTimeDuration" USER_NonRecursiveSum=`echo "$USER_NonRecursiveSum + $thisTime" | bc` done A: That particular style of loop does not run in a sub-shell, it will update the variable just fine. You can see that in the following code, equivalent to yours other than adding things that you haven't included in the question: USER_NonRecursiveSum=0 ((USER_Num = 4)) # Add this to set loop limit. ((lineCount = 1)) # Add this to set loop control variable initial value. while [ $lineCount -le $(($USER_Num)) ] do thisTime="1.2" # Modify this to provide specific thing to add. USER_NonRecursiveSum=`echo "$USER_NonRecursiveSum + $thisTime" | bc` (( lineCount += 1)) # Add this to limit loop. done echo ${USER_NonRecursiveSum} # Add this so we can see the final value. That loop runs four times and adds 1.2 each time to the value starting at zero, and you can see it ends up as 4.8 after the loop is done. While the echo command does run in a sub-shell, that's not an issue as the backticks explicitly capture the output from it and "deliver" it to the current shell.
Q: Bootstrap navbar only working after resize with IE9 I am helping a friend with the design of his homepage using bootstrap 3. Now the design is almost ready, but we have come across a strange behaviour of the navbar at the bottom of the page when accessing the page with IE9. As usual there are four sizes defined (large, medium, small, xtrasmall). If the page is loaded for the first time with IE9 in large or medium size, the navbar does not work. Only after re-sizing the window to at least small or xtrasmall the navbar works - even in large or medium. With Chrome, FF or Safari, everything works fine. Any idea, how we could fix the behaviour? website: www.theballroomshow.com Bernhard A: It seems to be related to a sort of "IE9 z-index" bug. I found this: http://icreatestuff.co.uk/blog/article/ie9-z-index-stacking-problem-or-something-stranger and added a transparent 1x1 "fixer.png" to the navbar. Now it works immediately in IE9 without resizing. Glad, that I am using Firefox most of the times. :-)
Q: Bayesian testing between two rate constants Suppose I have 2 models which represent the same chemical system. Both models have the exact same reactions, however the second model has a slight variation. The variation is regarding an intervention, for model 1 we assume that we have 1 intervention in which $1000$ of molecule $X$ is dumped into our chemical system in one big go, whereas model 2 assumes that we dump $200$ molecules of $X$ in in 5 even time intervals (so total number of molecules dumped into each system is equal). I want to see what affect this variation has on one of my rate constants in my chemical system, let's call this rate constant $c$. I use the gillespie algorithm to simulate both models, the models are stochastic hence each result is unique from the last. I assume to have perfect information so I know the complete sample path, i.e. know the time and type of each reaction that occurs. As I know the time and type of each reaction I am able to calculate how many times each reaction occurs and update my prior beliefs of my rate constants to my updated posterior My question is: What is a good Bayesian test to perform to test difference in rate constants or something along those lines. Further detail: Following on from the 1st paragraph where I outline the models. A very important assumption I have about my rate constant $c$ is that it has a gamma distribution. Also for this reaction with rate constant $c$ I assume my prior beliefs to be the same for both models. What I have done: So after thinking about this for a while, I thought a good place to start off would be to do 50 simulated repetitions of this system for each model. This allows me to get 50 unique posterior distributions for each model for my rate constant $c$ based on the data which was simulated. Now I know, as I have a gamma distribution, that the expectation (ie mean) for each updated posterior is $\frac{a}{b}$ for a posterior $\sim Ga(a,b)$ and variance $\frac{a}{b^2}$. Maybe I could test between the ranges between the expectations/variances for my rate constant $c$ between the 2 models. I hope this is clear, if there is any part that is not I will make sure to edit the question. A second, perhaps better, approach: Maybe what I could do is see what the bayes factor is given a data set when comparing my 2 models. I was wondering how I would go about this, as every time I've attempted to do bayes factors it seems to go horribly wrong Edit: I was looking to do something along the lines of these plots (https://stackoverflow.com/questions/11546256/two-way-density-plot-combined-with-one-way-density-plot-with-selected-regions-in?rq=1) but not entirely sure how to go about this. Should I take the 50 variances for each model and do a density plot between the 2?
Q: Want to develope multiple apk to upload on google play for single application of indic font I am developing indic font application for android but some devices not able to render indic fonts for that I am going to use images of indic text ,that will created on server side and my application going to fetch it at runtime this thing is doable for me. I want to make two apk for upload on google play. 1)I can upload multiple apk for single application using this Link shows how to upload multiple apk Is it a best solution to create multiple apk for this. reasons to make multiple apk are for these are 1) Device which can render indic font use text rendering apk for fast downloading because images of text slow down my app. help me what is the best solution for this problem A: You probably won't be able to use multiple .APKs for this, and you probably don't want to. The Official Docs state that you wouldn't be able to filter by font availability. However, what you should do, is use a single APK, and detect at runtime if Indic fonts work on a given device, and switch between those features at runtime.
Q: Meteor/React - Update subscription on state change I'm in trouble with subscription and React, maybe i don't do it the right way. Here is the problem : i'd like to create a page with a movies list provided by a mongo collection, there is also a genre filter and a "load more" button. When i use load more only, i update publication to skip existing item and return new ones, it work well. When i change my genre filter, i simply update my publication with that filter, work fine too... But if i do that two actions together, for example : load more, then filter by genre, the results looks bad and seems to keep old results, pagination isn't reseted to default value. Here is a simplified version of my code. Server side publication : Meteor.publish('movies.published', function ( sort = null, skip = 0, limit = 20, filters = {} ) { if ( ! sort || typeof sort !== 'object' ) { sort = {releaseDate: -1}; } let params = Object.assign({ webTorrents: { $exists: true, $ne: [] }, status: 1, }, filters); console.log( '----------------Publishing--------------------'); let cursor = Movies.find(params, { sort: sort, skip: skip, limit: limit }); // Test publication // Count is always good console.log(cursor.fetch().length); return cursor; }); Client side component : import React from "react"; import TrackerReact from "meteor/ultimatejs:tracker-react"; import Movies from "/imports/api/movies/movies.js"; import Genres from "/imports/api/genres/genres.js"; const itemPerPage = 1; // let's say 1 item to simplify our test const defaultOrder = 'releaseDate'; export default class Home extends TrackerReact(React.Component) { constructor(props) { super(props); let options = Object.assign(Meteor.settings.public.list.options, {genres: Genres.find()}); this.state = { subscription: { movies: Meteor.subscribe('movies.published', {[defaultOrder]: -1}, 0, itemPerPage), }, filters: {}, sort: defaultOrder, options: options, }; } componentWillUnmount() { this.state.subscription.movies.stop(); } filterByGenre(event) { let filterGenre = { ['genres.slug']: event.target.value !== '' ? event.target.value : {$ne: null} }; this.updateFilters(filterGenre); } updateFilters( values ) { // Merge filters let filters = Object.assign(this.state.filters, values); console.log('updating filters', filters); // Update subscription with filters values // here i must reset the pagination this.state.subscription.movies.stop(); let newSubscription = Object.assign({}, this.state.subscription, { movies: Meteor.subscribe('movies.published', {[this.state.sort]: -1}, 0, itemPerPage, filters), }); this.setState({ subscription: newSubscription, filters: filters, }) } loadMore( skip ) { // Add an item let newSubscription = Object.assign({}, this.state.subscription, { movies: Meteor.subscribe('movies.published', {[this.state.sort]: -1}, skip, itemPerPage, this.state.filters), }); this.setState({ subscription: newSubscription, }); } render() { if ( ! this.state.subscription.movies.ready() ) { return ( <div>loading...</div> ); } // Get our items let movies = Movies.find().fetch(); return ( <div> <div className="container-fluid"> {/* Filters */} <form className="form form-inline"> <div className="form-group m-r m-2x"> <select className="form-control" value={this.state.filters['genres.slug'] && this.state.filters['genres.slug']} onChange={this.filterByGenre.bind(this)}> <option value="">Genres</option> {this.state.options.genres.map((genre, key) => { return <option key={key} value={genre.slug}>{genre.name}</option> })} </select> </div> </form> <hr /> {/* list */} <div className="row list"> {movies.map((movie) => { return ( <div key={movie._id} className="col-xs-2">{movie.title}</div> ) })} </div> {/* Load more */} <button id="load-more" type="button" className="btn btn-sm btn-info" onClick={this.loadMore.bind(this, movies.length)}> Load more </button> </div> <div className="col-xs-3 pull-right text-right">{movies.length} movies</div> <hr /> </div> ) } } Here is a better way to do that ? Thanks for your help ! A: I founded what was the problem. When using the method loadMore, i don't stop the old subscription (i want to keep old items and add the new ones), the problem is that "addMore" subscription was keeped in my subscriptions array (see Meteor.default_connection._subscriptions). So when i change filters i close only the last "loadMore" subscription... 2 solutions : * *Loop through Meteor.default_connection._subscriptions, to close old "LoadMore" subscriptions. *Keep a copy of old items in a array and merge them with new ones after subscription was updated, that what i did. Updated client code : import React from "react"; import TrackerReact from "meteor/ultimatejs:tracker-react"; import Movies from "/imports/api/movies/movies.js"; import Genres from "/imports/api/genres/genres.js"; const itemPerPage = 1; const defaultOrder = 'releaseDate'; export default class Home extends TrackerReact(React.Component) { constructor(props) { super(props); let options = Object.assign(Meteor.settings.public.list.options, {genres: Genres.find()}); this.state = { subscription: { movies: Meteor.subscribe('movies.published', {[defaultOrder]: -1}, 0, itemPerPage), moviesCount: Meteor.subscribe('movies.count'), }, skip: 0, filters: {}, sort: defaultOrder, options: options, }; // our local data this.data = []; this.previous = []; } componentWillUnmount() { this.state.subscription.movies.stop(); } filterByGenre(event) { let filterGenre = { ['genres.slug']: event.target.value !== '' ? event.target.value : {$ne: null} }; this.updateFilters(filterGenre); } updateFilters( values ) { // Merge filters let filters = Object.assign(this.state.filters, values); // Update subscription ( reset pagination ) this.state.subscription.movies.stop(); this.state.subscription.moviesCount.stop(); let newSubscription = Object.assign({}, this.state.subscription, { movies: Meteor.subscribe('movies.published', {[this.state.sort]: -1}, 0, itemPerPage, filters), moviesCount: Meteor.subscribe('movies.count', filters), }); this.setState({ subscription: newSubscription, filters: filters, skip: 0, }); } loadMore() { // Keep a copy of previous page items this.previous = this.data; // Update subscription this.state.subscription.movies.stop(); let newSubscription = Object.assign({}, this.state.subscription, { movies: Meteor.subscribe('movies.published', {[this.state.sort]: -1}, this.previous.length, itemPerPage, this.state.filters) }); this.setState({ subscription: newSubscription, skip: this.previous.length, }); } getMovies() { // Wait subscription ready to avoid replacing items if ( ! this.state.subscription.movies.ready() ) { return this.previous; } // Get new data and merge with old ones let newData = Movies.find().fetch(); this.data = this.previous.concat(newData); // Reset previous array this.previous = []; return this.data; } render() { if ( ! this.state.subscription.movies.ready() && ! this.previous.length ) { return ( <div>loading...</div> ); } // Get our items let movies = this.getMovies(); return ( <div> <div className="container-fluid"> {/* Filters */} <form className="form form-inline"> <div className="form-group m-r m-2x"> <select className="form-control" value={this.state.filters['genres.slug'] && this.state.filters['genres.slug']} onChange={this.filterByGenre.bind(this)}> <option value="">Genres</option> {this.state.options.genres.map((genre, key) => { return <option key={key} value={genre.slug}>{genre.name}</option> })} </select> </div> </form> <hr /> {/* list */} <div className="row list"> {movies.map((movie) => { return ( <div key={movie._id} className="col-xs-2">{movie.title}</div> ) })} </div> {/* Load more */} <div className="row"> <div className="col-xs-12 text-center"> {Counts.get('movies.count') > movies.length && <button id="load-more" type="button" className="btn btn-sm btn-info" onClick={this.loadMore.bind(this)}> Load more </button> } </div> </div> </div> <div className="col-xs-3 pull-right text-right">{Counts.get('movies.count')} movies</div> <hr /> </div> ) } } I hope it will help !
Q: HttpServletRequest getCookies() always returns null Jersey Api I m able to add the cookie to response and view it on my chrome browser. I checked it through settings --> advancedSettings --> content settings. @Context HttpServletRequest servletRequest; Cookie[] cookies = servletRequest.getCookies(); I m using @Context to get the request and getCookies() always returns null . I m able to see the cookie in request headers in chrome using Inspect Element. A: I was using @context UriInfo and uriInfo variable add a request with cookie part of its header. I was able to extract the cookie as single String and do String manipulation over it but it works fine. Still HttpServletRequest getCookies it didn't work.
Q: Object reference not set to an instance of an object? Having problem setting my script from 2d to 3d ;-; Here ist my whole script This is the Line where it seems like I have a problem with. Since im not super experienced I took this code out from a 2D Game. Vector3Int gridPosition = tileMapReadcontroller.GetGridPosition(Input.mousePosition, mousePosition: true); Not sure if this is a problem when im trying to insert this in a 3D world :(
Q: Making next button behave like submit button I have a form that has 3 parts.Each part needs to be validated before it can move to next part. The catch is that there can be only one submit button at the end of it, since I call an external client to process/store the form. The reason it needs to act like submit button is because it needs to validate the form elements. The JS works for navigation perfectly, need to find a way to incorporate validation EDIT: The submit button should work like a submit button but the next button can work as validation button Code: <form> <fieldset> <h2>Personal Details</h2> <input type="text" name="first_name" placeholder="First Name" required/> <input type="text" name="last_name" placeholder="Last Name" required/> <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> <fieldset> <h2 class="fs-title"> Details</h2> <input type="text" name="emailaddress" placeholder="Email" required/> <input type="text" name="phonenum" placeholder="Phone" required/> <input type="button" name="previous" class="previous action-button-previous" value="Previous" /> <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> <fieldset> <h2>More</h2> <input type="text" name="city" placeholder="City" /> <input type="text" name="state" placeholder="State" /> <input type="text" name="zip" placeholder="Zip Code" /> <input type="button" name="previous" class="previous action-button-previous" value="Previous" /> <button type="button" name="submit" class="submit action-button" value="Submit" onclick="callclient()">Submit </button> </fieldset> </form> A: Here you go. The code comments should explain it well enough, and it could use additional polishing, but it should get you started: HTML: // I started by separating each form section into its own form <form class="form-step"> <fieldset> <h2>Personal Details</h2> <input type="text" name="first_name" placeholder="First Name" required/> <input type="text" name="last_name" placeholder="Last Name" required/> <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> </form> <form class="form-step"> <fieldset> <h2 class="fs-title"> Details</h2> <input type="email" name="emailaddress" placeholder="Email" required/> <input type="phone" name="phonenum" placeholder="Phone" required/> <input type="button" name="previous" class="previous action-button-previous" value="Previous" /> <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> </form> <form class="form-step"> <fieldset> <h2>More</h2> <input type="text" name="city" placeholder="City" /> <input type="text" name="state" placeholder="State" /> <input type="text" name="zip" placeholder="Zip Code" /> <input type="button" name="previous" class="previous action-button-previous" value="Previous" /> <button type="button" name="submit" class="submit action-button" value="Submit">Submit </button> </fieldset> </form> jQuery: $(document).ready(function(){ var forms = $('form'); // Whenever a button is clicked $(':button').on('click', function(e){ // Get the current form and the button name var $form = $(this).parentsUntil('form'); var button_name = $(this).attr('name'); // Validate the form unless going backwards if(validate($form) || button_name === 'previous'){ switch(button_name) { case 'next': // Next next_form(); break; case 'previous': // Previous prev_form(); break; case 'submit' : // Submit submit_forms(); break; default: // Do nothing } }else{ // Form not valid } }); // Show next function next_form(){ // Get all visible forms var visible_forms = $('form:visible'); // Get the last form in the array var $current_form = $(visible_forms).last(); // Get the next form var $next_form = $current_form.next(); // Handle visibility of buttons $current_form.find(':button').css('visibility','hidden'); // Show the next form $next_form.fadeIn(); } // Show previous function prev_form(){ var visible_forms = $('form:visible'); var $current_form = $(visible_forms).last(); var $prev_form = $current_form.prev(); $prev_form.find(':button').css('visibility','visible'); $current_form.fadeOut(); } // Submit function submit_forms(){ // All forms are valid // Create new form programically that contains all form elements // Submit it var form_data = forms.find('input:not(:button)').clone(); var action = '/echo/html/'; var method = 'POST'; var $full_form = $('<form/>').attr({ action: action, method: method }).append(form_data); // Submit the form $full_form.appendTo('body').css('display','none').submit(); } }) // Validate expects jQuery object function validate($form){ // Set valid to true var valid = true; // Any invalid element will set valid to false $.each($form.find('input:not(:button)'), function(index, input){ // Utilizing HTML5 validation if(!input.checkValidity()){ valid = false; } }) return valid; } Here's the working jsFiddle.
Q: How to add methods dynamically I'm trying to add methods dynamically from external files. Right now I have __call method in my class so when i call the method I want, __call includes it for me; the problem is I want to call loaded function by using my class, and I don't want loaded function outside of the class; Class myClass { function__call($name, $args) { require_once($name.".php"); } } echoA.php: function echoA() { echo("A"); } then i want to use it like: $myClass = new myClass(); $myClass->echoA(); Any advice will be appreciated. A: You can dynamically add attributes and methods providing it is done through the constructor in the same way you can pass a function as argument of another function. class Example { function __construct($f) { $this->action=$f; } } function fun() { echo "hello\n"; } $ex1 = new class('fun'); You can not call directlry $ex1->action(), it must be assigned to a variable and then you can call this variable like a function. A: if i read the manual right, the __call get called insted of the function, if the function dosn't exist so you probely need to call it after you created it Class myClass { function __call($name, $args) { require_once($name.".php"); $this->$name($args); } } A: Is this what you need? $methodOne = function () { echo "I am doing one.".PHP_EOL; }; $methodTwo = function () { echo "I am doing two.".PHP_EOL; }; class Composite { function addMethod($name, $method) { $this->{$name} = $method; } public function __call($name, $arguments) { return call_user_func($this->{$name}, $arguments); } } $one = new Composite(); $one -> addMethod("method1", $methodOne); $one -> method1(); $one -> addMethod("method2", $methodTwo); $one -> method2(); A: You cannot dynamically add methods to a class at runtime, period.* PHP simply isn't a very duck-punchable language. * Without ugly hacks. A: What you are referring to is called Overloading. Read all about it in the PHP Manual A: You can create an attribute in your class : methods=[] and use create_function for create lambda function. Stock it in the methods attribute, at index of the name of method you want. use : function __call($method, $arguments) { if(method_exists($this, $method)) $this->$method($arguments); else $this->methods[$method]($arguments); } to find and call good method. A: /** * @method Talk hello(string $name) * @method Talk goodbye(string $name) */ class Talk { private $methods = []; public function __construct(array $methods) { $this->methods = $methods; } public function __call(string $method, array $arguments): Talk { if ($func = $this->methods[$method] ?? false) { $func(...$arguments); return $this; } throw new \RuntimeException(sprintf('Missing %s method.')); } } $howdy = new Talk([ 'hello' => function(string $name) { echo sprintf('Hello %s!%s', $name, PHP_EOL); }, 'goodbye' => function(string $name) { echo sprintf('Goodbye %s!%s', $name, PHP_EOL); }, ]); $howdy ->hello('Jim') ->goodbye('Joe'); https://3v4l.org/iIhph A: You can do both adding methods and properties dynamically. Properties: class XXX { public function __construct($array1) { foreach ($array1 as $item) { $this->$item = "PropValue for property : " . $item; } } } $a1 = array("prop1", "prop2", "prop3", "prop4"); $class1 = new XXX($a1); echo $class1->prop1 . PHP_EOL; echo $class1->prop2 . PHP_EOL; echo $class1->prop3 . PHP_EOL; echo $class1->prop4 . PHP_EOL; Methods: //using anounymous function $method1 = function () { echo "this can be in an include file and read inline." . PHP_EOL; }; class class1 { //build the new method from the constructor, not required to do it here by it is simpler. public function __construct($functionName, $body) { $this->{$functionName} = $body; } public function __call($functionName, $arguments) { return call_user_func($this->{$functionName}, $arguments); } } //pass the new method name and the refernce to the anounymous function $myObjectWithNewMethod = new class1("method1", $method1); $myObjectWithNewMethod->method1(); A: I've worked up the following code example and a helper method which works with __call which may prove useful. https://github.com/permanenttourist/helpers/tree/master/PHP/php_append_methods
Q: issue integrating flex with ruby on rails I'm having an issue integrating flex with ruby on rails. I get this error: ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): <internal:prelude>:8:in `synchronize' /Users/tammam56/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service' /Users/tammam56/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run' /Users/tammam56/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread' I believe Rails automatically generate an AuthenticityToken when using "View" components that generates the HTML as I notice in the console AuthenticityToken gets passed with every request. But When I'm using Flex as my client interface instead of HTML generated by view how do I get/generate this AuthenticityToken and store it in Flex. Thanks, Tam A: Hey, great question. This was actually a pretty tough problem to solve, but Dima and contributors from RestfulX have solved it quite nicely. In short, you have to store the authenticity token in Flex after the first request Flex makes to Rails, right when everything starts up. Then you pass it back with every request from Flex to Rails. To get the request, RestfulX has an initializer script that gets in there with the Rack middleware to send the authenticity token to Rails. I suggest checking out the RestfulX Google Group, and checking out the sample Pomodo on Rails application (RestfulX integrating Flex and Rails). It's a serious Project Management Flex app with an Admin system, so check out the code for all that authentication stuff. It was built off a script like this one: FlashSessionCookieMiddleware And here's a tutorial explaining file uploads between Flex and Rails, which have a lot of issues with authenticity tokens. Let me know how it goes! Lance A: I'm not a flex specialist but here is how you store in a js variable: window._token = '<%= form_authenticity_token %>'; A: There's a blog post on it that describes all the steps in how to do it. See at: http://blog.dt.org/index.php/2008/06/rails-2-flex-3-and-form-authenticity-tokens/ Hope it helps
Q: Naive matrix multiplication improvement My CS teacher asked us to "add a small change" to this code to make it run with time complexity of N3 - N2 instead of the normal N3. I cannot for the life of me figure it out and I was wondering if anyone happened to know. I don't think he is talking about strassens method. from when I looked at it, maybe it could take advantage of the fact that he only cares about a square (diagonal) matrix. void multiply(int n, int A[][], int B[][], int C[][]) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { C[i][j] = 0; for (int k = 0; k < n; k++) { C[i][j] += A[i][k]*B[k][j]; } } } } A: You cannot achieve Matrix multiplication in O(N2). However, you can improve the complexity from O(N3). In linear algebra, there are algorithms like the Strassen algorithm which reduces the time complexity to O(N2.8074) by reducing the number of multiplications required for each 2x2 sub-matrix from 8 to 7. An improved version of the Coppersmith–Winograd algorithm is the fastest known matrix multiplication algorithm with the best time complexity of O(N2.3729).
Q: How to switch windows in Vim in Windows (the OS)? I've read that Ctrl-W + hjkl switches windows in Vim from this answer, but when I try that it simply closes my terminal. I'm on Windows and using vim on a remote account in my terminal. A: I was using Git Bash inside Console2, and Console2 had Ctrl+W bound to "close tab".
Q: How to draw text on XImage object in Linux I read the reference of Xft library, but it seems to draw text only on server site drawable: Pixmap or Window. The same is about the native xlib text drawing functions. But how to draw some text on a XImage object that has an array of pixels in memory on the client site? What library to use and where to find some reference and example sources? There is no need for ultra-high-quality typography and probably RTL is not needed. On the other hand it is good to have UTF-8 support and simple API. For example FreeType seems to be not what is needed - it renders single glyphs, not directly Unicode text. This way, what I need is the API of Xft, but for memory bitmaps. (Or as an example Win32 TextOut level function). I prefer a plain C code examples, but any other non-OOP language is OK too. A: most toolkits are using pango for this. If you target more than just latin scripts it is probably the only sane choice around. Otherwise plain freetype rendering might be enough for you (there are plenty of examples). If you need complex scripts but want to go low level, use freetype + harfbuzz
Q: Reset Button for highchart drilldown pie I have implemented drilldown pie chart using highcharts with 3 level drilldowns. I would like to add a reset button that brings back the pie chart to initial state if the user has drilldown to any level. is there a way to implement the reset? Thanks in advance A: You can use drillUp method: document.getElementById('drillUp').addEventListener('click', function(){ chart.drillUp(); if(chart.series[0].name !== "Browsers"){ chart.drillUp(); } }); Live demo: https://jsfiddle.net/BlackLabel/0ju31xb8/ API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#drillUp
Q: Send correct JSON as parameter to RPC I need to make an rpc to a thirh party API and send the following JSON { "jsonrpc":"2.0", "id":"number", "method":"login.user", "params":{ "login":"string", "password":"string" } } I have created a method to make the rcp but i cannot get the correct JSON to be send public JObject Post() { object[] a_params = new object[] { "\"login\" : \"[email protected]\"", "\"password\": \"Password\""}; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://test.test.ru/v2.0"); webRequest.ContentType = "application/json; charset=UTF-8"; webRequest.Method = "POST"; JObject joe = new JObject(); joe["jsonrpc"] = "2.0"; joe["id"] = 1; joe["method"] = "login.user"; if (a_params != null) { if (a_params.Length > 0) { JArray props = new JArray(); foreach (var p in a_params) { props.Add(p); } joe.Add(new JProperty("params", props)); } } string s = JsonConvert.SerializeObject(joe); // serialize json for the request byte[] byteArray = Encoding.UTF8.GetBytes(s); webRequest.ContentLength = byteArray.Length; WebResponse webResponse = null; try { using (webResponse = webRequest.GetResponse()) { using (Stream str = webResponse.GetResponseStream()) { using (StreamReader sr = new StreamReader(str)) { return JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd()); } } } } catch (WebException webex) { using (Stream str = webex.Response.GetResponseStream()) { using (StreamReader sr = new StreamReader(str)) { var tempRet = JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd()); return tempRet; } } } catch (Exception) { throw; } } With my code i'm getting the following JSON {"jsonrpc":"2.0","id":1,"method":"login.user","params":["\"login\" : \"[email protected]\"","\"password\": \"AmaYABzP2\""]} As i understand my error is that params is an array([]) instead of an object({}). Based on my method how can get the correct json? A: I correct my mistake. The code shoukd be JObject a_params = new JObject { new JProperty("login", "login"), new JProperty("password", "Password") }; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://test.test.ru/v2.0"); webRequest.ContentType = "application/json; charset=UTF-8"; webRequest.Method = "POST"; JObject joe = new JObject(); joe["jsonrpc"] = "2.0"; joe["id"] = "1"; joe["method"] = "login.user"; joe.Add(new JProperty("params", a_params));
Q: Using readr to declare/parse three different types of dates I have struggled for quite some time now to read in a dataset and parse the proper date format using readr. My data looks like this: short_name full_name month Euro Jan January 1 10 Feb February 2 20 Mar March 3 30 Apr April 4 40 May May 5 50 Jun June 6 60 What I do want to do is to declare the first three columns (short_name, full_name, month) all a month so I can later use them to plot in ggplot. Variant_1: Here I try to read in the data and declare it read_csv2(file = "abc.csv", col_names = TRUE, col_types = cols(short_name = col_date(format = ("%b")), full_name = col_date("%B"), month = col_date(format = "%m"), Euro = col_integer())) Variant_2: Here I try to read in the data as character and later parse the proper format read_tsv("abc.txt", col_names = T, col_types = cols(short_name = col_character(), full_name = col_character(), month = col_character(), Euro = col_character())) parse_datetime(abc$full_name, format = "%B", locale = ("en_US")) None of them worked so far and I have received a lot of different errors. Is it even possible to use "%B" and "%b" and "%m" alone to declare a dataset?
Q: How to use raw_input in a socket Just before I say anything, if you are confused about the title it means to say I used this bit of code: cmd, addr = sock.accept() how could I use that code for the clients to see the raw_input, Here's my code: from socket import * sock = socket(AF_INET, SOCK_STREAM) HOST = "0.0.0.0" PORT = 8080 sock.bind((HOST, PORT)) sock.listen(5) while True: cmd, addr = sock.accept() cmd.send ('Welcome to server.py\r\n') main = raw_input("> ") Here is my output: -bash-4.1# python server.py > i want that to be on the client side when they connect that's there but its on the server side A: [Converting my comment to an answer] There are two applications here (possibly on two different machines). One application opens a server socket and listens for the connection. Upon a connection from another process (client), it sends the string Welcome to server ... . The second application creates a client socket and connects to the server. Once connection is established the two processes can talk to each other using such strings (this is slightly inaccurate, but is okay for this answer). It is then the job of the two processes to co-ordinate with each other using whatever they have received from the other side. i want that to be on the client side when they connect that's there but its on the server side Thing is its coming up on the server side What you need to do is change your client process (the one can connects to the server) -- NOT the script you have posted -- the other process, to have raw_input(..).
Q: Problema en login con password_verify() reciban un cordial saludo y gracias de antemano por sus respuestas; como indica el título, el problema se presenta al querer comparar una contraseña proveniente del login con la contraseña que ya está guardada en mi bd y encriptada con anticipación a través del registro de usuario, colocaré porciones de código para mayor comprensión, primero les explico como encripté la contraseña y el tipo de algoritmo utilizado: Controlador "Registro" (Encriptando contraseña) $contrasena = password_hash($_POST['contrasena'], PASSWORD_BCRYPT); Instanciando y utilizando un método de la clase Registro $objeto = new Registro; $respuesta = $objeto->registrarUsuario($cedula, $username, $contrasena, $correo, $claveAcceso, $idRol); Modelo "Registro" public function registrarUsuario($cedula, $username, $contrasena, $correo, $claveAcceso, $idRol) { $query = 'INSERT INTO usuarios (cod_usuario, username, password, email, clave_acceso, rol_id, status) VALUES (:cedula, :username, :contrasena, :correo, :claveAcceso, :idRol, 1)'; try { $PDOStatement = Conexion::prepare($query); $PDOStatement->bindParam(':cedula', $cedula, \PDO::PARAM_STR); $PDOStatement->bindParam(':username', $username, \PDO::PARAM_STR); $PDOStatement->bindParam(':contrasena', $contrasena, \PDO::PARAM_STR); $PDOStatement->bindParam(':correo', $correo, \PDO::PARAM_STR); $PDOStatement->bindParam(':claveAcceso', $claveAcceso, \PDO::PARAM_STR); $PDOStatement->bindParam(':idRol', $idRol, \PDO::PARAM_STR); $PDOStatement->execute(); return 'Registro Exitoso'; } catch (PDOException $e) { return $e->getMessage(); } } Hasta acá todo bien, debo hacer una pausa para comentarles que el campo de mi entidad donde guardo la contraseña encriptada posee una longitud de 255 caracteres. Una vez registrado el usuario procedo a trabajar sobre el login y acá viene el detalle: Controlador "Login" if (isset($_POST['submit'])) { $cedula = $_POST['letra_cedula'] . $_POST['cedula']; $contrasena = $_POST['contrasena']; $objeto = new Login; $usuariosRegistrados = $objeto->obtenerUsuariosRegistrados($cedula); print_r($usuariosRegistrados); if ($usuariosRegistrados != NULL) { foreach ($usuariosRegistrados as $valor) { if ($cedula == $valor['cod_usuario'] && password_verify($contrasena, $valor['password'])) { print_r($valor['password']); } } } else { echo $autenticacion = 'Cédula o contraseña incorrectos'; } } Reconozco que la variable $contraseña no la estoy utilizando, lo que sucede es que ando realizando distintos tipos de pruebas para hallar la solución pero no he tenido éxito, me apoyé en la siguiente fuente: Login con password_verify Modelo Login public function obtenerUsuariosRegistrados($cedula) { $query = 'SELECT cod_usuario, password FROM usuarios WHERE cod_usuario = :cedula'; try { $PDOStatement = Conexion::prepare($query); $PDOStatement->bindParam(':cedula', $cedula, \PDO::PARAM_STR); //$PDOStatement->bindParam(':contrasena', $contrasena, \PDO::PARAM_STR); $PDOStatement->execute(); return $usuariosRegistrados = $PDOStatement->fetchAll(); } catch (PDOException $e) { return $e->getMessage(); } } Cualquier sugerencia y/o ayuda será bien recibida, más información en caso de que la necesiten: PHP 7.3.1 (cli) (built: Jan 9 2019 22:43:14) ( ZTS MSVC15 (Visual C++ 2017) x86 ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.3.1, Copyright (c) 1998-2018 Zend Technologies A: Gracias por sus respuestas. Logré solucionar el problema aplicando la lógica del siguiente vídeo: https://www.youtube.com/watch?v=j6I1p2DlxYM&t=324s Sin embargo, después de realizar varias pruebas, increíblemente funcionó prácticamente como estaba antes (como lo había publicado acá). Realmente no reconozco qué fue lo que sucedió, pero dejo los pasos realizados por si le sirve a alguien más: * *Me aseguré con var_dump() que la contraseña encriptada llegaba bien a mi controlador. *Apliqué la lógica del vídeo al traer la contraseña encriptada y usar la función password_verify(). *Fui al gestor de bbdd pgadmin y cambié la longitud de mi campo llamado password de 255 a 60 caracteres con tipo de dato character varying (VARCHAR). Para este punto funcionaba todo increíble, es excelente pero acá viene lo extraño: posteriormente me di a la tarea de realizar una última prueba y colocar prácticamente el mismo código que publiqué acá y también funcionó. Aún estoy averiguando el por qué de esto. Coloco cómo quedó el código: <?php if (isset($_POST['submit'])) { $cedula = $_POST['letra_cedula'] . $_POST['cedula']; $contrasena = $_POST['contrasena']; $objeto = new Login; $usuariosRegistrados = $objeto->obtenerUsuariosRegistrados($cedula); //Recorremos registros obtenidos de la bd y lo comparamos con lo que hemos recibido del Frontend if ($usuariosRegistrados != NULL) { foreach ($usuariosRegistrados as $valor) { if ($contrasena == password_verify($contrasena, $valor['password'])) { /*Redirección al index, pasamos la variable url con valor 'home' vía GET, así una vez que /* el usuario se logee entrará en la interfaz home y se podrá visualizar la posición actual /* en la que se encuentra a través de la url /* /* Nota: Como estamos trabajando indexado y con jquery él capturará eso que envíamos vía GET, /* él recibirá 'homeControlador', aquí envíamos 'home' y el archivo index le agrega el sufijo /* 'Controlador' debido a esto se utiliza un condicional en el Frontend */ header('Location:index.php?url=home'); } else { echo $autenticacion = 'Cédula o contraseña incorrectos'; } } } else { echo $autenticacion = 'Cédula o contraseña incorrectos'; } } Si prestamos atención al condicional en donde se valida la contraseña que viene del login y la que está encriptada se darán cuenta que antepuse la variable $contraseña al comparar (eso no estaba). Sin embargo, sin anteponer esa variable funciona igualmente... cosas de la vida. Gracias a @franmost por la sugerencia de reducir código.
Q: Possible causes of pthread_cond_wait()'s not releasing a mutex? My program is seemingly having a deadlock problem. Basically I have a class that looks like this: class Foo { public: Foo(); void bar(); private: void monitor(); bool condition_; pthread_t monitor_; pthread_mutex_t mutex_; pthread_cond_t cv_; }; In Foo's constructor, I invoke monitor() in a separate thread (namely monitor_). This monitor() function does the following: pthread_mutex_lock(&mutex_); while (true) { while (!condition_) { pthread_cond_wait(&cv_, &mutex_); } // do something // and then setting condition_ to false condition_ = false; } pthread_mutex_unlock(&mutex_); The bar() function is the only public interface (excluding ctor and dtor) of Foo. It also needs to acquire the mutex in its execution. My symptom is that bar() can never acquire mutex_. It looks like pthread_cond_wait() does not release the mutex as it is supposed to do. And if I disable the monitor thread (thus no racing condition), then bar() can run to its completion without any problem. Of course, the above code is a stripped-down version of my real code. Actually I think there is no logic error in this code and I'm using pthread correctly. I'm suspecting if there are any other causes for this deadlock situation. Can anyone give a clue on this? Thanks! A: My bet is that it fails in here: while (!condition_) { pthread_cond_wait(&cv_, &mutex_); } Let's assume, condition is false. You enter the while loop and in the first run everything goes fine, i.e. you unlock the mutex and wait on the decision variable. Can it happen that the condition variable changes but not the boolean condition ? In that case you would enter pthread_cond_wait with an uninitialized mutex and undefined behaviour can occur... I guess it would help if you would show the bar() method as well. Another guess would be thread priorities. Maybe insert a yield to give the threads a better chance to switch. A: I would look at your constructor and the bar() function, and possibly if you've accidentally made a copy of the object in question. I've copied the classes you provided, and my assumptions on how the rest of it operates below. The program below wakes up every second, and signals the thread. #include <pthread.h> #include <iostream> class Foo { public: Foo() { condition_ = false; pthread_mutex_init(&mutex_, NULL); pthread_cond_init(&cv_, NULL); pthread_create(&monitor_, NULL, startFunc, this); } void bar() { pthread_mutex_lock(&mutex_); std::cout << "BAR" << std::endl; condition_ = true; pthread_cond_signal(&cv_); pthread_mutex_unlock(&mutex_); } private: Foo(const Foo&) {}; Foo& operator=(const Foo&) { return *this; }; static void* startFunc(void* r) { Foo* f = static_cast<Foo*>(r); f->monitor(); return NULL; } void monitor() { pthread_mutex_lock(&mutex_); while (true) { while (!condition_) { pthread_cond_wait(&cv_, &mutex_); } // do something // and then setting condition_ to false std::cout << "FOO" << std::endl; condition_ = false; } pthread_mutex_unlock(&mutex_); } bool condition_; pthread_t monitor_; pthread_mutex_t mutex_; pthread_cond_t cv_; }; int main() { struct timespec tm = {1,0}; Foo f; while(true) { f.bar(); nanosleep(&tm, NULL); } } A: In case you run into this again, I ran into a very similar situation where I was running into a deadlock, where I was expecting cond_wait to release the mutex so that other threads could lock the mutex. My issue was that I had set the mutex as recursive (with settype->PTHREAD_MUTEX_RECURSIVE_NP) and was mistakenly locking the mutex twice before the cond_wait call. Since the cond_wait only unlocked it once, the mutex was still locked. The obvious fix was to only lock it once. Also, as a lesson learned, I won't be using the recursive mutex setting unless I really need to.
Q: Etale cohomology and l-adic Tate modules $\newcommand{\bb}{\mathbb}\DeclareMathOperator{\gal}{Gal}$ Before stating my question I should remark that I know almost nothing about etale cohomology - all that I know, I've gleaned from hearing off hand remarks and reading encyclopedia type articles. So I'm looking for an answer that will have some meaning to an etale cohomology naif. I welcome corrections to any evident misconceptions below. Let $E/\bb Q$ be an elliptic curve the rational numbers $\bb Q$: then to $E/\bb Q$, for each prime $\ell$, we can associate a representation $\gal(\bar{\bb Q}/\bb Q) \to GL(2n, \bb Z_\ell)$ coming from the $\ell$-adic Tate module $T_\ell(E/\bb Q)$ of $E/\bb Q$ (that is, the inverse limit of the system of $\ell^k$ torsion points on $E$ as $k\to \infty$). People say that the etale cohomology group $H^1(E/\bb Q, \bb Z_\ell)$ is dual to $T_\ell(E/\bb Q)$ (presumably as a $\bb Z_\ell$ module) and the action of $\gal(\bar{\bb Q}/\bb Q)$ on $H^1(E/\bb Q, \bb Z_\ell)$ is is the same as the action induced by the action of $\gal(\bar{\bb Q}/\bb Q)$ induced on $T_\ell(E/\bb Q)$. Concerning this coincidence, I could imagine two possible situations: (a) When one takes the definition of etale cohomology and carefully unpackages it, one sees that the coincidence described is tautological, present by definition. (b) The definition of etale cohomology (in the case of an elliptic curve variety) and the action of $\gal(\bar{\bb Q}/\bb Q)$ that it carries is conceptually different from that of the dual of the $\ell$-adic Tate module and the action of $\gal(\bar{\bb Q}/\bb Q)$ that it carries. The coincidence is a theorem of some substance. Is the situation closer to (a) or to (b)? Aside from the action $\gal(\bar{\bb Q}/\bb Q)$ on $T_\ell(E/\bb Q)$, are there other instances where one has a similarly "concrete" description of representation of etale cohomology groups of varieties over number fields and the actions of the absolute Galois group on them? Though I haven't seen this stated explicitly, I imagine that one has the analogy [$\gal(\bar{\bb Q}/\bb Q)$ acts on $T_\ell(E/\bb Q)$: $\gal(\bar{\bb Q}/\bb Q)$ acts on $H^1(E/\bb Q; \bb Z_\ell)$]::[$\gal(\bar{\bb Q}/\bb Q)$ acts on $T_\ell(A/K)$: $\gal(\bar{\bb Q}/\bb Q)$ acts on $H^1(A/K; \bb Z_\ell)$] where $A$ is an abelian variety of dimension $n$ and $K$ is a number field: in asking the last question I am looking for something more substantively different and/or more general than this. I've also inferred that if one has a projective curve $C/\bb Q$, then $H^1(C/\bb Q; \bb Z_\ell)$ is the same as $H^1(J/\bb Q; \bb Z_\ell)$ where $J/\bb Q$ is the Jacobian variety of $C$ and which, by my above inference I assume to be dual to $T_\ell(J/\bb Q)$, with the Galois actions passing through functorially. If this is the case, I'm looking for something more general or substantially different from this as well. The underlying question that I have is: where (in concrete terms, not using a reference to etale cohomology as a black box) do Galois representations come from aside from torsion points on abelian varieties? [Edit (12/09/12): A sharper, closely related question is as follows. Let $V/\bb Q$ be a (smooth) projective algebraic variety defined over $\bb Q$, and though it may not be necessary let's take $V/\bb Q$ to have good reduction at $p = 5$. Then $V/\bb Q$ is supposed to have an attached 5-adic Galois representation to it (via etale cohomology) and therefore has an attached (mod 5) Galois representation. If $V$ is an elliptic curve, this Galois representation has a number field $K/\bb Q$ attached to it given by adjoining to $\bb Q$ the coordinates of the 5-torsion points of $V$ under the group law, and one can in fact write down a polynomial over $\bb Q$ with splitting field $K$. The field $K/\bb Q$ is Galois and the representation $\gal(\bar{\bb Q}/\bb Q)\to GL(2, \bb F_5)$ comes from a representation $\gal(K/\bb Q) \to GL(2, \bb F_5)$. (I'm aware of the possibility that knowing $K$ does not suffice to recover the representation.) Now, remove the restriction that $V/\bb Q$ is an elliptic curve, so that $V/\bb Q$ is again an arbitrary smooth projective algebraic variety defined over $\bb Q$. Does the (mod 5) Galois representation attached to $V/\bb Q$ have an associated number field $K/\bb Q$ analogous to the (mod 5) Galois representation attached to an elliptic curve does? If so, where does this number field come from? If $V/\bb Q$ is specified by explicit polynomial equations is it possible to write down a polynomial with splitting field $K/\bb Q$ explicitly? If so, is a detailed computation of this type worked out anywhere? I'm posting a bounty for a good answer to the questions succeeding the "Edit" heading. A: Regarding the Dec 9 edit: Yes, but you probably won't like it. Take the etale cohomology of V_{Q-bar} with coefficients in Z/5Z. Then this is a finite abelian group, and Gal(Q-bar/Q) acts continuously on it. Therefore the subgroup of Gal(Q-bar/Q) acting trivially is open, and hence corresponds to a finite Galois extension K of Q. I don't know whether, given the defining equations of V, there exists an algorithm to find a polynomial whose splitting field is K. The only idea I'd have is to use fibration by curves to try to reduce the question to the etale cohomology of curves with coefficients in local systems, which can probably be calculated by using a Tate module-style approach on Jacobians. I think it's an interesting question, but I bet no one's ever looked at it. A: IMO, the scenario is closer to your (a). I'll sketch an explanation of the duality between $H^1(E,\mathbf{Z}_l)$ and the dual to the Tate module. We have $H^1(E,\mathbf{Z}_l)=\text{Hom}(\pi_1(E),\mathbf{Z}_l)$, where that $\pi_1$ means etale fundamental group with base point the origin $O$ of $E$. Thus the isomorphism we really want is between $\pi_1(E)\otimes\mathbf{Z}_l$ and $T_\ell(E)$. What is $\pi_1(E)$? In the topology world, we'd consider the universal cover $f\colon E'\rightarrow E$ and take $\pi_1(E)$ to be its group of deck transformations. Then $\pi_1(E)$ has an obvious action on $f^{-1}(O)$. If $E$ is the complex manifold $\mathbf{C}/L$ for a lattice $L$, this is just the natural isomorphism $\pi_1(E)\cong L$. But in the algebraic geometry world, there is no universal cover in the category of varieties, so the notion of universal cover is replaced with the projective system $E_i\to E$ of etale covers of $E$. Then $\pi_1(E)$ is the projective limit of the automorphism groups of $E_i$ over $E$. One nice thing about $E$ being an elliptic curve is that any etale cover $E'\rightarrow E$ must also be an elliptic curve (once you choose an origin on it, anyway); if $E\rightarrow E'$ is the dual map then the composition $E\rightarrow E'\rightarrow E$ is multiplication by an integer. So it's sufficient to only consider those covers of $E$ which are just multiplication by an integer. Since it's $\pi_1(E)\otimes\mathbf{Z}_l$ we're interested in, it's enough to consider the isogenies of $E$ given by multiplication by $l^n$. What are the deck transformations of the maps $l^n\colon E\rightarrow E$? Up to an automorphism of $E$, they're simply translations by $l^n$-division points. And now we see the relationship to the Tate module: A compatible system of deck transformations of these covers is the exact same thing as a compatible system of $l^n$-division points. Thus we get the desired isomorphism. Naturally, it's Galois compatible! In the end, we see that torsion points were tucked away in the construction of the etale cohomology groups, so it wasn't exactly a coincidence. Hope this helps. Re the edit: I believe your best bet is to work locally. First of all, you didn't mention which Galois representation you wanted exactly; let's say you want the representation on $H^i$ of your variety for a given $i$. Let's assume this space has dimension $d$. Step 1. For each prime $p$ at which your variety $V$ has good reduction, you can compute the local zeta function of $V/\mathbf{F}_p$ by counting points on $V(\mathbf{F}_{p^n})$ for $n\geq 0$. In this way you can compute the action of the $p^n$th power Frobenius on $H^i(V\otimes\overline{\mathbf{F}}_p,\mathbf{F}_5)$ for various primes $p$. Step 2. Do this enough so that you can gather up information on the statistics of how often the Frobenius at $p$ lands in each conjugacy class in the group $\text{GL}_d(\mathbf{F}_5)$. In this way you could guess the conjugacy class of the image of Galois inside $\text{GL}_d(\mathbf{F}_5)$. Step 3. Now your job is to find a table of number fields $F$ whose splitting field has Galois group equal to the group you found in the previous step. I found a table here: http://hobbes.la.asu.edu/NFDB/. You already know which primes ramify in $K$ -- these are at worst the primes of bad reduction of $V$ together with 5 -- and you can distinguish your $F$ from the other number fields by the splitting behavior your found in Step 1. Then $K$ is the splitting field of $F$. A caveat: Step 1 may well take you a very long time, because unless your variety has some special structure or symmetry to it, counting points on $V$ is Hard. Another caveat: Step 3 might be impossible if $d$ is large. If $d$ is 2 then perhaps you're ok, because there might be a degree 8 number field $F$ whose splitting field has Galois group $\text{GL}_2(\mathbf{F}_5)$. If $d$ is large you might be out of luck here. You are free not to accept this answer because of the above caveats but I really do think you've asked a hell of a tough question here! A: You might certainly say that Galois representations come from modular forms (or, more generally and more conjecturally, from automorphic forms on groups more general than GL_2.) You can say what it means for an ell-adic Galois representation to be associated to a modular form without reference to etale cohomology. But if you want to prove the existence of such a Galois representation -- for instance, by constructing it -- I don't see that you have much choice but to invoke etale cohomology. And it's not so clear that this any less "concrete" than, say, invoking the ell-adic Tate module of some unspecified abelian 6-fold or something. A: There's a conjecture of Fontaine and Mazur that says that every "reasonable" Galois representation occurs in the etale cohomology of some algebraic variety, so there's no way of avoiding it. Weil managed to prove the Weil conjectures for curves and abelian varieties using only (a variant of) the Tate modules, but that's about as far as you can go. The best thing is to understand etale cohomology so that it is no longer a black box. For the Fontaine Mazur conjecture, see Kisin's article, Notices AMS, 2007 (What is a Galois representation?).
Q: Why I do not need to put string escape character while passing property in React Component I was creating a custom component in React and the custom component accepts regex expression as props. Like this - <CustoInput label='Email Id' width={{width:'50%'}} regex='^[A-Z0-9]+@[A-Z]+\.[A-Z]{2,3}$' msg='* Improper format'/> Generally in javascript I would need to put an escape character and the expression should look like this if I pass this as a variable - '^[A-Z0-9]+@[A-Z]+\\.[A-Z]{2,3}$' But in react, when I pass props values like this, no escape character is required and it works fine. Why is that? A: Because \ is an escape character for JavaScript string literals (and thus needs to be escaped to specify a literal backslash); while it has no special significance whatsoever in HTML (and is thus treated as any regular character). Conversely, you'd likely need to escape &, for example (as &amp;), which does not need escaping in JavaScript.
Q: Is it possible to get observable before transformation via operator? Is it possible to? More verbose question I have something like this: const source = Rx.Observable.interval(500); const transformed = source.mergeMap(() => Rx.Observable.timer(100)); transformed observable is new observable and it is not connected to initial observable source (I can not access it through transformed, as I think). Is it possible to somehow get initial (before operator applying) observable after transforming with operator? My case Code: @AppendLoader() @Effect() getFriends$: Observable<Action> = this.actions$ .ofType(friendsActions.GET_FRIENDS) .switchMap(() => { return this.friendsService.getFriends() .map((data: any) => new friendsActions.GetFriendsSuccessAction(data)) .catch(() => of(new friendsActions.GetFriendsFailureAction())); }); And AppendLoader: function AppendLoader() { return function (target: any, propertyKey: string) { let observable: any = null; Object.defineProperty(target, propertyKey, { configurable: true, enumerable: true, get: () => { console.log('get'); return observable; }, set: (newObservable) => { console.log('set', newObservable); observable = newObservable; observable .subscribe((action: any) => { console.log(action); }); } }); }; } I have three observables there: * *this.actions$ (all actions) *created from this.action$ this.action$.ofType(friendsActions.GET_FRIENDS) (observables of friendsActions.GET_FRIENDS type) *third observable (2nd and switchMap applied to it) (observables of GetFriendsSuccessAction/GetFriendsFailureAction) I have access only to 3rd observable in the decorator since this observable is in the getFriends$ property. I want to do some actions in the AppendLoader decorator. I want to subscribe to 2nd observable in the list and when value is emitted I want to show load spinner (showLoader() for example). And I want to subscribe to third observable and when success/failure value is emitted I want to hide load spinner. A: I'm briefly checked RxJs5 source code seems it's not possible. But for your case, you can do the following: * *Create new observable 'forDecoratror$': second$ = this.actions$.ofType(friendsActions.GET_FRIENDS) getFriends$ = second$.switchMap(() => {...}); forDecoratror$ = Observable.Merge(second$.mapTo("2nd"), getFriends$) *In decorator call showloader() when "2nd" comes Just keep in mind everything is a stream :-)
Q: How can I tell when a Azure AD client secret expires? I have many applications registered in Azure AD Tenant and many of these are having client secret keys issued for 1 or 2 years. Is there a way to get an alert before the expiry as expired keys will cause an outage. A: We can also query the application to get the end-date of secret key. Here is a code sample using client credentials flow via the Azure Graph client for your reference. And please ensure that you have grant the app with Directory.Read.All permission to this API for using client credentials flow. var graphResourceId = "https://graph.windows.net"; var appId= ""; var appObjectId = ""; var secret = ""; var clientCredential = new ClientCredential(appId,secret); var tenantId = "xxx.onmicrosoft.com"; AuthenticationContext authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}"); var accessToken = authContext.AcquireTokenAsync(graphResourceId, clientCredential).Result.AccessToken; Uri servicePointUri = new Uri(graphResourceId); Uri serviceRoot = new Uri(servicePointUri, tenantId); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await Task.FromResult(accessToken)); var app = activeDirectoryClient.Applications.GetByObjectId(appObjectId).ExecuteAsync().Result; foreach (var passwordCredential in app.PasswordCredentials) { Console.WriteLine($"KeyID:{passwordCredential.KeyId}\r\nEndDate:{passwordCredential.EndDate}\r\n"); } A: At this time, there is no out of the box mechanism for alerting when client secrets are expiring. You can vote for this ask in the Azure AD Feedback Entry: Need email alert option when keys are about to expire Alternatively, you can build your own alerting mechanism by polling the Graph (currently the Azure AD Graph and eventually the Microsoft Graph once /servicePrincipals is in /v1.0/ in there). Query /servicePrincipals and filter on PasswordCredentials.EndDate and KeyCredentials.EndDate. You'll need to do your filtering client side since Graph doesn't support filtering on these values yet. 2021-12-07 Update Azure AD Graph has been deprecated. Query Microsoft Graph's /servicePrincipals and filter on the EndDate property of the PasswordCredentials object. A: You can use Logic App to automate the process. I found this useful: https://techcommunity.microsoft.com/t5/core-infrastructure-and-security/use-azure-logic-apps-to-notify-of-pending-aad-application-client/ba-p/3014603?fbclid=IwAR3ECopMRsitagEStKLC_yvAmFX4a1Ispn_a8ZFitapPquq9OZcZvQgKVOQ A: I created a "simple" one-line Azure Powershell command to show all principals that have or will expire in the next 30 days. Using that as a data feed for an email (like Send-MailMessage) or other alerting tool may be fairly straight forward. Get-AzureADApplication -All:$true | Select-Object AppId, displayName -ExpandProperty PasswordCredentials | Where-Object EndDate -lt (Get-Date).AddDays(30) | Sort-Object EndDate | Format-Table AppId, DisplayName, EndDate Note: If you have multiple secrets on a principal, each one shows up as its own line in the output. If you want to see all your principals and their secret expirations, just remove the Where-Object clause in the middle.
Q: Как добавить в manifest разрешение QUERY_ALL_PACKAGES В документации говориться добавить разрешение в манифест, чтобы получить все установленные приложения на устройстве начиная с Android 11 и выше, я добавил но подчеркивает красным и пишет A declaration should generally be used instead of QUERY_ALL_PACKAGES; see https://g.co/dev/packagevisibility for details Что я делаю не так ? <manifest> <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" /> </manifest> A: Android 11 и выше используют новую систему разрешений, которая называется "Declarations". Вместо разрешения QUERY_ALL_PACKAGES надо использовать объявление packageVisibility. <manifest> <queries> <package android:name="com.example.mypackage" android:visibility="permission" android:protectionLevel="normal" android:requestedPermission="android.permission.QUERY_ALL_PACKAGES" /> </queries> </manifest> На месте com.example.mypackage укажите имя вашего пакета. После этого, нужно запросить разрешение packageVisibility у пользователя при запуске приложения, с помощью метода requestPermissions(). Дополнительная информации и примеров можно посмотреть по этой ссылке https://developer.android.com/training/permissions/package-visibility A: По какой-то не понятной причине разработчики Android Studio, решили в место жёлтого предупреждения установить красный в итоге это водит в заблуждение кажется что эта ошибка а это просто предупреждение которое можно проигнорировать <manifest ...> <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:ignore="QueryAllPackagesPermission"/> ... </manifest>
Q: My Pygame (which work with tiled) has a big latency to update the map I have start to developed my first game and I use the Pygame library for this. For the map and the object I use Tiled. When I want to go to the up part of the map (which isn't display at first) I can see that there is a lot of latency with the sprite of the player. The two file that run the map: game.py from entities import * from map import MapManager from text import DialogBox class Game: def __init__(self, screen_dimensions: tuple = (1920, 1020)): # create game window screen_dimensions = list(screen_dimensions) if screen_dimensions[0] < 480: screen_dimensions[0] = 480 if screen_dimensions[1] < 255: screen_dimensions[1] = 255 screen_dimensions = tuple(screen_dimensions) self.screen = pygame.display.set_mode(screen_dimensions) pygame.display.set_caption("Project ReBorn") self.zoom = screen_dimensions[0] / 480 # generate player self.player = Player() self.map_manager = MapManager(self.screen, self.player, self.zoom) self.in_dialog = False self.dialog_box = DialogBox('dialog', screen_dimensions=screen_dimensions, width=int(200 * self.zoom), height=int(40 * self.zoom), zoom=self.zoom) def handle_input(self): pressed = pygame.key.get_pressed() dir_x = None dir_y = None go_up, go_down, go_left, go_right = False, False, False, False face = '' sprint = pressed[pygame.K_LSHIFT] handed = "right_handed" if handed == "right_handed": go_up = pygame.K_w go_down = pygame.K_s go_left = pygame.K_a go_right = pygame.K_d elif handed == "left_handed": go_up = pygame.K_i go_down = pygame.K_k go_left = pygame.K_j go_right = pygame.K_l if pressed[go_up] is not pressed[go_down]: if pressed[go_up]: dir_y, face = "up", "up" elif pressed[go_down]: dir_y, face = "down", "down" if pressed[go_left] is not pressed[go_right]: if pressed[go_left]: dir_x, face = "left", "left" elif pressed[go_right]: dir_x, face = "right", "right" self.player.move(face, sprint, dir_x, dir_y) def run(self): # game loop clock = pygame.time.Clock() running: bool = True while running: self.player.save_location() if not self.in_dialog: self.handle_input() self.map_manager.update() self.dialog_box.render(self.screen, self.zoom) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.in_dialog = self.map_manager.check_npc_collisions(self.dialog_box) clock.tick(60) pygame.quit() map.py from dataclasses import dataclass import pytmx import pyscroll from entities import * @dataclass class Portal: origin_map: str target_map: str point: str @dataclass class Map: name: str walls: list group: pyscroll.PyscrollGroup tmx_data: pytmx.TiledMap portals: list npcs: list class MapManager: def __init__(self, screen, player, zoom): self.maps = dict() self.screen = screen self.player = player self.zoom = zoom self.current_map = "Around_Home" self.register_all_map() self.tp_player("Spawn") self.tp_npcs() def check_npc_collisions(self, dialog_box): for sprite in self.get_group().sprites(): if sprite.feet.colliderect(self.player.rect) and type(sprite) is NPC: return dialog_box.execute(sprite.dialog) def check_collisions(self): # portals for portal in self.get_map().portals: if portal.origin_map == self.current_map: point = self.get_object(portal.point) rect = pygame.Rect(point.x, point.y, point.width, point.height) if self.player.feet.colliderect(rect): copy_portal = portal self.current_map = portal.target_map self.tp_player(copy_portal.point) # walls/entities for sprite in self.get_group().sprites(): if type(sprite) is NPC: if sprite.feet.colliderect(self.player.rect): sprite.speed = 0 else: sprite.speed = 1.75 if sprite.feet.collidelist(self.get_walls()) > -1: sprite.move_back() def tp_player(self, name: str): point = self.get_object(name) self.player.position[0] = point.x self.player.position[1] = point.y self.player.save_location() def register_all_map(self): #self.register_map( # "Map", # "ref" #) self.register_map( "Around_Home", "Beach", zoom=self.zoom, portals=[ Portal(origin_map="Around_Home", target_map="Home_down", point="Home_enter"), #Portal(origin_map="Around_Home", target_map="Atlantis", point="Atlantis_north_enter") ], npcs=[ NPC("Beach", "Honey", nb_points=2, dialog=['Hello~', 'How are you ?']) ], layer=3 ) self.register_map( "Home_down", "Beach", zoom=self.zoom, portals=[ Portal(origin_map="Home_down", target_map="Around_Home", point="Home_exit"), Portal(origin_map='Home_down', target_map="Home_up", point="Home_up") ], layer=4 ) self.register_map( "Home_up", "Beach", zoom=self.zoom, portals=[ Portal(origin_map="Home_up", target_map="Home_down", point="Home_down") ] ) def register_map(self, name: str, area: str, zoom: float = 4, portals: list = [], npcs: list = [], layer: int = 3): # load map tmx_data = pytmx.util_pygame.load_pygame(f"../assets/map/map_tmx/{area}/{name}.tmx") map_data = pyscroll.data.TiledMapData(tmx_data) map_layer = pyscroll.orthographic.BufferedRenderer( map_data, self.screen.get_size() ) map_layer.zoom = zoom # define list of walls walls: list = [] for obj in tmx_data.objects: if obj.name == "collision": walls.append(pygame.Rect(obj.x, obj.y, obj.width, obj.height)) # draw layers group group = pyscroll.PyscrollGroup(map_layer=map_layer, default_layer=2) # add entities group.add(self.player) for npc in npcs: group.add(npc) # add map to dict self.maps[name] = Map(name, walls, group, tmx_data, portals, npcs) def get_map(self): return self.maps[self.current_map] def get_group(self): return self.get_map().group def get_walls(self): return self.get_map().walls def get_object(self, name: str): return self.get_map().tmx_data.get_object_by_name(name) def tp_npcs(self): for _map in self.maps: map_data = self.maps[_map] npcs = map_data.npcs for npc in npcs: npc.load_points(map_data.tmx_data) npc.tp_spawn() def draw(self): self.get_group().draw(self.screen) self.get_group().center(self.player.rect.center) def update(self): self.get_group().update() self.check_collisions() for npc in self.get_map().npcs: npc.npc_move() self.draw() I have already tried to increase the fps and reduce the player speed but it wasn't successful.
Q: Measurability of $u:[0,T] \to X$ where $u$ is in Bochner space Let $f \in L^p(0,T;X)$ where $X$ is a separable Banach space. So $f$ is a Bochner function and hence Bochner measurable, meaning that there is a sequence of measurable countably-valued functions that converges to $f$ a.e in $t$. Let us denote $([0,T],S)$ as the measure space associated to the time interval. How do I know that $u:[0,T] \to X$ is $S$-measurable? I don't know what sigma-algebra $S$ should be though.
Q: .htaccess and page names I have a fairly massive web site for which I need to modify the names of the files shown in the URL. I am using Apache 2 with mod_rewrite enabled. I currently have the following configuration in my .htaccess file: RewriteEngine on RewriteBase / RewriteRule ^CakeList\.php$ TastyThingsList.php [T=application/x-httpd-php] Now, when I access the http://mysitename/CakeList.php I do indeed see the data for the TastyThingsList.php page. If a user types in http://mysitename/TastyThingsList.php, they do see the page, but rather than the address bar reading "TastyThingsList.php" I want it to read "CakeList.php". Is this possible to accomplish using mod_rewrite? Note that the CakeList.php page does not actually exist, I am more or less using it as an alias for the TastyThingsList.php page. I have been reading many of the online tutorials for mod_rewrite, but I cannot seem to find the answer. In short, whether the user types: http://mysitename/CakeList.php or http://mysitename/TastyThingsList.php, I would like the address in the browser to show http://mysitename/CakeList.php. Thank you WebCow A: Use the redirect flag for RewriteRule: RewriteRule ^TastyThingsList\.php$ CakeList.php [R=permanent,L] This works by returning a URL to the client browser, which actually has to re-request it, and that's how it displays in the address bar to the user. Ideally, this URL would never be given out if it is never to be used, and might even be configured to be inaccessible if typed in directly. Unless you have a really weird httpd configuration, you shouldn't need the T flag in the RewriteRule in the question.
Q: generate json format using php I want to generate .json file format in php file. for that i write following code. <?php $res=array(); $response = array(); $con=mysql_connect("localhost","root",""); if(!$con){ die("connection failed".mysql_error()); } $db=mysql_select_db("companies",$con); if(!$db){ die("connection failed".mysql_error()); } $result = mysql_query("SELECT * FROM companies"); while($row = mysql_fetch_array($result)) { $res[]=array('name'=> $row['name'],'id' => $row['company_id']+1); } mysql_close($con); $response['company'] = $res; echo (json_encode($response)); ?> it gives output like this: {"company":[{"name":"abc","id":2},{"name":"cde","id":3}]} but i want output like this: [{"company":{"name":"abc","id":1}},{"company":{"name":"cde","id":2}}] how should i change my php file? A: You need one more associative array: while($row = mysql_fetch_array($result)) { $res[] = array( 'company' => array('name'=> $row['name'],'id' => $row['company_id']+1) ); } And now all you have to send is json encoded $res.
Q: Как анимировать изменение высоты и ширины блока при помощи transition: width, height Для примера: $('.test').on('click', function() { $(this).text() === 'Длинный текст, длинный тексть длинный текст' ? $(this).text('Короткий текст') : $(this).text('Длинный текст, длинный тексть длинный текст'); }); .test { background-color: #1aafff; color: #ffffff; cursor: pointer; padding: 20px; position: absolute; user-select: none; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="test"> Нажимать сюда </div>
Q: Cakephp edit.ctp not populating input boxes despite existing in $this->data I'm struggling to find the answer to this. I have only been using CakePHP for a month and I've hit a problem. It's something I can fix by manually inserting the values but I expected my data to pre-populate. Here is what is happening: The Model is Product which hasMany 'Dynamicprice' I'm testing a product with the id of 7 (/products/edit/7). the first part of my edit function is: public function edit($id = null) { $this->Product->id = $id; if (!$this->Product->exists()) { throw new NotFoundException('Invalid Product'); } if ($this->request->is('get')){ $this->request->data = $this->Product->read(); } debug($this->request->data); //other stuff setting vars for drop-down lists } the debug($this->request->data); gives me the following: array( 'Product' => array( 'id' => '7', 'category_id' => '70', 'name' => 'Full Test', 'description' => 'This is to test all features', 'price' => '0.00', 'aesthetic' => true, 'image' => '', 'price_structure' => '2', 'suggest_for' => '', 'created' => '2012-06-28 12:49:06', 'modified' => '2012-06-28 12:49:06' ), 'Dynamicprice' => array( (int) 0 => array( 'id' => '15', 'product_id' => '7', 'drop' => '600', 'prices' => '6000:9.99, 12000:18.99 ' ), (int) 1 => array( 'id' => '16', 'product_id' => '7', 'drop' => '1200', 'prices' => '6000:19.99, 12000:28.99 ' ), (int) 2 => array( 'id' => '17', 'product_id' => '7', 'drop' => '2400', 'prices' => '6000:29.99, 12000:38.99 ' ) ) ) However, whilst everything in ['Product'] pre-populates the ['Dynamicprice'] array does not pre-populate the following: <?php echo $this->Form->input('Dynamicprices.0.id'); echo $this->Form->input('Dynamicprices.0.drop', array('label' => 'Drop 1 (mm). Enter "0" for "Any Drop"')); echo $this->Form->input('Dynamicprices.0.prices', array('label' => 'Prices 1', 'type' => 'textarea', 'rel' => 'dynamic')); ?><hr><?php echo $this->Form->input('Dynamicprices.1.id'); echo $this->Form->input('Dynamicprices.1.drop', array('label' => 'Drop 2 (mm).')); echo $this->Form->input('Dynamicprices.1.prices', array('label' => 'Prices 2', 'type' => 'textarea', 'rel' => 'dynamic')); ?><hr><?php echo $this->Form->input('Dynamicprices.1.id'); echo $this->Form->input('Dynamicprices.2.drop', array('label' => 'Drop 3 (mm).')); echo $this->Form->input('Dynamicprices.2.prices', array('label' => 'Prices 3', 'type' => 'textarea', 'rel' => 'dynamic')); ?> Am I right to expect them to populate automatically and if so what have I done wrong? I have created /Model/Dynamicprice.php with the following just to make sure: class Dynamicprice extends AppModel { public $name = 'Dynamicprice'; public $belongsTo = 'Product'; But as I expected it didn't change anything. A: This is the second time I've done this this week; ask a stupid question. Yes I was right to expect them to pre-populate. The problem is I got my naming conventions mixed up. "Dynamicprices.1.drop" shouldn't have the 's' at the end. Silly me!
Q: Word that means to "get something good but loses something else good in return" I was at the optical store getting a new pair of glasses and lens. Since I have a somewhat high prescription, when selecting the features for the lenses I asked the clerk whether there is an option where the lenses can be made thinner than the regular lenses with the same prescription and she said yes, those are the high-index lenses and they cost a little bit more. Then I asked her since these lenses are thinner thus better, will it lose quality in other areas such as clarity, impact resistance, etc.. I feel the way I asked this is somewhat wordy and I wonder if there's an expression that means what I'm trying to say. An expression that describes the fact of getting something that improves its quality, but will in turn cause the lost of quality in something else sort of like a balance, I guess similar to the word sacrifice? But using sacrifice doesn't seem that correct in this context. A: To sacrifice resistance for thinness is correct English. Sacrifice food for weight loss Sacrifice salary for job safety I sacrificed stability for lightness when I chose my sunglasses You gained thinner lenses at the cost of impact resistance Are there any disadvantages to these thinner lenses? A: In my humble opinion, the word "trade-off" is most appropriate here. Sacrifice suggests loss, not gain. You would have to use both "sacrifice" and "gain" to obtain the meaning that "trade-off" provides in one package. You could then ask: "What are the trade-offs?" rather than "What do I sacrifice for these gains?" A: This is similar to "negative externalities". These are basically things that are inherently included in any given action that are detrimental. Usually they are something that should not be ignored, but are at first. For example, lets say everybody really wants a big Wal-mart to be built in their city, because it is cheaper and faster. At first the idea is great, however, a negative externality may be that people who own small businesses may be pushed out, and then they are worse-off than they were before. I really love this word, it is the perfect thing to use in this type of situation. Also remember that there can be positive externalities as well! :) A: Sacrifice works. Maybe trade, exchange and forego too? To trade resistance for thinness? To exchange resistance for thinness. To forego resistance in favour of thinness.
Q: command prompt when i try install any dependence when I try to install any dependence in command prompt get this error message and tried to google but nothing any one to help me please please I need help someone to help me A: try installing locally. and add this path to your system variable: C:\Program Files\nodejs A: Reinstall the node. You have two ways to install Node.js on your computer. Option 1 – Setup by running the .msi installation file * *Its a typical Windows installation and automated. No need to add entries in environment varaiable Option 2 – Setup by extracting .zip file * *This method does not require admin access and can be used to install on nodejs on a system on which you dont have admin access such as you official laptop or desktop. *Removing nodejs is as simple as deleting the folder. You will have to add entries in environment variable if you want to execute node command from any location in windows command prompt. https://nodejs.org/en/download/ A: Based on the screenshot.your access is denied.Would suggest starting the terminal as an administrator before running the command.
Q: $[0,\omega_1]$ is not first countable. I was looking for examples of spaces that are not first countable. On wikipedia they give the example of $[0,\omega_1]$. I think I understand that $\omega_1$ is a limit point of $[0,\omega_1)$ since if $(\alpha,\beta)$ is an open containing $\omega_1$ it contains an ordinal smaller than $\omega_1$ and thus this ordinal is in $[0,\omega_1)$. Now why is there no sequence of $[0,\omega_1)$ converging to $\omega_1$. It is not entirely clear to me how to prove this. Also I don't really understand why this implies that $\omega_1$ doesn't have a countable basis. A: If there exist a sequence $x_n\in [0,\omega_1)$ converging to $\omega_1$, then $\omega_1$ would be countable, which is not. To see this you can use the model where ordinals are defined as $0=\emptyset$ $1=\{\emptyset\}=\{0\}$ $2=\{\emptyset,\{\emptyset\}\}=\{0,1\}$ ... $\alpha=\{\beta: \beta<\alpha\}$ the set of ordinals smaller than $\alpha$ Then, if $x_n<\omega_1$ and $x_n\to \omega_1$ then $\omega_1=\cup_n x_n$ is coutable union of countable set (because $\omega_1$ is the first uncountable) and so it would be countable.
Q: Django - Python - Multiple User Types With BooleanField In Custom User Model & OneToOne Relationships I am building a web application that will enable two different types of users to log in, with each user group having access to different pages on the site. As the information collected is similar for each type of user, I am planning to use only one custom user model with two boolean fields for each user type. The model will be defined as follows: class My_Users(AbstractBaseUser): ... is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_typeA = models.BooleanField(default=False) is_typeB = models.BooleanField(default=False) ... I intend to use OneToOne fields based on user IDs in other models, for both typeA and typeB users. So for example, there could be: class Model1(models.Model): id = models.OneToOneField(TypeA, on_delete=models.CASCADE, primary_key=True,) ... class Model2(models.Model): id = models.OneToOneField(TypeB, on_delete=models.CASCADE, primary_key=True,) ... My question are the following: 1/ This will imply that some ids created in my user model will be typeA and some others will be typeB. Will this be a problem for the one to one reliationship? i.e. will it be a problem that the ids are not incremental (type A could be id 1, 3, 4, 5, etc... whilst type B could have ids 2, 6, 7, etc...) for the one-to-one relationship. 2/ Is this the best set up in order to ensure that the app is scalable. If not, what would this be? Thanks. A: * *No, it's not a problem for the one-to-one relationship. As stated in this SO answer, a OneToOne is just a ForeignKey with unique=True and the reverse relation being singular. *Would be helpful to a little more detail on how you're dividing up the app based on the type of user, and what you mean by "scalable". Django's Groups and permissions is a more generalisable solution for "each user group having access to different pages on the site", and then you can check group membership when you're creating objects too.
Q: Display data in TextBox that clicked on DataGridView I have a problem displaying the data on text boxes when clicked on DataGridView because I show only fullname and student id column on DataGridView. con.Open(); SqlDataAdapter sda = new SqlDataAdapter("SELECT Student_ID as S_ID, Fname +' '+ Lname +' '+ Mname as NAME from student", con); DataTable dtbl = new DataTable(); sda.Fill(dtbl); dataGridView1.DataSource = dtbl; dataGridView1.Columns[0].Width = 40; dataGridView1.Columns[1].Width = 200; dataGridView1.RowHeadersVisible = false; con.Close(); A: So, If I understand you correctly. When you're clicking on a datagridview cell you wanna display the information in the textboxes? Start with this: * *Click on your datagridview. -> Select Events -> Double click on "CellContentClick" From here you can select the data from datagridview, and insert it into the textbox like this: private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { YourTextBoxName.Text = dataGridView1.CurrentRow.Cells["Lname"].Value.ToString(); }
Q: While creating SQL table and entering data into that table i am receiving error message INSERT INTO TourEvents(TourName,Month,Day,Year,Fee) VALUES ('East ','Jan',16,2016,200) Error at line 1: ORA-02291: integrity constraint (S9684921.SYS_C003209195) violated - parent key not found Can someone please explain to me what I might be doing wrong to get this error message To create table i have written below code CREATE TABLE TourEvents ( Month varchar(50) ,Day INT ,Year INT ,Fee INT ,TourName varchar(50) ,CONSTRAINT PK_TourEvents PRIMARY KEY (TourName,Month,Day,Year) ,FOREIGN KEY (TourName) REFERENCES TOURS(TourName) ); I am new to SQL and therefore struggling with constraints a bit. Any help will be greatly appreciated. A: Create the TOURS table and insert the record as East in TourName column then execute your insert script A: Your insert statement is trying to insert a value into column TourName which doesn't exist in the TOURS table. Value East should be in the TOURS table as it was used as foreign key. To better understand foreign key see this
Q: ESP-IDF deep_sleep and FreeRTOS tasks I work on project where I use FreeRTOS tasks and I would like to go into deep_sleep. Is there anything that I should do before going into the deep_sleep ? Or after wake up, RTOS scheduler works as nothing happen ? A: There's no easy way to mix freeRTOS and deep_sleep mode. During deep sleep the CPU is powered down and its context is lost, yet the RTC memory can be retained. As all SRAM's content is lost, there's no easy backup-restore we can do here to safely restore everything after coming out from deep sleep. But what you can do is to bring everything down to a safe state before entering deep-sleep, you can signal all your tasks to finish what they're doing and exit, and then take some advantage of ESP32's relatively low wake-up latency. It is a very unpleasant inconvenient for a Wi-Fi connected device, but more or less acceptable for BLE devices that will wake up and send a beacon once in a few seconds. You would also want to fine-tune the second stage bootloader's configuration by enabling the CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP option so waking-up from deep-sleep would be faster than booting from a cold reset.
Q: Unity3d rollback to previous state? I am looking for a way to make my Unity3D application able to "rollback" to a previous state so that the scene is exactly the same as it was N milliseconds. For example, say I have a player which has moved forward 5 units. There are objects in the foreground moving around, such as a ball rolling... now imagine that I would like to "undo" 3 moves: the player should appear where he was 3 steps ago and the rolling ball should also move backwards in time. What approach would I take here? I have thought to create "states", each timestamped with Time.realTimeSinceStartup, but that property is readonly. Alternatively, I thought that I could keep track of frame count, enable V-Synch so that render time is at 30ms, and rollback 30ms * n_frames, but unfortunately, the render time is not constant, even with V-Synch. Perhaps this is similar to saving the game and then restoring it? However, the save and restore need to be very fast, on the order of less than 10ms. What are my options here?
Q: How to refactor this validation method I have a lot of duplicated code below. I am thinking if there is a way to clean it up and remove the lots of duplicated code. I think i should create a method which to do the logging and throw the exception? But i am unable to get my mind around on how to do it for (Shape shape : Shapes) { if (shape.getShapeName().isEmpty()) { final String mesg = String.format("Empty Shape."); log.error(mesg); throw new Exception(mesg); } invalidChar = p.matcher(shape.getShapeName()).find(); if (invalidChar) { final String mesg = String.format("Invalid character(s) in Shape name %s", shape.getShapeName()); log.error(mesg); throw new Exception(mesg); } if (shape.getShapeDesc().isEmpty() || shape.getShapeDesc().trim().length() == 0) { final String mesg = String.format("Empty Shape description."); log.error(mesg); throw new Exception(mesg); } if (Character.isWhitespace(shape.getShapeDesc().charAt(0))) { final String mesg = String.format("Empty first character in Shape description %s", shape.getShapeDescription()); log.error(mesg); throw new Exception(mesg); } p = Pattern.compile("[^a-zA-Z0-9]+"); invalidChar = p.matcher(shape.getShapeDesc()).find(); if (invalidChar) { final String mesg = String.format("Invalid character in Shape description %s", shape.getShapeDesc()); log.error(mesg); throw new Exception(mesg); } } A: You can write a method which takes two parameters, a boolean and a string, and call the condition with the logging and the error throw in this method void checkError(boolean condition, String message) { if(condition) { log.error(message); throw new Exception(message); } } and then instead of your conditions you can use checkError(shape.getShapeName().isEmpty(), "Empty Shape."); A: In addition to @T.Garcin's answer, This if statement: shape.getShapeDesc().isEmpty() || shape.getShapeDesc().trim().length() == 0 Can be shortened to just the right condition, since it would be the same. But I'd suggest trimming the value in the Shape constructor then just calling isEmpty rather than having to remember to call trim everywhere. That means you also don't have to do this check if (Character.isWhitespace(shape.getShapeDesc().charAt(0))) { final String mesg = String.format("Empty first character in Shape description %s", shape.getShapeDescription()); log.error(mesg); throw new Exception(mesg); }
Q: How to access/manipulate a mutable array passed as parameter within a function in Swift 4.2x? I have the following code below: var rootTasks: [Task]? func loadRootTasks() { rootTasks == nil ? rootTasks = [Task]() : rootTasks?.removeAll() // removeAll() works here TasksManager.loadTasks(parentTaskIDString: "0", tasks: &rootTasks!) } static func loadTasks(parentTaskIDString: String, tasks: inout [Task]) { let urlString = Config.httpsProtocol + "://" + Config.server + Config.portString + "/" + TasksManager.getTasksEndpoint + "/" + parentTaskIDString let url = URL(string: urlString) var urlRequest = URLRequest(url: url!) urlRequest.setValue(AccountsManager.sharedInstance.securityAccessToken, forHTTPHeaderField: "Authorization") let defaultSession = URLSession(configuration: .default) let getTasksTask = defaultSession.dataTask(with: urlRequest, completionHandler: { (data, response, error) in guard (response as? HTTPURLResponse)?.statusCode == 200 else { print("GetTasks response status code != 200") return } guard error == nil else { print("GetTasks error") return } guard let jsonData = data else { print("GetTasks did not receive JSON data") return } do { // PROBLEM is here: // compiler flags "Escaping closures can only capture inout parameters explicitly by value" tasks.removeAll() // removeAll() does not work here // same error here tasks = try JSONDecoder().decode([Task].self, from: jsonData) NotificationCenter.default.post(name: .rootTasksRefreshed, object: nil, userInfo: nil) } catch { print("GetTasks JSON parsing exception") } }) getTasksTask.resume() } The problem is in the line "// PROBLEM ...". The compiler flags the "Escaping closures can only capture inout parameters explicitly by value" error. The function "loadTasks" is a static method, which is called by "loadRootTasks". It needs to pass a "tasks" array which is a member variable, and needs to be modified from within the static method after the asynchronous method dataTask() runs. How do I resolve the problems to be able to "tasks.removeAll()", etc? I have read other posts, but there are not for Swift 4.2. I need help specifically for Swift 4.2. Thanks! A: You cannot manipulate an inout parameter in asynchronous code. In this case, though, there's no need to do so. Don't pass rootTasks to your loadTasks method at all. First, make your loadTasks method an instance method instead of a static method. Now your loadTasks method can see rootTasks, directly. So it can just change it, directly! So, at that point, there's no need to say tasks.removeAll() // removeAll() does not work here Just say self.rootTasks.removeAll() And so on. (However, your asynchronous code should probably take care to touch self.rootTasks only on the main thread.) If you don't want to do that — that is, if you insist on leaving loadTasks as a static method — then you will have to do this in a normal way: loadTasks must take a completion handler which it will then call, as a way of passing the array back to the original caller asynchronously.
Q: Loop making program freeze I've been assigned to make a Black Jack game. I want it to be replayable by pressing a button when the round is over. I've set it up so that I have a method named initGame() that plays each player and the dealer a card each, and enables players[] buttons. It then runs runGame(), which is supposed to check if a player is done playing (over 21/pressed stay). When all players are deone it then sets running to false, enabling the resetbutton, which then runs initGame(). I kind of want it to loop around like this. However, the game freezes the second time runGame() is ran, when initNewGame() works fine. private void initNewGame(){ dealer.addCard(); for(int i = 0; i < numberofplayers; i++){ players[i].addCard(); //draws card, adds score and paints card to the board players[i].setStatus(false); //makes the buttons usable in the players[] class } runGame(); } /* * runGame() is meant to check if the players all have played out their hand, to then allow the dealer to play his. After that it sets running = false, allowing the player to either use the shuffle button or start a new game */ private void runGame(){ while(running){ int count=0; for(int i = 0; i<numberofplayers; i++){ //loops through all the player checking their status if(players[i].getStatus()) count++; } if(count==numberofplayers){ //checks if all players have >=21 or have pressed stay dealer.addCard(); //plays the dealers hand if(dealer.getPoints() >=19){ //stops when dealer have >=19 running = false; //stops entire loop } } } } class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e){ if(!running){ //won't allow players to reset while a round is playing if(e.getSource().equals(resetbutton)){ //Checks for rese/new game button System.out.println("reset"); dealer.setPoints(0); //sets dealers hand to 0 dealer.paintText(); //updates delaers painted score dealer.clearCards(); //clear the painted cards for(int i = 0; i < numberofplayers; i++){ players[i].setPoints(0); players[i].clearCards(); players[i].paintText(); } gui.repaint(); running = true; //allows the runGame() to start initNewGame(); //this one works the second time }else if(e.getSource().equals(shufflebutton)){ d1.shuffleDeck(); System.out.println(running); } } } } A: Your problem is due to your while loop blocking the GUI's event thread, freezing the GUI. But more importantly... Yours looks to be a Swing GUI (you don't tell us, so I'm guessing based on the there being an ActionListener). If so, you need to re-think your program flow and structure so that it conforms to event-driven programming principles. You should get rid of that while (running) loop, and instead give your class a field for the Player whose turn it is, and have the program change the value of that field after each player takes a turn. For a very simple example, here's a small GUI that shows one active player at a time. If the active player is clicked on, then the next player becomes active. There are no while loops involved but instead I change the state of the program when needed: import java.awt.Color; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.*; import javax.swing.event.SwingPropertyChangeSupport; @SuppressWarnings("serial") public class CardGameGui extends JPanel { public static final String[] PLAYER_NAMES = {"John", "Bill", "Frank", "Andy"}; private static final Color ACTIVE_BG = Color.pink; // a Map that allows us to associate a JLabel with a CardPlayer private Map<CardPlayer, JLabel> playerLabelMap = new HashMap<CardPlayer, JLabel>(); private CardPlayers cardPlayers = new CardPlayers(PLAYER_NAMES); public CardPlayer currentPlayer = cardPlayers.getCurrentPlayer(); public CardGameGui() { setLayout(new GridLayout(1, 0, 5, 0)); for (CardPlayer cardPlayer : cardPlayers) { JLabel playerLabel = createPlayerLabel(cardPlayer); playerLabelMap.put(cardPlayer, playerLabel); add(playerLabel); } playerLabelMap.get(currentPlayer).setBackground(ACTIVE_BG); cardPlayers.addPropertyChangeListener(new CardPlayersListener()); } private JLabel createPlayerLabel(CardPlayer player) { JLabel label = new JLabel(player.getName()); label.setOpaque(true); int ebGap = 15; label.setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap)); label.addMouseListener(new PlayerLabelListener()); return label; } public void activateCurrentLabel(CardPlayer currentPlayer) { for (CardPlayer cardPlayer : cardPlayers) { playerLabelMap.get(cardPlayer).setBackground(null); } playerLabelMap.get(currentPlayer).setBackground(ACTIVE_BG); } private class CardPlayersListener implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { if (CardPlayers.CARD_PLAYER.equals(evt.getPropertyName())) { currentPlayer = cardPlayers.getCurrentPlayer(); System.out.println(currentPlayer); activateCurrentLabel(currentPlayer); } } } private class PlayerLabelListener extends MouseAdapter { @Override public void mousePressed(MouseEvent mEvt) { JLabel playerLabel = (JLabel) mEvt.getSource(); JLabel currentPlayerLabel = playerLabelMap.get(currentPlayer); if (playerLabel == currentPlayerLabel) { cardPlayers.incrementPlayerIndex(); } } } private static void createAndShowGui() { CardGameGui mainPanel = new CardGameGui(); JFrame frame = new JFrame("CardGame"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } } class CardPlayers implements Iterable<CardPlayer> { public static final String CARD_PLAYER = "card player"; private List<CardPlayer> playerList = new ArrayList<>(); private int currentPlayerIndex = 0; private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport( this); public CardPlayers(String[] playerNames) { for (String playerName : playerNames) { playerList.add(new CardPlayer(playerName)); } } public CardPlayer getCurrentPlayer() { return playerList.get(currentPlayerIndex); } public void incrementPlayerIndex() { CardPlayer oldValue = getCurrentPlayer(); currentPlayerIndex++; currentPlayerIndex %= playerList.size(); CardPlayer newValue = getCurrentPlayer(); pcSupport.firePropertyChange(CARD_PLAYER, oldValue, newValue); } @Override public Iterator<CardPlayer> iterator() { return playerList.iterator(); } public void addPropertyChangeListener(PropertyChangeListener listener) { pcSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { pcSupport.removePropertyChangeListener(listener); } } class CardPlayer { private String name; public CardPlayer(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "CardPlayer: " + name; } } A: Problem is that you called initNewGame(); from within event handler code. You should use the same thread as in the first initNewGame call or create a new one.
Q: How to setup ContentType for Azure ServiceBus from Spring JMS I'm trying to use library azure-servicebus-jms-spring-boot-starter to send messages to topic. Everything works, however messages are being stored in subscriptions as application/xml type and I can't find the way how to setup this correctly to have them stored as application/json. I've tried to configure message converter to send ContentType as described here but that doesn't work either. @Bean public MessageConverter jacksonJmsMessageConverter() { final MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(){ @Override protected TextMessage mapToTextMessage(Object object, Session session, ObjectWriter objectWriter) throws JMSException, IOException { final TextMessage message = super.mapToTextMessage(object, session, objectWriter); message.setStringProperty("ContentType", "application/json"); return message; } }; converter.setTargetType(MessageType.TEXT); converter.setTypeIdPropertyName("_type"); converter.setObjectMapper(objectMapper); return converter; } A: There is no exposed means of setting the content-type on the messages sent from the Qpid JMS client. The client itself uses this field as part of the JMS mapping to AMQP to distinguish certain message types that it sends and to determine at receive time what certain messages should be presented as. It is technically possible to use reflection to reach in and so the value but the APIs you have to use from the JmsMessageFacade class are not public and could change with any release so choosing to do so comes with significant risk.
Q: Why does < instead of << in stream output still compile? Today I made a small typo in my program, and was wandering why I wasn't getting any output, although the program compiled fine. Basically it reduces to this: #include <iostream> int main() { std::cout < "test"; // no << but < } I have absolutely no idea what kind of implicit conversion is performed here so the program still compiles (both g++4.9.2 and even g++5). I just realized that clang++ rejects the code. Is there a conversion to void* being performed (cannot think of anything else)? I remember seeing something like this, but I thought it was addressed in g++5, but this doesn't seem to be the case. EDIT: I was not compiling with -std=c++11, so the code was valid in pre-C++11 (due to conversion to void* of ostream). When compiling with -std=c++11 g++5 rejects the code, g++4.9 still accepts it. A: Yes, the compiler is converting cout to a void*. If you use the -S switch to get the code's disassembly, you'll see something like this: mov edi, OFFSET FLAT:std::cout+8 call std::basic_ios<char, std::char_traits<char> >::operator void*() const cmp rax, OFFSET FLAT:.LC0 setb al test al, al Which makes it clear that operator void* is the culprit. Contrary to what Bill Lynch said, I'm able to reproduce it with —std=c++11 on Compiler Explorer. However, it does appear to be an implementation defect, since C++11 should have replaced operator void* with operator bool on basic_ios. A: This is only valid before C++11. You're basically doing: ((void *) std::cout) < ((char *) "test")
Q: Sudoku doesn't work, probable sys.path error As the title suggests, the default sudoku game doesn't work anymore. I used to use it quite frequently however, after a break when i tried to run it again, it doesn't open. If I search for Sudoku on the dash and click on it, the command is registered, but nothing happens. I'm on 12.04. How can this be fixed? Edit Upon trying to run it in the terminal as gnome-sudoku or gnome-sudoku -v, i get the following error- Traceback (most recent call last): File "/usr/games/gnome-sudoku", line 21, in <module> from gnome_sudoku.gnome_sudoku import start_game ImportError: No module named gnome_sudoku.gnome_sudoku Edit #2 Paste bin links for - 1) locate gnome_sudoku http://paste.ubuntu.com/5864729/ 2)python -c "import sys; print sys.path" http://paste.ubuntu.com/5864604/ 3)grep -n "" /usr/games/gnome-sudoku http://paste.ubuntu.com/5864607/ Edit #3 As lgarzo suggested, /usr/lib/python2.7/dist-packages may be missing from my sys.path, and the output for python -c 'import os; print os.environ["PYTHONPATH"]' is Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/local/lib/python2.7/UserDict.py", line 23, in __getitem__ raise KeyError(key) KeyError: 'PYTHONPATH' And upon running PYTHONPATH=/usr/lib/python2.7/dist-packages gnome-sudoku in the terminal I get - ImportError: /usr/lib/python2.7/dist-packages/gi/_gi.so: undefined symbol: PyUnicodeUCS4_AsUTF8String My python version is 2.7.4, how can one proceed? A: Try to run it from command line/terminal gnome-sudoku or verbose gnome-sudoku -v let us know if the cmd line show any errors.
Q: CSS animation rotation issue I have an animated infinite auto-scrolling carrousel. The tiles of the carrousel ares tilted to transform:rotateX(45deg) but they revert to 0deg because the animation for auto-scrolling has its own transform:. Since the animation is a loop I want the tiles to stay at a fixed rotation so there is no stutter through each loop. .slider { background: none; height: 600px; margin: auto; overflow:hidden; position: relative; display: flex; align-items: center; width: 100%; } .slider::before, .slider::after { content: ""; height: 100px; position: absolute; width: 200px; z-index: 2; } .slide-track { animation: scroll 5s linear infinite; display: flex; width: calc(300px * 14); perspective: 9000px; } @keyframes scroll { 0% { transform: translateX(0); } 100% { transform: translateX(calc(-300px * 7))} } .slide { width: 300px; height: 500px; background-color: #17141d; margin-left: 30px; transform: rotateX(45deg) scale(0.8); border-radius: 10px; box-shadow: -1rem 0 3rem #000; display: flex; justify-content: center; overflow: hidden; flex-direction: column; align-items: center; } <div class="slider"> <div class="slide-track"> <div class="slide" ></div> <div class="slide"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide"></div> </div> </div> A: The transform property accepts multiple values simultaneously. In your case, change the keyframes declaration to this: @keyframes scroll { 0% { transform: translateX(0) rotateX(45deg) scale(0.8); } 100% { transform: translateX(calc(-300px * 7)) rotateX(45deg) scale(0.8); } }
Q: How can you draw 32bppargb images with the Win32 AlphaBlend function? I've been fussing with this for the better part of the night, so maybe one of you can give me a hand. I have found GDI+ DrawImage in C# to be far too slow for what I'm trying to render, and from the looks of forums, it's the same for other people as well. I decided I would try using AlphaBlend or BitBlt from the Win32 API to get better performance. Anyway, I've gotten my images to display just fine except for one small detail—no matter what image format I use, I can't get the white background to disappear from my (transparent) graphics. I've tried BMP and PNG formats so far, and verified that they get loaded as 32bppargb images in C#. Here's the call I'm making: // Draw the tile to the screen. Win32GraphicsInterop.AlphaBlend(graphicsCanvas, destination.X, destination.Y, this.TileSize, this.TileSize, this.imageGraphicsPointer, tile.UpperLeftCorner.X, tile.UpperLeftCorner.Y, this.TileSize, this.TileSize, new Win32GraphicsInterop.BLENDFUNCTION(Win32GraphicsInterop.AC_SRC_OVER, 0, Convert.ToByte(opacity * 255), Win32GraphicsInterop.AC_SRC_ALPHA)); For the record, AC_SRC_OVER is 0x00 and AC_SRC_ALPHA is 0x01 which is consistent with what MSDN says they ought to be. Do any of you guys have a good solution to this problem or know a better (but still fast) way I can do this? A: Graphics.DrawImage() speed is critically dependent on the pixel format. Format32bppPArgb is 10 times faster than any other one on any recent machine I've tried. Also make sure you the image doesn't get resized, be sure to use a DrawImage() overload that sets the destination size equal to the bitmap size. Very important if the video adapter's DPI setting doesn't match the resolution of the bitmap. A: Have you tried an opacity of just 255 rather than a calculated one? This blog post describes what you're trying to do:- http://blogs.msdn.com/andreww/archive/2007/10/10/preserving-the-alpha-channel-when-converting-images.aspx Critical thing is that he carries out a conversion of the image to make the alpha channel compatible.. A: Ok. From a pure Win32 perspective: In order for AlphaBlend to actually alpha blend... it needs the source device context to contain a selected HBITMAP representing an image with 32bpp bitmap with a pre-multiplied alpha channel. To get a device bitmap with 32bpp you can either call one of the many functions that will create a screen compatible device bitmap and hope like hell the user has selected 32bpp as the desktop bitdepth. OR, ensure that the source bitmap is a DIBSection. Well, the library or framework that is creating it from the loaded image for you. So, C# is loading your images with 32bpp argb, BUT, how are you converting that C# representation of the bitmap into a HBITMAP? You need to ensure that a DIB Section is being created, not a DDB (or device dependent bitmap), and that the DIB Section is 32bpp.