INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Selecting last record in plsql Hello I need to select last record in a table(bill_account_billcycle). After finding it I need to take bill_date column date from last record and need implement inside my cursors' query. I read rownum max etc but couldnt succeed to implement. I am open to advices. I am going to add a screenshoot of one bill_account record to there and my scripts. thank you from now. ![]( CURSOR c1 IS SELECT DISTINCT intl_prod_id FROM apld_bill_rt abr, acct_bill ab, bill_acct_billcycle bab WHERE abr.CHRG_TP = 'INSTALLMENT' AND abr.TAX_CATG_ID = 'NOTAX' AND abr.acct_bill_id = ab.acct_bill_id AND ab.bill_date = bab.bill_date IN (select );-- I should do something here.
To me, it looks like CURSOR c1 IS SELECT DISTINCT intl_prod_id FROM apld_bill_rt abr JOIN acct_bill ab ON abr.acct_bill_id = ab.acct_bill_id WHERE ab.bill_date = (SELECT MAX (bab.bill_date) FROM bill_account_billcycle bab) -- AND abr.chrg_tp = 'INSTALLMENT' AND abr.tax_catg_id = 'NOTAX' i.e. remove `bill_account_billcycle` table from cursor's `FROM` clause; select the _last_ date using a subquery.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, oracle, plsql" }
Struggling with input validation/check constraint I'm trying to create a table with an email address column and want to make sure that only addresses in the correct format (contains "@") are allowed. I know how to use the `LIKE` operator in queries but not how to put a value constraint on a column.
You can add the check constraint like this For your basic example: alter table t add contraint chk_email (check (email like '%@%') ); Of course, that is really only a betting. Perhaps something more like this: alter table t add contraint chk_email (check (email like '%_@[^.]%' and -- one @ and something before and after email not like '%@%@%' and -- not more than one @ email not like '%[^-.a-zA-Z0-9_]%' -- valid characters) ); This still will allow invalid emails, but it is at least closer.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "sql, tsql, constraints" }
MYSQL Update Query syntax error 28-10-2016a UPDATE DFEntryValues SET DFEntryValues.DFFieldvalue = NOW() FROM DFEntryValues JOIN DFEntries ON DFEntryValues.DFEntryID = DFEntries.DFEntryID JOIN DynamicFormStructures ON DFEntries.DynamicFormStructureID = DynamicFormStructures.DynamicFormStructureID JOIN Projects ON DynamicFormStructures.ProjectID = Projects.ProjectId JOIN Clients ON Projects.ClientID = Clients.ClientID JOIN DFFieldDefinition ON DFEntryValues.DFFieldDefinitionID = DFFieldDefinition.DFFieldDefinitionID WHERE Clients.ClientID = '26' AND DFFieldDefinition.label = 'Geboortedatum'; I get the following error: Error Code: 1064 > You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE Clients.ClientID = '26' AND DFFieldDefinition.label = 'Geboortedatum' SET' at line 12 Can someone point me out what's wrong with this query? Kind regards!!
It seems you are not using correct format. Hope this helps. UPDATE DFEntryValues JOIN DFEntries ON DFEntryValues.DFEntryID = DFEntries.DFEntryID JOIN DynamicFormStructures ON DFEntries.DynamicFormStructureID = DynamicFormStructures.DynamicFormStructureID JOIN Projects ON DynamicFormStructures.ProjectID = Projects.ProjectId JOIN Clients ON Projects.ClientID = Clients.ClientID JOIN DFFieldDefinition ON DFEntryValues.DFFieldDefinitionID = DFFieldDefinition.DFFieldDefinitionID SET DFEntryValues.DFFieldvalue = NOW() WHERE Clients.ClientID = '26' AND DFFieldDefinition.label = 'Geboortedatum';
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql" }
Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined I have this function in my program that converts integers to strings: QString Stats_Manager::convertInt(int num) { stringstream ss; ss << num; return ss.str(); } But when ever i run this i get the error: aggregate 'std::stringstream ss' has incomplete type and cannot be defined Im not really sure what that means. But if you know how to fix it or need any more code please just comment. Thanks.
You probably have a forward declaration of the class, but haven't included the header: #include <sstream> //... QString Stats_Manager::convertInt(int num) { std::stringstream ss; // <-- also note namespace qualification ss << num; return ss.str(); }
stackexchange-stackoverflow
{ "answer_score": 175, "question_score": 110, "tags": "c++, string, qt, stringstream" }
SQL distinct field combination disregard the position Hi I have a SQL question: Table: Flight Origin Destination -------------------- Boston LA LA Bostion Newyork LA DC Newyork How could I select the distinct combination of the fight path if I do not care origin or destination: (Boston to LA) = (LA to Boston)
You can use `row_number` to do this. Get the partition by least of origin and destination, greatest of origin and destination so a combination like (a,b),(b,a) is treated the same. Then get the first row per group. select origin,destination from ( select origin,destination ,row_number() over(partition by case when origin<destination then origin else destination end, case when origin>destination then origin else destination end order by origin) as rnum from flight ) t where rnum=1
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "sql, sql server" }
QT GraphicScene - Text label collission I want to stop labels colliding within my Scene and as a result used this code to check for a collision:- QGraphicsTextItem *textLabel = new QGraphicsTextItem; .... addItem(textLabel); //check for collision QList<QGraphicsItem*> items = this->items(textLabel>boundingRect(),Qt::IntersectsItemBoundingRect); I never get any items in the list, yet on screen I can see the collisions. Am I reading the documentation incorrectly?
You're checking if any items are colliding with the label's bounding rect which is in the label's local coordinates. What you should be doing is checking relative to scene coordinates. However, note that QGraphicsItem has this function: - QList<QGraphicsItem *> QGraphicsItem::collidingItems(Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const Which, as the documentation describes: - > Returns a list of all items that collide with this item. The way collisions are detected is determined by applying mode to items that are compared to this item, i.e., each item's shape or bounding rectangle is checked against this item's shape. The default value for mode is Qt::IntersectsItemShape. So you'd be better calling: - QList<QGraphicsItem*> items = this->collidingItems();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "qt, collision, qgraphicsscene" }
Do strange parts apply retroactively? For example, let's say I have a Strange Scattergun with no parts attached and no kills. I kill 5 medics, then apply a 'Medics Killed' part to the Strange Scattergun. Then, I kill 5 more medics. What stat will be displayed? 5 medic kills, or 10 medic kills? Or another way of phrasing it - will strange parts reflect statistics you accrued before applying the part? Or does it only start counting those statistics after it's been applied?
The answer is a simple **NO**. Strange parts only begin to count the statistics after they are applied. Previous stats are not accounted for. > When applied, it will not count any previous stats. Reference: TF2 Wiki
stackexchange-gaming
{ "answer_score": 7, "question_score": 4, "tags": "team fortress 2" }
Setting a Model before saving using devise I am using devise for my User models in a RoR project. My User model belongs to a Plan (basic, hobby, professional, etc) I have a RegistrationController to control the registration of a new user. Like this: class RegistrationsController < Devise::RegistrationsController When a new user is created (after checking duplicity, password rules, etc) I want to add to each new user of the app the basic plan (because of businnes rules related to credit card, etc...) So basic, I want that, for each User created something like: #forget about this hard coding on Plan @user.plan = Plan.find(1) I dont know witch method I can add this part of my code. Because this is made on devise. Someone can help me?
Your devise model is backed by ActiveRecord (most likely), and so you have access to all of the ActiveRecord lifecycle hooks, such as before_save. Open your user model and put in: class User < ActiveRecord::Base #... devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable #... before_save :assign_plan def assign_plan self.plan = Plan.find_by_name('basic').first end #... end
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails, devise" }
privatemsg and services fully integration Does there exist any module even sandbox or starting point module (not ublished on drupal.org) to help achieve privatemsg crud operations over services module.
There exist a sandbox project pm services clone comand git clone --branch 7.x-1.x privatemsg_services cd privatemsg_services also pm services(profile2) but it needs profile2 to be enabled beore
stackexchange-drupal
{ "answer_score": 2, "question_score": 1, "tags": "services, privatemsg" }
Is it possible to Rename a work Item type in Azure DevOps? Is it possible and if so how do I rename a work item type in Azure DevOps (VSTS)? Essentially I just want to change the name "Bug" to "Defect". Any thoughts greatly appreciated.
You can't change the name of "Bug" to another name because it's system work item type. If you want to use "Defect" instead of "Bug" you can create a custom process template: ![enter image description here]( Add new work item type with name "Defect" (define all the fields like in Bug): ![enter image description here]( ![enter image description here]( Disable the "Bug": ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "azure devops" }
Tableau Desktop delete calculated fields Hi I was in the process of creating a calculated filed in my tableau desktop 2018.2 and I figured later that I no longer needed it, but i can't seem to delete it. Any solutions? I have posted a picture of my current calculated fields. ![enter image description here](
Instead of going to the Analysis menu, right click on the field itself in the Dimension or Measures section and select Delete. ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "tableau api" }
SQL Server Database Diagram I am using SSMS v18, I need to create an ER diagram from my database. As Microsoft removed diagram from new version of SSMS (v18) so now How can I get a diagram for my database??
Database diagrams have been re-added as of 18.1 in SSMS.
stackexchange-dba
{ "answer_score": 2, "question_score": 1, "tags": "sql server, database design, ssms, database diagrams" }
How can I make this layout on Android? I am using ViewPager to swipeing images in layout. But I want to that this is looking differently. I would like to: On the right side of the screen the next image is displaying a little, and the left side of the screen the previous image is displaying. How can I make it? Here it is a picture to show what I am imagining: < And how can I use ViewPager in subpart of the screen?
Please follow this link to implement view pager. And to show view pager in subpart you can set its width and height like this <android.support.v4.view.ViewPager android:id="@+id/vpPager" android:layout_width="match_parent" android:layout_height="300dp"> </android.support.v4.view.ViewPager>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -4, "tags": "android, layout, android viewpager" }
Line number "off" case .tex file on Visual Studio Code Is it possible turn off line number automatically when editing a .tex file?
Use Language-specific editor settings Edit the right (global/workspace) `settings.json` "[latex]": { "editor.lineNumbers": "off" }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "visual studio code, latex" }
How to customize namespace prefixes on Jersey(JAX-WS) when serializing my resources on Jersey, I want to use namespaces in some cases. Is there any way to customize the namespace prefixes on jersey? Default: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <order xmlns:ns2=" <price>123</price> <ns2:link rel="duh" href="/abc/123"/> <ns2:link rel="abc" href="/def/234"/> </order> I want something like: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <order xmlns:atom=" <price>123</price> <atom:link rel="duh" href="/abc/123"/> <atom:link rel="abc" href="/def/234"/> </order> Thanks, Lucas
If you use the MOXy JAXB implementation you can control your prefixes using the @XmlSchema package level annotation: @javax.xml.bind.annotation.XmlSchema( xmlns = { @javax.xml.bind.annotation.XmlNs(prefix = "atom", namespaceURI = " }) package org.example.domain; To use MOXy JAXB you need to have a file named jaxb.properties in with your model classes with the following entry: javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory For an example of using MOXy with Jersey see: * <
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "jaxb, jersey, jax rs" }
Zotero: referencing multi-word organisations like "World Bank" so that it's not, "Bank, World" I'm using Zotero to manage references, and I've manually inputed a reference to: World Bank. 2019. "World Development Indicators." URL: So under author, I typed: Author: World Bank [all in the `last name` field]. When I compile my bibliography, this means that I'm getting the reference as: Bank. 2019. “World Development Indicators.” Is there a way that I can enter a multi-word organisation as an author, and still get my desired output of: World Bank. 2019. "World Development Indicators." URL:
Found the answer: < There's a tiny box to the right of the author names, that if you click on, you can change the setting to a full name.
stackexchange-academia
{ "answer_score": 1, "question_score": 2, "tags": "citations, reference managers" }
How are IP address compared to the default 0.0.0.0/0 or ::/0 on binary level? Let's say I have an ipv4 destination address - `63.168.52.12` In binary format the address: `00111111.10101000.00110100.00001100` The default route in binary is `00000000.00000000.00000000.00000000` I am trying to understand how the default route matches all ip addresses. What does it mean for subnet mask to be zero? The first two bits match and the difference is at third bit. Is the IP checked bit by bit against the default route ip and looks for match? I read in another question that all IPv4 networks are subnets of the 0.0.0.0/0 network. I don't quite understand that statement.
The relevant part of the default route is the `/0` prefix length, not really the `0.0.0.0` address part. Generally, `/0` means "match at least the first zero bits of an address", making it match always. Technically, the `/0` length is expanded to the subnet mask `0.0.0.0` (or for comparison `/16` to `255.255.0.0`, `/17` to `255.255.128.0` etc.). That subnet mask is used in a bitwise `AND` operation ( _masking_ ) with the address to be matched. Since all bits become zero the result is always `0.0.0.0`. In operation, the routing table (FIB) entries are queried in the order of longest to shortest prefix: if (destinationaddress AND entry.mask) == entry.prefix then use entry.gateway Since `/0` is the shortest possible prefix it's always checked last and matches any address.
stackexchange-networkengineering
{ "answer_score": 3, "question_score": 1, "tags": "ip address" }
Do all reductive group schemes over semilocal rings admit finite-dimensional free faithful representations? The definition of a reductive group scheme is as in SGA III. Frankly, I only know that they exist for the adjoint group (the adjoint representation). In SGA III, I could only find a result for general groups over a regular ring of dimension $\leq 2.$ But since reductive groups are especially nice, maybe they do have such a representation? If not all reductive groups do, which of them do?
In Corollary 3.2 of the paper R. W. Thomason, Equivariant resolution, linearization, and Hilbert’s fourteenth problem over arbitrary base schemes, Adv. Math. 65 (1987), 16–34, this was proved for semisimple group schemes or, more generally, for reductive group schemes which are either split reductive, or semisimple, or with isotrivial radical and coradical, or over a normal base S.
stackexchange-mathoverflow_net_7z
{ "answer_score": 6, "question_score": 3, "tags": "rt.representation theory, algebraic groups, group schemes" }
Off-canvas navigation using only CSS I am trying to set up an off canvas navigation using only CSS. Basically I want the navigation to be 20% width and have it behind the main content and then when you click the menu icon, the header and body content will slide 20% off the right hand side of the screen and the navigation will be revealed. I've almost got it working based off a similar implementation(although they were doing it with width and not positioning) but I am struggling with the last little part. Here is my pen Any ideas? Thanks!
Just add `background: #fff;` to `.content` style definition. It will do the trick.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, css, navigation" }
how to get the closest number to zero in a loop I am trying to make a program that print the closest number to zero without using arrays I tried to print the minimum number as it will be the closest number to zero but this doesnot work when one of the numbers is negative public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int t = 0; int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { t = in.nextInt(); if (t < min) { min = t; } } System.out.println(min); }
If you want to find the number closest to zero, then you should be checking for the smallest absolute value of the input: int min = Integer.MAX_VALUE; for (int i=0; i < n; i++) { t = in.nextInt(); if (Math.abs(t) < Math.abs(min)) { min = t; } } Note carefully that we need to use the absolute value on both sides of the inequality.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, loops" }
calculate count of char use in string I'm trying to make this program work and I can't, The script i want must should calculate count of char use in string example : string=good result=g1o2d1 is there any way to write script that calculate exactly count of string like my example or not ? #!/bin/bash string=ssstttrrrriiiinnnnngg z=$( for((i=0;i<${#string};i++)) do; echo ${string:i:1}; done | uniq -c ) echo $z * * * my result : s 3 t 3 r 4 i 4 n 5 g 2 but for analysis some document i want script to calculate char some like firstchar1=$( bash script ) ...... i need that value for use another script please advise me regards
$ echo "abaaacdefg" | grep -o . a b a a a c d e f g $ echo "abaaacdefg" | grep -o .| sort a a a a b c d e f g $ echo "abaaacdefg" | grep -o .| sort | uniq -c 4 a 1 b 1 c 1 d 1 e 1 f 1 g $ echo "abaaacdefg" | grep -o .| sort | uniq -c | awk '{printf $2$1}' a4b1c1d1e1f1g1 See Bash: Split string into character array and counting duplicates in a sorted sequence using command line tools
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "string, bash" }
IF, ELSE IF, ELSE ou IF IF IF. Quando usar, qual a diferença? É uma questão bem básica, porém que me intriga bastante. Vejam o código abaixo: var bola = "redonda"; if(bola == "comestivel") return comer(); if(bola == "liquida") return beber(); if(bola == "redonda") chutar(); Agora vejam o mesmo com `if`, `else if` e `else` var bola = "redonda"; if(bola == "comestivel") return comer(); else if(bola == "liquida") return beber(); else chutar(); Ou seja, o mesmo fim pode ser obtido de ambas as maneiras. O `else if` e `else` não teriam apenas efeito semântico?
No seu exemplo, não faz mesmo diferença, por dois motivos: 1. Não existem duas condições que possam ser atendidas ao mesmo tempo. 2. Você sempre retorna quando entra em um dos `if`, e os seguintes não executam Agora considere o seguinte exemplo: var numero = 100; if(numero <= 100) { console.log("menor ou igual a 100"); } else if(numero < 1000) { console.log("menor que 1000"); } O `else` não será executado, pois já entrou no `if` ( _else_ quer dizer "senão"). Blocos de `else` e `else if` só executam se nenhuma das condições anteriores tiver sido atendida. Contraste com isto: var numero = 100; if(numero <= 100) { console.log("menor ou igual a 100"); } if(numero < 1000) { console.log("menor que 1000"); } Aqui ambos são executados, já que são duas condições independentes e o número `100` atende a ambas.
stackexchange-pt_stackoverflow
{ "answer_score": 39, "question_score": 39, "tags": "javascript, if, else, condição" }
Web Request Listener I would like to write a plugin that calculates a cryptographic hash of every file rendered in the browser (images, html, css, etc), without causing a second get request for the various files. Ideally I could listen for each resource being loaded and get a copy of the bytestream that comes back. Does anyone know if such a hook exists / what it would be called? Thanks!
Not at the moment. There is a feature request to allow (at least) read access to response body in `chrome.webRequest.onCompleted`, but it's not currently implemented.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "google chrome, google chrome extension" }
check virtualenv activation in makefile I am working on an app which has frontend (angularjs) and backend(python, flask framework). I am creating a `Makefile` for this app. To install backend dependencies using `requirements.txt` file, I want to check if `virtualenv` has been activated or not. If `virtualenv` is activated then only installs dependencies using `requirements.txt` file otherwise not. dummy: if virtualenv_activated: install_dependencies I checked this link: running inside virtualenv but didn't understand much about writing this in Makefile. Any useful help will be appreciated!
Finally I found out the way to do this, we can write it as: ifeq ($(VIRTUAL_ENV), ) @echo "virtual env is not activated" else @echo "virtual env is activated" endif So, this way we can check for `virtual_env` activation. Thanks!
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "makefile, devops" }
Can NS records contain IPV6 addresses? I have some local domains, and I want them to be accessible over ipv6 only. I'm using unbound. local-zone: "example.com" redirect local-data: "example.com. 2562000 IN NS 2607:XXXX:XXXX:XXX::XXX" local-zone: "test.example.com" redirect local-data: "test.example.com. 2562000 IN NS 2607:XXXX:XXXX:XXX::XXX" local-data: "test.example.com. 2562000 IN AAAA 2607:XXXX:XXXX:XXXX::XXX" But I can't find for sure, if you are allowed to have IPV6 addresses as NS records, as pretty much every one I find in the internet uses domains...
`NS` records can only ever have names as their value. No IPv4 addresses, no IPv6 addresses. Ie, you need a name with address records (`A` and/or `AAAA`) that you can refer to in the `NS` record.
stackexchange-serverfault
{ "answer_score": 5, "question_score": 0, "tags": "domain name system" }
select id number from visible element Suppose I have like this: <div id="a1">test</div> <div id="a2">thest</div> the 'id's starting with `a` are a lot and css for one `a` is visible and others are hidden and now I want to get the number for visible id like this var idz = $('[id^=a]:visible').attr('id'); var idv = parseInt(idz, 10); But seems wrong. How can I do?
in this case `idz` will be `a1`, you need to first get the numeric portion form this, for that you can use String.substring() var idz = $('[id^=a]:visible').attr('id'); var idv = parseInt(idz.substring(1), 10);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "jquery" }
Don't show slideshow image caption I have a jQuery slideshow that displays a caption over each slide by taking the text from the image's alt and title text. The only problem is I don't want it to display the caption at all when an image in the slideshow doesn't have a title/alt. See the example code here: < I know I need to have an IF statement test to see if the image title/alt is blank, but nothing I try has worked.
Try something along the lines of: var title = $('.showimage').attr('title'); var alt = $('.showimage').attr('alt'); if (typeof title !== 'undefined' && title !== false && typeof alt !== 'undefined' && alt !== false)​ { // WRAP YOUR WHOLE FUNCTION IN HERE } else { // WRAP YOUR WHOLE FUNCTION IN HERE WITHOUT THE SHOW CAPTION FUNCTION }​
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, slideshow, caption" }
Non-3D View for Widgets in Dock I have the following QDockWidget: !enter image description here My question is how do I get rid of the 3-D view for the QTableWidget in this case. I just want plain white background, no 3-D frames, no raised stuff... I think I have to do something with the style but I don't know what...
Since `QTableWidget` inherits from `QFrame`, you can simply set: widget->setFrameStyle(QFrame::Panel | QFrame::Plain);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "qt" }
Python loop creating for line in f: yo = f.readline(), index = yo.find(':'), p = yo[0:index+1], pic = yo[index+1:len(yo)], print ('zz' + p), f.close() SyntaxError: can't assign to function call Why can't I assign my variable (yo) to f.readline() in loop but can do it when it's not in loop?
Note: assuming "," at the end are just typos. You should always (in 99% cases) use `with` statement when working with files: with open("filename") as f: for yo in f: index = yo.find(':') p = yo[0:index+1] pic = yo[index+1:len(yo)] print ('zz' + p) To answer your question, after `for line in f:` cycle is done `f.readline()` will not return what you probably expect from it. P.S. Consider this 'pythonic' optimization: with open("filename") as f: for yo in f: p, pic = yo.split(':', 1) print('zz{p}:'.format(p=p))
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python" }
What happened to Magneto after the past changed in X Men Days of Future Past? In **X Men Days of Future Past** , After the history was changed, Logan wakes up and we see that everyone is there, including Charles, Jean, Scott, Storm, and Beast. However, Magneto was not there. He was also with Charles and remaining X Men when they went to China to seek help of Kitty. I am curious to know what happened to Magneto in the end when past was changed?
Magneto's disappearance in the new future clearly suggests that he didn't come together with Professor X. And it's reason is clear because there is no risk of Sentinels anymore. So we can conclude any number of theories about it, like he is still planning something bad, or retired from his villain work or died or anything you can ever think of. But we don't know what happened because now the old trilogy is no more canon, as discussed in one of my own answers. So we only know what happens till X-Men Apocalypse, rest is uncertain. As per X-Men Apocalypse, the latest status of the character is: > Magneto helps rebuilding the X-Mansion with Jean Gray and then goes on his separate ways.
stackexchange-movies
{ "answer_score": 5, "question_score": 7, "tags": "plot explanation, x men cinematic universe, x men days of future past" }
jquery how to get the page's current screen top position? jquery how to get the page's current screen top position? If I scroll my mouse wheel to some part of the page, how do I get the page's current top position? I want click one element in my page, then open a div which top is to current screen top. So just put the current screen top position to: $('#content').css('top','current position'); And #content { position:absolute; left:100px; }
var top = $('html').offset().top; should do it. edit: this is the negative of `$(document).scrollTop()`
stackexchange-stackoverflow
{ "answer_score": 50, "question_score": 44, "tags": "jquery" }
Php minimum value form wordpress Im trying to get a minimum form value for my Php wordpress form. I want to make that the value is always more than 6. So the visitor have to selected a value above 6 and not below 6. Hope you can help, this is my code so far. <div class="quantity fl-wrap clearfix"> <span><i class="fa fa-clock-o"></i><?php esc_html_e( 'Maanden: ', 'citybook-add-ons' ); ?></span> <div class="quantity-item" data-min="1"> <input type="button" value="-" class="minus"> <input type="text" name="lb_quantity" value="6" class="qty" size="4" required="required"> <input type="button" value="+" class="plus"> </div> </div>
I am not sure what Wordpress plugin your using. but try changing following line: <div class="quantity-item" data-min="1"> to: <div class="quantity-item" data-min="6">
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php, wordpress, forms" }
Combinatronics Summation Series I have a series as follows: > $$\sum_{k=1}^{15} {30 \choose 2k-1}/2k$$ I have tried expanding and evaluating by replacing $${30\choose29}/30 $$ with $${30\choose1}/30 $$ How do you solve it, is there a general approach to attempt such questions?
> We obtain \begin{align*} \color{blue}{\sum_{k=1}^{15}\binom{30}{2k-1}\frac{1}{2k}}&=\frac{1}{31}\sum_{k=1}^{15}\binom{31}{2k}\tag{1}\\\ &=\frac{1}{31}\sum_{k=1}^{15}\binom{31}{32-2k}\tag{2}\\\ &=\frac{1}{31}\sum_{k=1}^{15}\binom{31}{2k-1}\tag{3}\\\ &\color{blue}{=\frac{1}{31}\left(2^{30}-1\right)}\tag{4} \end{align*} _Comment:_ * In (1) we use the binomial identity $\binom{p}{q}=\frac{p}{q}\binom{p-1}{q-1}$. * In (2) we change the order of summation $k\rightarrow15-k+1=16-k$. * In (3) we use the binomial identity $\binom{p}{q}=\binom{p}{p-q}$. * In (4) we observe that the series in (1) and (3) summed up give $\sum_{k=1}^{30}\binom{31}{k}=2^{31}-2$.
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "sequences and series, binomial coefficients" }
Downloading file using Spring Portlet MVC I want to allow the user to save file using mvc portlet. In my code i am making an **ajax call** hence it has to be a resource response. response.setContentType( "application/octet-stream" ); response.setProperty("Content-Disposition","attachment; filename=\""+fname+"\""); response.setContentLength(b.length); OutputStream po= response.getPortletOutputStream(); po.write(b,0,b.length); po.flush(); po.close(); In ajax response when i do `alert(resp)`, I am getting the whole content of my file in alert but still not getting any option for download. Please help and thanks in advance ;)
Well, since you get the response, you need to allow the user to download it. You can for example use the HTML `data:` _protocol_ and redirect the browser to smt. like data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAA... for a PNG image. Anyway, can't you use a normal request to a portlet? It's trivial then.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, spring, portlet, spring portlet mvc" }
What ../path and ~/path Indicates in MVC? I have one custom helper class called Image which is having two arguments: 1. src 2. alt Now I am going to call that in one of View, @Html.Image("../Images/Indian.gif","Image is not supported or exist") <img src="~/Images/Indian.gif" alt="Image is not supported or exist" /> Now, this both will give me same result but I am confused that why the path was not the same for both and what "../path" and "~/path" indicate? This two-line it generates when I do inspect element in a web browser: <img alt="Image is not supported or exist" src="../Images/Indian.gif" /> <img src="/Images/Indian.gif" alt="Image is not supported or exist" />
> In **ASP.NET** , the tilde `(~)` refers to the application root directory. On the other hand, Two dots `(..)` refers to the folder that is one level higher than the current folder. When you just use `../` regular paths relative to the web server.Means go up a path from current location (Remember that : `. = This location | .. = Up a directory`). The `~` character provide virtual paths and refer to the root of the website.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "asp.net mvc, razor, path, html helper, src" }
Use Taylor sequence write approximate value Use Taylor sequence write approximate value: $$ \sqrt{9.5} $$ Estimate the error approximations three components. Which function should I expand?
One possibility is to expand $f(x)=\sqrt{x}$ about $x=9$. For that you will want to express $\sqrt{x}$ in the form $a_0+a_1(x-9)+a_2(x-9)^2+\cdots$. Alternately (and this would be my preference) expand $f(x)=\sqrt{9+x}=(9+x)^{1/2}$ about $x=0$, that is, find (part of) the Maclaurin expansion of $(9+x)^{1/2}$. The two ways are essentially equivalent. In the first version, you will put $x=9.5$. In the second, you will put $x=0.5$. **Remark:** One might think in terms of using $f(x)=\sqrt{10+x}$. The disadvantage is that then the coefficients involve $\sqrt{10}$. If we use $\sqrt{9+x}$, the coefficients are nice rational numbers. I also direct you to an equivalent but more attractive version of the second way suggested by @minar. It uses $f(x)=3(1+x)^{1/2}$ at $x=\frac{1}{18}$
stackexchange-math
{ "answer_score": 0, "question_score": 2, "tags": "calculus, taylor expansion" }
Is there a proof for existence of complex and hypercomplex numbers As mathematics advanced ,mathematicians found out new type of numbers such as complex numbers and hypercomplex numbers . I had been really fascinated by this idea and the uses of these numbers. However I still have a doubt about them which had actually occured to me recently.When we define a number how do we know that their existence alone does not contradict the existing axioms and theories?Also ,I have heard that there are theories about real numbers whose proofs are based oncomplex numbers. How do we know that those are correct unless we are sure that complex numbers numbers do exist?Thus ,my question is , **IS THERE AN ACTUAL PROOF FOR EXISTENCE OF COMPLEX NUMBERS** or is it that I am mistaken some where?Please help. Thanks in advance...
We can define $\mathbb C$ as the set $\mathbb R^2$ with binary operations $+_C$ and $\times_C$, where $(a,b)+_C(a',b')=(a+a',b+b')$ and $(a,b)\times_C(a'b')=(aa-bb', ab'+ba').$ The reals are then isomorphically embedded in $\mathbb C$ as $\mathbb R\times \\{0\\}.$
stackexchange-math
{ "answer_score": 1, "question_score": -4, "tags": "complex numbers" }
Finding the cube root of a matrix EDIT. Let $A=\begin{pmatrix} -41 & 231 \\\ 66 & 223\end{pmatrix}$ and let $X\in M_2(\mathbb{C})$ s.t. $X^3 =A$. That follows is a little computational reasoning. 1. Show (without any calculation) that, necessarily, $X$ is in the form $aI+bA$, where $a,b\in\mathbb{C}$. 2. Show that $\det(A-x^3I)$ admits, as a factor, a polynomial in $\mathbb{Z}[x]$ of degree $2$ (during a first step, work in $\mathbb{Z}/29\mathbb{Z}$). 3. Find the solutions $X\in M_2(\mathbb{Q})$.
The above matrix $M$ is diagonalizable, so write $D=SMS^{-1}$. Then it is easy to find a matrix $D'$ with $D'^3=D$. Then $(S^{-1}D'S)^3=S^-1{}DS=M$. Even the direct computation gives a solution. Let $$ A=\begin{pmatrix} a & b \\\ c & d \end{pmatrix}. $$ Then $A^3=M$ says that \begin{align*} a^3 + 2abc + bcd + 41 & = 0,\\\ a^2b + abd + b^2c + bd^2 - 231 & = 0\\\ a^2c + acd + bc^2 + cd^2 - 66 & = 0\\\ abc + 2bcd + d^3 - 223 & =0 \end{align*} Buchberger's algorithm immediately gives several solutions, e.g. $$ A=\begin{pmatrix} -3 & 7 \\\ 2 & 5 \end{pmatrix}. $$
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "linear algebra, matrices" }
Delphi method call followed by () I've encountered in some code the following call : `SQLParser.Parse(qry.SQL.Text)().GetWhereClause` and I don't understand the meaning of those 2 parenthesis after the Parse call. Following the implementation I got the declarations for each one of them: TSQLParser = class public class function Parse(const ASQL: string): ISmartPointer<TSQLStatement>; TSQLStatement = class function GetWhereClause: string; and ISmartPointer<T> = reference to function: T;
The Parse function returns a reference to a function. You can call this function. A longer equivalent form would be: var FunctionReference: ISmartPointer<TSQLStatement>; SQLStatement: TSQLStatement; begin { Parse returns a reference to a function. Store that function reference in FunctionReference } FunctionReference := TSQLParser.Parse(qry.SQL.Text); { The referenced function returns an object. Store that object in SQLStatement } SQLStatement := FunctionReference(); { Call the GetWhereClause method on the stored object } SQLStatement.GetWhereClause(); The line in the question is just a shorter version that does not use explicit variables to store the intermediate results.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 4, "tags": "delphi, function pointers, delphi xe2" }
convert uint32 into readable values Hello I am writing an API to communicate with the network manager on ubuntu. When I ask for the IP address the dbus service return something like : broadcast_add = dbus.UInt32(4278298816L, variant_level=1) What I am doing so far is converting it to 32 bit binary by : In [1]: '{0:0<32}'.format(bin(broadcast_add)[2:]) Out[1]: '11111111000000011010100011000000' Is there any straightforward way to convert this uint32 to readable ip address like 192.168.1.255
If you can access this value `4278298816`, you might try to use `struct`, for example: >>> import struct >>> >>> struct.unpack('<BBBB', struct.pack('<I', 4278298816)) (192, 168, 1, 255) >>> >>> '{}.{}.{}.{}'.format(*_) '192.168.1.255' >>>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, python 2.7, struct, dbus" }
How to code the final inner loop in my babysort function? I have a function that needs to sort values in ascending order and there are duplicates. I guess thats what i'm doing with "howMany". But i'm stuck on coding the final loop that assigns the values to counts[j]. void babySort(int nums[], int length){ int counts[100]={0}; for(int i=0;i<length;i++) counts[nums[i]]++; int j=0; for(int index=0; index<100; index++){ int howMany=counts[index]; // need innerloop here that assigns values to counts[j] } }
Well, just run the loop `howMany` times and overwrite the value in `nums`. int j = 0; for (int counter = 0; counter < howMany; ++counter) { nums[j++] = index; } Now sure why do you want to re-assign values to `counts`. `counts` already stores the frequency of each number in `nums`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c++" }
Stop $_POST from having the same value when I refresh When a vote value is changed, the form POSTs the change, then refreshes the page. This is called on the top of the page upon load: if (isset($_POST['q'.$question_id])) { $user->updateQuestionVotes($question_id, $_POST['q'.$question_id]); } Why does it update every time I refresh after the first time? Do I need to unset it somehow?
Because that's the natural behavior of every browser. You need to redirect the user to the same page so that the POST values will not be in the header anymore. Have you tried this? header("Location: /back/to/same/page"); This will redirect the user to whatever page they need to land back on, removing any POST parameters that they sent. Any time you refresh a page, it uses the same headers as before, which means the POST content will still be there.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "php, post" }
How to delete all unpublished comments? I have literally thousands of unpublished comments. I am wondering what is the easiest way to git rid of them altogether. Thanks
For Drupal 6, run the following PHP code: db_query('DELETE FROM {comments} WHERE status = 1'); For Drupal 7, run the following PHP code: db_query('DELETE FROM {comment} WHERE status = 0'); You can also execute the query using Drush's sql-query command, for example drush sql-query "DELETE FROM {comment} WHERE status = 0"
stackexchange-drupal
{ "answer_score": 1, "question_score": 6, "tags": "comments" }
Will I lose the enhancements if I trade my robot? I have an enhancement level 1 for Jaguar. If I trade my robot for any of the robots available, what happens to the enhancements that I won for my robot? Do I have to win those again?
When you trade your robot, you will lose all of the enhancements on your current robot. But not all is lost -- the more enhancements you had, the more money you'll get for trading in your robot. You'll lose your robot enhancements because not all robots have the same enhancements available. For instance, the Katana can have highly-enhanced arms, but its maximum leg enhancements will be lower than its maximum arm enhancements. On the other hand, the _pilot_ training you purchase will apply to every robot. There are also some special enhancements you can get from _destroying_ the secret characters; those will also be lost when you trade in your robot.
stackexchange-gaming
{ "answer_score": 1, "question_score": 2, "tags": "one must fall 2097" }
invalid source string in KSH but not in BASH I try to generate a random string using this command: tr -dc 'A-Za-z0-9!#$%&()*+,-./:;<=>?@[\]^_`{|}~' </dev/urandom | head -c16; echo; I need to put that command into a function within a shell script which needs to run on AIX and Linux. As bash is not installed on our AIX machines I need to use ksh93. When I try to execute this command in bash (or zsh) it works as expected. But in KSH it fails with 'invalid source string'. I tried to rearrange the string and deleted some of the characters but without success. The output is tr: A-Za-z0-9!#$%&()*+,-./:;<=>?@[\]^_`{|}~: invalid source string How do I need to pass this string to ksh to have that working? Thanks in advance
Thanks for the input @glenn-jackman: When I remove \ from the list I got the error obout invalid multibyte character byte but I already knew that LC_ALL must be set to avoid that. I escaped the string now. The **working** snippet is LC_ALL=C tr -dc 'A-Za-z0-9!#$%&()*+,\-./:;<=>?@[\\]^_`{|}~' < /dev/urandom | head -c16; echo; Thanks
stackexchange-unix
{ "answer_score": 1, "question_score": 1, "tags": "linux, ksh, tr" }
APT: Public Key is missing? How to fix? I updated my sources.list with deb squeeze main deb-src squeeze main And called gpg --keyserver subkeys.pgp.net --recv-keys 1C4CBDCDCD2EFD2A The Result was, that it seemed to import something, so the key was found on this sever!? Nevertheless now I get the error: > GPG error: < squeeze Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 1C4CBDCDCD2EFD2A 1. How can I disable/ignore the keychecking in apt in general? 2. What is the adviced way to fix the problem itself. Is there some way to search the key somewhere elese? How would I do that?
You have to add the key to apt using `apt-key`: gpg -a --output /tmp/pub.asc --export 1C4CBDCDCD2EFD2A sudo apt-key add /tmp/pub.asc && rm /tmp/pub.asc cf. <
stackexchange-serverfault
{ "answer_score": 6, "question_score": 4, "tags": "debian, apt, xtrabackup" }
Facebook Navigation - iPhone vs iPad Facebook recently updated their iphone's navigation, to tabs at the bottom. I am curious as to why they did not also do this with their iPad app? I guess you don't see the bottom tabs very often on the iPad, but if they are willing to do it for the iPhone why not for the iPad? Any thoughts? Or logic as to why they stuck with the slide out drawer (Hamburger Menu) on the iPad?
It is obviously difficult to justify why they made this particular product design decision _(without being in a design meeting to hear the discussion)_. My thought would be that they are attempting to optimize gesture inputs. Luke Wroblewski did an excellent write-up a while back about Responsive Navigation: Optimizing for Touch Across Devices. You'll notice that the previous "hamburger menu" was in the **Hard** to access zone for standard touch input. Their new solution places the key features within a short gesture of the thumb. On the iPad, the hamburger treatment is in the **OK** zone. One could also argue that they wanted to elevate the primary functionality, and allow context switching in the application without having to toggle a menu constantly.
stackexchange-ux
{ "answer_score": 0, "question_score": 0, "tags": "navigation, menu, iphone, ipad" }
php/mysql : How to insert a gzcompress-ed string into a text mysql field? I have been trying to compress and store a json encoded string into mysql, but I am getting "unexpected /" errors. I also tried to use addslashes like this: addslashes(gzcompress(json_encode($mystring))); And to display json_decode(gzuncompress(stripslashes($mystring))); But it fails on insert with the error I mentioned. I read somewhere a string with gzcompress should be stored as a blob, but I was hoping there is a way to store it in a mysql text field so I dont have to mess with the db. PS: Some asked for full error message here it is: > Warning: Unexpected character in input: '\' (ASCII=92) state=1 > > PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\x9C\xED}\x8Br\xDB...' for column 'field_text_value' at row 1.
Store it as a `BLOB`. Even if there were a way to store it in a `VARCHAR` or `*TEXT` field in a way that survives a round trip, it would be a horrible way. Are you sure you need compression anyway? You can also make MYSQL do the compression, e.g. `INSERT INTO mytable (compressed_json) VALUE (COMPRESS('[\"the json\"]')`.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 5, "tags": "php, mysql, text, compression, gzip" }
Storing multiple values from single function in python This function prints multiple values, which are indices of a string z, however i want to store those values, and using return will terminate the function leaving me with only the first value of several. def find(a): index=a while index<len(z)-1: if z[index]=="T": for index in range (index+20,index+30): if z[index]=="A" and z[index+1]=="G" and z[index+2]=="T": a=index print a index=index+1
The most straightforward way is to return a `tuple` or `list`: def find(a): index=a ret = [] while index<len(z)-1: if z[index]=="T": for index in range (index+20,index+30): if z[index]=="A" and z[index+1]=="G" and z[index+2]=="T": a=index ret.append(a) index=index+1 return ret You can also use `yield`. I am removing the code for it (you can read the link, it is excellent) because I think returning a `list`makes more sense in your case than `yield`. `yield` makes more sense if you don't intend to always use all of the values returned or if the return values are too many to hold in memory.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, recursion, return" }
Generate all combinations of list members, repeat X times I have list with elements ["0000", "0001"] and i want create repeat them 4 times with all possible pairs. Ex. 0000 0000 0000 0000 0000 0000 0000 0001 0001 0000 0000 0000 0000 0001 0000 0000 0000 0000 0001 0000 0001 0001 0001 0001 0001 0001 0001 0000 0001 0001 0000 0000 0000 0000 0001 0001 Already tried all < functions but these are not what i want.How can i do that, anyone can help me ? Solved by @Adam, list(itertools.product(*([[0, 1]] * 4))) Thanks for everyone helping that fast, love you all.
What about using list comprehensions? (x,y) for x in a for y in b Where `a == list[0]` and `b==list[1]` Repeated four times: (x,x,y,y) for x in a for y in b
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, combinations" }
Binding to Dataset Selected Row Is there any way bind textboxes to the row of a dataset that is selected in a combobox? For example I have a dataset with 2 columns, one called name (this is the primary key) and the other is called author. I would like to set up databinding so that when the user selects the name in the combobox the corresponding author appears in the text of a textbox. Specifically I want to know if this can be done through databinding or if it will require code for the selecteditemchanged event, or if it should be done using a value converter. I think it would be possible to do with a value converter, but I was hoping it could be accomplished entirely in XAML. This turned out to be a good tutorial to follow for building the appropriate code using the visual studio wizards for all the data stuff. <
Try this: <TextBox Text="{Binding ElementName=comboboxName, Path=SelectedItem.author}" /> `comboboxName`is Name attribute of your ComboBox `.author` is field name
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "wpf, xaml, binding, dataset" }
Why does calling c_str() on a function that returns a string not work? I have a function that is returning a string. However, when I call it and do `c_str()` on it to convert it into a `const char*`, it only works when I store it into another string first. If I directly call `c_str()` off of the function, it stores garbage value in the `const char*`. Why is this happening? Feel like I'm missing something very fundamental here... string str = SomeFunction(); const char* strConverted = str.c_str(); // strConverted stores the value of the string properly const char* charArray= SomeFunction().c_str(); // charArray stores garbage value static string SomeFunction() { string str; // does some string stuff return str; }
`SomeFunction().c_str()` gives you a pointer to a temporary(the automatic variable `str` in the body of `SomeFunction`). Unlike with references, the lifetime of temporaries isn't extended in this case and you end up with `charArray` being a dangling pointer explaining the garbage value you see later on when you try to use `charArray`. On the other hand, when you do string str_copy = SomeFunction(); `str_copy` is a copy of the return value of `SomeFunction()`. Calling `c_str()` on it now gives you a pointer to valid data.
stackexchange-stackoverflow
{ "answer_score": 27, "question_score": 21, "tags": "c++, string" }
Minimum IOS version for Adobe Air App I am writing an app for IOS using Adobe Air 3.2 using the new stage 3D feature. What is the minimum version of IOS that I can target? Also in order to target the new Ipad 3 it seems that you need to instruct the compiler to reference IOS 5.1. Will this mean that if I compile with that setting I wont be able to run my app on lower IOS versions?
1) iOS 4 and above is stated in the specs 2) You can run on any version above your deployment target, which I assume is iOS 4.0 because of what the above tech specs state, regardless of the version you compile against.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ios, air, stage3d" }
How to use code assist in Eclipse with ant Usually when we use Eclipse IDE, it can assist us with related functions/variables, checking the compilation errors automatically. Now I want to use Ant to manage the compilation and deployment process. After adding import instruction in build.xml, I can compile and run it with an Ant builder. But the problem is, when coding, the Eclipse editor cannot give code suggestions and always complains that I don't import some libraries which added in build.xml. How to make the Eclipse editor give code suggestion and checking compilation errors based on settings in build.xml with a ant builder?
My version of eclipse works fine for code completion and syntax checking. Maybe yours is turned off? Check under Window > Preferences > Ant > Editor and then on the Problems tab make sure that 'Ignore all buildfile problems' is turned off. There are also some content assist options around that area - mine are all turned on. I'm using SCS 2.5.0.RELEASE, which sits on top of eclipse 3.6.1.r361
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "eclipse, ant, code assist" }
C function that doesn't 'wait' for any input, but detects if any? Is there a C function that doesn't wait for input but if there is one, it detects it? What I'm trying to do here is continue a loop endlessly until any key is pressed. I'm a newbie, and all the input functions I've learned so far waits for the user to input something.. I hope I'm clear, although if I'm not I'm happy to post the code..
WIndows kbhit( ) does exactly this **non-blocking keyboard char-ready check** , and there's a kbhit( ) for Linux **over here**
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c, windows, gcc, input, codeblocks" }
Android Unzip zip file I need some help really fast. I am having troubles with unzipping a file that I have downloaded to my phone as a background process in the app that I am building. The code that I have downloads a zip file from a server that I have set up specifically for the app. The zip file is not corrupted or anything like that. But if you guys could help me find a way to unzip the file that would be fantastic I have tried a few different ways and I cant seem to get it right. :/
You can use open source "zt-zip" to solve your problem:zt-zip
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, android" }
Can not edit build.prop I am trying to edit the lcd density in build.prop in /system but every time after reboot my changes are lost.. I tried to adb pull + edit + adb push in normal and recovery mode.. also i tried fileexpert and super manager but nothing worked. I heard many people saying about root explorer but its not free.. I want to be sure if my problem will be solved with root explorer then i will buy it.. Please help me out guys.. I am using android 2.3.3 on HTC HD2. My Rom is custom one (HyperDroidGBX-v12)
Answering my own question as found the solution. We can edit build.prop from mobile. I downloaded ES file explorer which is free. then from optin set "root explorer" and set "mount system as read/write" Now edit build.prop and save it using ES file explorer's editor then uncheck "root explorer" and "mount system as read/write" for safety.. hope it wil help someone :)
stackexchange-android
{ "answer_score": 4, "question_score": 3, "tags": "editing" }
Change values in a multidimension Scala array I'm pretty new in Scala and trying to change the values in a multi dimension Array in the _Scala way_ if there is such thing :) Let's see the problem: val table = Array.fill(5, 5){1} and I'm trying to change every 1 to 5 for (i <- 0 until table.length) { for (j <- 0 until table(i).length) { table(i)(j) = 5 } } But I think there will be some other (more functional way) to do the same thing. Thank you!
val table = List.fill(5, 5){1} val all5 = table.map(_.map(_ => 5))
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "scala" }
Generated, namespaced POCO classes ( _I feel like I'm missing something important here._ ) I'm creating a WCF Data Service (5.0) using the "database first" approach for the entities. I've created tables with " _namespaced_ " names, using the `.` ( _dot_ ) such as `[Entertainment.Event]` and `[Promotions.Event]`. The EF 4.x POCO generator template of course knocks these out, via the call to `CSharpCodeProvider.CreateEscapedIdentifier()`. I'd like very much to generate ( _and regenerate, and appropriately map_ ) **namespaced POCOs** ; specifically, preserving the implied namespaces of the tables. What am I looking at as far as accomplishing this? I'm guessing it will involve awhile's worth of swimming through T4 templates. Ultimately, is this doable?
I'd suggest to create one context per your DB schema, placing each one into whatever namespace you like.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, entity framework, edmx" }
reimer tieman reaction only one ortho product **why we cannot have two reimer tiemann substitutions on the same phenol as CHO- group is electron withdrawing it wont disturb electron concentration at its meta which is phenol's ortho- product**
There are some literature evidence that shows to have two Reimer–Tiemann substitutions on same phenol ring could be possible. For example, salicilic acid is a Reimer–Tiemann product from phenol and carbon tetrachloride. Yet, it had undergone another Reimer–Tiemann reaction to give 5-formyl-2-hydroxybenzoic acid with $17\%$ yield (para-substitution) but no 3-formyl-2-hydroxybenzoic acid (ortho-substitution) when chloroform was replaced by trichloroacetic acid ( _J. Chem. Soc._ , **1933** , 496-500). For more examples: Read, _Chem. Rev._ , **1960** , _60(2)_ , 169–184. _J. Chem. Soc._ , **1933** , 496-500.
stackexchange-chemistry
{ "answer_score": 2, "question_score": -4, "tags": "organic chemistry, aromatic compounds, phenols, carbene" }
In locally weighted regression, how determine distance from query point with more than one dimension If the query point in a locally weighted regression is multidimensional (for different features), how do we determine if there are points close-by the query point? This is especially true if the features have different units.
If x is a vector of the individual differences for each feature, one could use a few different norms to measure the "size" of x (and the distance between any two points). The most commonly used norm is the L2 norm. Different normalization schemes could be used but if you scale each feature so that 80% of the points have a value between -10 and 10 you should be OK.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "machine learning, logistic regression" }
How to split string by character length and not include next section of string? If I'm splitting a string by character length and wanted the split string to not include the next section of the string which is specified by a _comma_ or by another wildcard. How do I do this whilst being below the character limit? raw_string = ('ABCD,DEFG,HIJK') split_string = re.findall(.{1,10}, raw_string) > split_string = 'ABCD,DEFG,H' How do I set my Regex so that my string produces something like this? >split_string = "ABCD,DEFG"
You might let it backtrack until it can assert a comma to the right. Note that you are using `re.findall` that will return a list of matches. import re raw_string = 'ABCD,DEFG,HIJK' split_string = re.findall(r".{1,10}(?=,)", raw_string) print(split_string) Output ['ABCD,DEFG']
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, regex" }
How to rebuild original data from a histogram? I have data in the following form. I have a list of values and a list of frequencies that indicate how often each value has occurred. Example list of values: `{5,7,4}` Example list of frequencies: `{1,2,3}` I would like to obtain the original data from which such a histogram was generated. Any suggestions on how to do this with _Mathematica_ ? Example: `{5,7,7,4,4,4}`
Without looking at performance, but only on understanding: First, you create a function `f` which takes a `value` and a `count` and which reproduces the `value` exactly `count` times. In the simplest case f[val_, count_] := ConstantArray[val, count] and you can call `f[3,4]` to get `{3,3,3,3}`. Now, you combine your input arrays so that you can call `f` directly for each pair. For this, you can use `MapThread`. To create you final result, you have to `Flatten` the output: Flatten[MapThread[f, {{5, 7, 4}, {1, 2, 3}}]] This all can of course be combined into one call vals = {5, 7, 4}; counts = {1, 2, 3}; Flatten[MapThread[ConstantArray, {vals, counts}]] or ConstantArray @@@ Transpose[{vals, counts}] // Flatten or (to simplify kgulers approach) Inner[ConstantArray, vals, counts, Join] and many more
stackexchange-mathematica
{ "answer_score": 19, "question_score": 12, "tags": "list manipulation, histograms" }
Converting Currency Method: <identifier> expected May split declaration into declaration and assignement What's wrong with this code? private void jButtonConvActionPerformed(java.awt.event.ActionEvent evt) { double Algerian_Dinars = Double.parseDouble(jtxtConvert.getText()); if (jCombCrrency.getSelectedItem().equals("USA")) { double US_Dollar = 0,00905365; /*here is the error???*/ String cconvert1 = String.format("N%.2f",Algerian_Dinars * US_Dollar); jlblConvert.setText(cconvert1);
You can't use comma in doubles in Java. double US_Dollar = 0,00905365; ^ I am assuming you missed out decimal instead like: double US_Dollar = 0.00905365;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "java, variable assignment" }
Python gives me the error sqlite3.OperationalError: incomplete input import sqlite3 con = sqlite3.connect("database.db") cursor = con.cursor() def tablo_olustur(): cursor.execute("CREATE TABLE veritabani(İsim TEXT, Yazar TEXT, Yayınevi TEXT, Sayfa INTEGER") con.commit() def veri_ekle(): cursor.execute("insert into veritabani Values('İstanbul Hatırası', 'Ahmet Ümit', 'Everest', 561)") con.commit() tablo_olustur() veri_ekle() con.close() It gives me the sqlite3.OperationalError: incomplete input error in the line 7. How do I solve this?
here is the error : cursor.execute("CREATE TABLE veritabani(İsim TEXT, Yazar TEXT, Yayınevi TEXT, Sayfa INTEGER") it should be like cursor.execute("CREATE TABLE veritabani(İsim TEXT, Yazar TEXT, Yayınevi TEXT, Sayfa INTEGER)") and now might work just balancing you parenthesis
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, python 3.x, sqlite" }
Hosting html file over mosquitto I just found that mosquitto had got a websockets upgrade which allows it to host the HTTP services. I tried hosting a html file using the websockets feature on the port 8080. The mosquitto broker seems to start fine and the mqtt services on the other ports seem to function properly. But when i try to access the html file over the localhost I get the a response saying no data sent by the server. I am not sure where my mistake lies..Any ideas?
Mosquitto is not a HTTP server, it can not serve generic files. The HTTP listener is only there to facilitate an upgrade to the websocket protocol in order to run MQTT over a websocket connection.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "html, mqtt, mosquitto" }
Auto Refresh Excel Sheet I have an excel workbook, in the workbook I have 2 sheets called Front Page and Drafting. Drafting worksheet is referencing some of the values in the Front Page worksheet. It is just a basic reference I have formulas like : ='Front Page'!D46 (in the drafting page cells to reference the cells in the Front Page) My problem is whenever I make a change to one of the referenced cells on the front page, I need to refresh my drafting page in order to get the newly entered value. I need to press F9 every time I make a change in the front page to make it reflect back to Drafting Page. I am not sure what is causing this issue? Could someone please help me fix it? Thank you.
On the Formulas ribbon, find the Calculation Options drop-down and make sure to select "Automatic". Then changes will reflect immediately, without pressing F9 ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "vba, excel, excel formula" }
Working with Google Maps API in Python I've been trying to work with the google maps api and i keep getting this error: "HTTPError: HTTP Error 403:Forbidden." take for example this simple case (its based on a more elaborate case where i extract the adress from an XML): from googlemaps import GoogleMaps import xml.etree.ElementTree as et gmaps = GoogleMaps() pars = et.XMLParser(encoding='utf-8') tree = et.parse('data.xml',parser=pars) root = tree.getroot() adress = "ringelblum 7 beer sheva" lat , lng = gmaps.address_to_latlng(adress) print lat, lng i've seen different videos and tutorials and it should be very simple. why doesnt it work? Thanks a lot guys.
You could try this, you will need to have a key from google, the requests library and know your way with json: geo_s =' param = {'address': address, 'key': 'YOUR_KEY'} response = requests.get(geo_s, params=param) json_dict = response.json() lat = json_dict['results'][0]['geometry']['location']['lat'] lng = json_dict['results'][0]['geometry']['location']['lng'] print({'lat': lat, 'lng': lng})
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "python, google maps, google maps api 3, geolocation" }
How Do I Enqueue a Script into 2 different Footers on the Same Site? I have two different footers being used on a WordPress site. One is the standard `footer.php`the other is for the contact and legal pages and is `footer-contact.php` Calling them on the relevant page is straightforward enough - I just a use `<?php get_footer('contact'); ?>` on the pages where the contact footer is needed. This 2nd footer design though isn't calling in the scripts. In my functions.php file I use the following, with the last parameter being 'true' which places the JS in the footer. `wp_enqueue_script('main_js', get_theme_file_uri('/js/main.js'), NULL, '1.0', true);` How do I also enqueue my scripts into the second footer i.e. `footer-contact.php`
While `get_footer('name_template_file');` includes the defined footer template it does not output Wordpress _wp_enqueued_ styles and scripts that are defined to be output in the footer automatically. To let your page output all javascript files and stylesheets that supposed to go to the footer call `<?php wp_footer(); ?>` at the place you want them to be rendered. You could consider to place them in you main template (directly before `</body>` so there is no need to put them in every single footer template you might include. In most cases it should work fine.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp enqueue script, footer" }
C++ map for ranges I am working on a project on C++ and I am new to the language. I am on a function which has to do something ranging from hex numbers 0x00 to 0xFF, and I have been told that I could do that with a map. Problem is, so far in the examples I've seen I have just seen it used for just one entry while I need something to be done depending on specific ranges. Is there a way I can do that in map or do I need to use something else to do the desired function?
If understand correct you store some values in a map, with key a value from 0x00 for 0xFF? Possible solution could be: typedef std::map<unsigned char, int> values; void print( values::const_iterator begin, values::const_iterator end ); values v; // print range [0x01,0x20] print( v.lower_bound( 0x01 ), v.upper_bound( 0x20 ) ); // print range [0x10,0x40[ print( v.lower_bound( 0x10 ), v.lower_bound( 0x40 ) ); // print range ]0x20,0x50[ print( v.upper_bound( 0x20 ), v.lower_bound( 0x50 ) ); Is that what you need?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++, dictionary, hex, range" }
How to access value from react-native-cn-richtext-editor I have successfully implemented `react-native-cn-richtext-editor` with limited toolbar functions. I want to know that, how to get value (text that we have typed) from editor. I am new in RN, have tried to get value but didn't get success. How can I resolve this issue, as I want to sent this text to server and then do further process.
Finally I got the solution of above question. convert the value in HTML with convertToHtmlString write following command, let html = convertToHtmlString(this.state.value) for more details refer this github link
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "react native, react native ios" }
how to hide multiple markers when zooming out Any one know how to avoid a same marker shown in multiple time latlngbounds.extend(markers[i].getPosition()); map.setCenter(latlngbounds); map.fitBounds(latlngbounds);
You can achieve this feature bu using Google Map Marker Cluster. Greate tutorial is here. <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript" }
How to return UTF with re:replace I'm trying to remove newline character in a string. I tried this : remove_newline(Data) -> re:replace(Data, "\n", ""). but it seems to return an ISO-8859 string. I tried this too : remove_newline(Data) -> {ok, MP} = re:compile("\n", [unicode]), re:replace(Data, MP, ""). but it doesn't work either. _Data_ comes from a _file:read_line_ an is UTF encoded. How to get an UTF string from re:replace ?
The reason is probably because you get the result as a list. You may need to use `re:replace(Data, "\n", "", [global, {return, binary}])`. Just look at documentation. <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "regex, utf 8, erlang" }
flex mobile project : add zoom controls on google map I am developing a google map application using adobe flex 4.5 . I need to add zoom controls like one we see in android mobile(+,-) to the map. I am using "map_flex_1_20.swc" file. If I use built in zoom controls it is appearing like one we see on desktop or web. please help me to add zoom controls(+,-) like on android device
I know that this is possible in JavaScript API...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "google maps, flex4.5" }
Three.js - setting cube color? I am trying to create a simple 3d game with three.js. I am trying to create coloured cubes, but all the cubes just stay the same color. When I create a cube I do: var geometry = new THREE.BoxGeometry(width, height, length); var material = new THREE.MeshNormalMaterial({color: hexColor}); var cube = new THREE.Mesh(geometry, material); (which is inside a function) Then I use the function twice, hexColor being 0x0000ff(blue) and 0xff0000(red). The cubes do generate, but all the faces of the cubes are different colours. I have also tried cube.material.color.setHex(); But it gives out Uncaught TypeError: Cannot read property 'setHex' of undefined Help please!!
your issue is that `THREE.MeshNormalMaterial()` doesn't have a color property. Try using `THREE.MeshBasicMaterial({ color: yourHexColor });` instead. If you do that, your `cube.material.color.setHex(yourHexColor);` call should work just fine. You can find all of the necessary information on the Three.js docs page and, if you're interested, take a look at the dedicated examples page.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, 3d, three.js" }
Deciding which machine learning algorithm to use I got this question on a test. I'm not clear what the right answer is because all three are classification algorithms: You have a ride sharing service where people can select their rides online based on price and time. A driver can transport more than 1 person at a time. You have information on the last 4 million trips (basically who took which ride). The goal is to predict which future rides will have more than 'X' number of passengers. Which algorithm would you NOT use: A) Logistic Regression B) Naive Bayes C) Support Vector Machine D) None of these Any ideas? I'm really interested in the thought process here.
It depend, but with respect to these information, the answer is D, Because you face with regression problem( **more than 'X'** ), and A,B,C can use for regression problems(although naive base regression is not very popular)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "algorithm, machine learning, classification" }
Find first and last order date for ID (same id might appear multiple times) in Excel I have a list of orders with the following columuns: Buyer ID, Order Date, Order Value I need to add one column that lists the FIRST order date, and one that lists the LAST order date. In case of only 1 order, the date would be the same in both columns. **EG - this is what I have** Buyer ID Order Date 1 1/31/2016 2 2/27/2016 1 5/31/2016 **This is what I would like** Buyer ID Order Date Last Order First Order 1 1/31/2016 5/31/2016 1/31/2016 2 2/27/2016 2/27/2016 2/27/2016 1 5/31/2016 5/31/2016 1/31/2016 I have over 1000 buyer IDs, not all of them have multiple orders
Let's assume your "Buyer ID" values are in cells `A2:A4`, and your "Order Date" values are in cells `B2:B4`. To get the "Last" value in cell `C2` (the topmost non-header cell in your "Last Order" column), type or paste the following formula, then press `Ctrl+Shift+Enter` to enter it: =MAX(IF($A$2:$A$4 = A2, $B$2:$B$4)) Then, to get the "First" value in cell `D2` (the topmost non-header cell in your "First Order" column), type or paste the following formula, and again press `Ctrl+Shift+Enter` to enter it: =MIN(IF($A$2:$A$4 = A2, $B$2:$B$4)) Then, simply formula-copy the cells `C2:D2` down to as many rows as you have data. Please note that it is important to enter the formulas using `Ctrl+Shift+Enter` instead of just pressing the `Enter` key, as this will create an array formula. Otherwise, in each cell you would get the `MAX` or `MIN` values for the entire range `A2:A4`, without taking the "Buyer ID" criterion into consideration.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "microsoft excel" }
MS Form Recognizer Tool Create Project When creating new Form Recognizer project, getting this error: I was working on this project last month and now cannot create new project or access existing proejct. Error Message S-Shot How to fix? Thanks.
When you share an Azure blob storage path, you have to set an expiration date of such access. The error message indicates that such shared access has expired. You need to re-share the blob storage path. Please refer to the readme file of our FoTT tool for more details. -xin [MS Azure Form Recognizer Team]
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "azure form recognizer" }
Is there a set that intersects every line twice which is Lebesgue measurable or Borel? Let $A$ be a subset of $\mathbb{R}^2$ which intersects every straight line in exactly two points. Is there a such set which is Lebesgue measurable or Borel? A well-known fact is that there exists such set which is not Lebesgue measurable.
There is such a set which is Lebesgue measurable, and indeed of Lebesgue measure zero. To see this, start with a subset $S$ of $\mathbb R^2$ such that every line intersects it in continuum many points, for instance $C\times\mathbb R\cup\mathbb R\times C$, where $C$ is the Cantor set. Now repeat your favorite transfinite recursive construction of a set $A$ intersecting each line at exactly two points, modifying it in such a way that we all the points picked belong to $S$. Since $A$ is a subset of a measure zero set $S$, it itself is Lebesgue measurable of measure zero. It appears that existence of such a set which is Borel is an open problem, see this MO post.
stackexchange-mathoverflow_net_7z
{ "answer_score": 20, "question_score": 12, "tags": "set theory, real analysis" }
Predictions using AUC metrics for multilabel classification I'm using AUC metrics to do a multilabel classification. Since keras has removed prediction_classes for obtaining the prediction classes, I just use a threshold of 0.5 to get the output classes. However, as I understand, for AUC the threshold should not be 0.5 for an imbalanced data set. How can I get the threshold that was used for training the model? Besides, I know that AUC is used for binary classification. Can I just use it for multilabel problem? How to calculate the threshold? By taking the average or not.
You can use **AUC** for the multi-label problem, check this. import numpy as np y_true = np.random.randint(0,2,(100,4)) y_pred = np.random.randint(0,2,(100,4)) m = tf.keras.metrics.AUC(multi_label=True, thresholds=[0, 0.5]) m(y_true, y_pred).numpy() FYI, from `tf 2.5`, it now supports logit predictions.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, tensorflow, keras, multilabel classification" }
Color (syntax highlighting) within an HTML <code> tag In a code fragment like the following ... class Foo { internal Foo() { for (int i = 0; i < 42; ++i); } } ... its various keywords and so on are color-coded when they're displayed in my browsers. When I do "View source", I don't see anything special in the HTML that would implement this color-coding. How and/or where is this syntax-specific color-highlighting implemented, then? For example is it built-in to the browsers, or is it implemented by site-specific JavaScript editing the DOM within the browsers? I find this a difficult question to Google for.
Stack Overflow uses Google's prettify JS library for doing syntax highlighting. It executes on the client side after the HTML has been delivered by the server. That's why you don't see it in the raw HTML source. If you have a browser plugin such as FireBug, you'll be able to inspect the DOM after prettify has done its magic. Update 2020-09-14: Stack Overflow switched from Google's prettify to highlight.js.
stackexchange-stackoverflow
{ "answer_score": 42, "question_score": 44, "tags": "html, syntax highlighting, color coding" }
Prevent the insertion of figure after the footnote How can I prohibit putting figure after the footnote? I have pretty simple LaTeX code that has a lot of figure environments, and I see the figure is inserted after the footnote. \documentclass[10pt, onepage]{article} \usepackage{graphics,graphicx} \usepackage{hyperref} ... dependent code\footnote{You should use at least JRE 1.5 or later, but I highly recommend using JRE 1.6 or later}, you can safely use the JRE 1.5 or later. \begin{figure} \centering \includegraphics[width=0.5\textwidth]{pic_install/4_configure_build_path.png} \caption{Configuration menu} \label{fig:config_build} \end{figure} !enter image description here
The solution is to load the `footmisc` package with the `[bottom]` option: \usepackage[bottom]{footmisc} For some interesting discussion of the rationale behind the standard behaviour, see: * Tables below footnotes, is this a good output routine algorithm or a bug?
stackexchange-tex
{ "answer_score": 21, "question_score": 19, "tags": "floats" }
How many 1's in last 4 days? ![enter image description here]( I would like to count or sum how many 1's in last four days (1/1 to 1/4) for each name (A, B, C, D) in Informatica Developer. Advise please!!
simply create an exp transformation and a new output port. Formula should be like this- o_how_many_1s= day1 + day2+day3+day4 Now, you said, all the day* values can be wither 0 or 1, so adding them will give you count of 1s. If you have null in these fields, then you can use `IIF(isnull(day1),0,day1)` logic while adding. If you have some numbers other than 0,1, then, then you need to use something specific like this o_how_many_1s= IIF(day1=1,1,0) + IIF(day2=1,1,0)+IIF(day3=1,1,0)+IIF(day4=1,1,0)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "count, sum, informatica" }
Set Custom Cursor from Resource File In my VB.net project I created a custom cursor (Window.cur). How can I assign that to the cursor without having to use the full file path to that file? VB.Net has My.Resources but it does not show the cursors that are embedded in the project. I found an example that used code like this: New Cursor(Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream("Window.cur") but that does not work.
Guessing the resource name can be difficult. To find out, run Ildasm.exe on your program. Double-click "Manifest" and look for the .mresource. Another way to do it that avoids guessing: Project + Properties, Resource tab. Click the arrow on the "Add Resource" button, Add Existing File and select your .cur file. Make your code look like this: Dim ms As New System.IO.MemoryStream(My.Resources.Cursor1) Button1.Cursor = New Cursor(ms)
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 6, "tags": "vb.net, mouse cursor" }
Check if an instance in AWS have absolutely no tags using python boto3 I'm using python boto3 to query and update tags from AWS instances. I'm trying to handle a condition where there are 'NO' tags present on an instance. I figured that the tags are actually list of dictionaries in a boto3 ec2 query response, however none of the methods for checking a non-existent 'list' is working. I have tried following options (i['Tags'] is list of tags) if i['Tags']: if not i['Tags']: if len(i['Tags']) != 0: Since no tags are present on the instance, all the above conditions fail with the following error message. Traceback (most recent call last): File "./tag-automation.py", line 106, in <module> read_instance_tags() File "./tag-automation.py", line 81, in read_instance_tags if not i['Tags']: KeyError: 'Tags' Any pointers to fix this would be greatly helpful. Thank you.
If there are no tags, then there would not be a `Tags` entry in the dictionary. Therefore, use: if 'Tags' not in i:
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, amazon web services, boto3" }
How can i get the uilabel text changed upon clicking a UIbuttion in the UITableViewCell I have UITableViewCell Cell Shown Below this Custom cell have two buttons for adding/subtracting the product quantity.I have set the current quantity as + button tag and able to get.but how will i set the label text 2 and so on when user click the + button. !I have UITableViewCell > i don't want to change the DataSource of the table view ie by adding the incremented value in the array from where the data coming into the UITableView and then reloading the tableView. Also upon exploring the SO i Find CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tblCart]; NSIndexPath *hitIndex = [self.tblCart indexPathForRowAtPoint:hitPoint]; to get the NSIndexPath for the cell that have the button.
I achieve the required funtionality using the following -(void)addQ:(UIButton*)sender { CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tblCart]; NSIndexPath *hitIndex = [self.tblCart indexPathForRowAtPoint:hitPoint]; NSInteger num=sender.tag; num=num+1; NSLog(@"%ld",(long)sender.tag); NSLog(@"hitIndex.row is %ld",(long)hitIndex.row); [self alterTheQuantity:hitIndex.row Num:num]; } -(void)minusQ:(UIButton*)sender { NSInteger num=sender.tag; num=num-1; if(num <0){ num=0; } CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tblCart]; NSIndexPath *hitIndex = [self.tblCart indexPathForRowAtPoint:hitPoint]; [self alterTheQuantity:hitIndex.row Num:num]; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ios, cocoa touch, uitableview, uikit" }
How to check if you can create BigInteger from String I have a method: public BigInteger method(String param){ try{ return new BigInteger(param); }catch(NumberFormatException e){ LOG.error(e, e); } } I want to check if I can create a `BigInteger` from those `String param` without generating `NumberFormatException`. Is there any way do it this way?
Basically you have 2 possible approaches: 1. You check if the String does only contain numbers, and not more than you could have in a Bigint 2. cast in a `try{}catch()` and catch everything... this is not very performant and more a lazy method of doing it! Here you can probably find some inspiration :)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "java" }
SYS_READ call only works once, seemingly skips over code when ran again I'm trying to rewrite a little text game in assembly for fun, and I noticed that I'm only able to run the following code successfully once. If I run it again elsewhere, it will seemingly skip over the code. I am compiling using the following command: `nasm -f elf64 -o test.o textgame.s && ld -o test test.o && ./test` Full code mov rax, 0 mov rdi, 0 mov rsi, buffer mov rdx, buffer_len syscall
Solved! Thanks to Jester! > With a buffer_len of 1 there is no place for the linefeed so the next time around that will be read.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "linux, assembly, x86, nasm" }
How to create a file from render html sails js Trying to make a file that render into ejs how can i do this let makeFile = res.view('file.ejs',{result:result}); fs.writeFile(sails.config.myconf.path+'file.xml', makeFile, function (err, result) { if(err){ console.log(err) return } }); Tried this way getting undefined always can any one please understand why this is causing issue thanks a ton in advance
`res.view` is really meant to come at the end of your method. It facilitates a return sent by the `res` object, and I don't think it returns anything useful. What you want is likely `res.render` \- you can use that to get (and then work with) the output html as a string. res.render('file.ejs', {result: result}, function(err, renderedHtml) { if (err) { /* handle the error */ } // renderedHtml should be the html output from your template // use it to write a new file, or whatever is required console.log(renderedHtml); return res.send({fileCreated: true}); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "node.js, sails.js, ejs" }
Prove the uniqueness of the decomposition of a vector space in a direct sum of $n$ vector subspaces Just to clarify, a sum of subspaces $U_{1},...,U_{n}$ of the vector space $V$ is said to be direct if $U_{j} \cap (U_{1}+...+U_{j}^*+...+U_{n})={0}$ In which the $U_{j}^*$ term is ommited from the sum. Also, the symbol used in this case is the $\oplus$. I want to prove that $V=U_{1}\oplus ... \oplus U_{n} \iff \forall \ v \in V, \ \forall \ j = 1,...,n \ \exists! \ u_{j} \in U_{j}$ such that $v=u_{1}+...+u_{n}$. What I thought to do first for the direct implication $(\Rightarrow)$ was to use contradiction, i.e. Assume $V=U_{1}\oplus ... \oplus U_{n} \ and \ \exists \ v \in V, \ \exists \ j \in \\{1,...,n\\}$ such that $\nexists \ or \ \exists^{>1}$ $u_{j} \in U_{j}$ such that $v \neq u_{1}+...+u_{n}$. I found this statement a little bit confusing. Does anyone could prove this by using contradiction or other method? If I incorrectly stated the negative please correct me.
For this direction $\implies$, the existence of a representation $$v=u_1+\cdots +u_n$$ is clear. The issue is to prove the uniqueness. Now suppose you have two representations of the same vector: $$v=u_1+\cdots +u_n\quad\hbox{and}\quad v=w_1+\cdots +w_n$$ Then $$(u_1-w_1)+\cdots +(u_n-w_n)=0$$ Assume that for some $1\leq i \leq n$, $(u_i-w_i)\neq 0$. Then this non-zero vector is equal to the vector $$-\sum_{j\neq i} (u_j-w_j)$$ which means that $U_i$ intersects non-trivialy the sum of the rest of the $U_j$'s, contradictory to the definition of the direct sum. Therefore, if $V$ is a direct sum of the $U_i$'s, then the representation is unique.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "linear algebra, solution verification" }
Layout for navigation directions In my android app, I'd like to display directions similar to the example below. For now, I don't care about the icons and images or dropdown buttons, most importantly I want to display each part of the trip in a card-like layout with lists of directions. What would the layout xml for this would look like? Is this a CardView with a RecyclerView inside of it? ![enter image description here](
When you have multiple views that may repeat multiple times even contains nested items, the best way to have efficiency in runtime I think is using `RecyclerView`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, android layout, layout" }
Specify Python version in Microsoft Azure WebJob? How can I select which Python version to use for a WebJob on Microsoft Azure? When I do `print(sys.version)` I get `2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)]` Where can I specify another version? I would like to use Python 3 for some jobs. I have tried adding `runtime.txt` reading `python-3.4` to the root path, but it had no effect.
Also if you wanna run different python versions in the same site, you can always drop a `run.cmd` that calls the right version of python for you. They are installed in `D:\Python34` and `D:\Python27`
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "python, python 2.7, python 3.x, azure, azure webjobs" }
Can't upgrade iPad to the latest build of iOS4.2 I have upgraded my iPad to iOS4.2 (gold master 8C134) but I didn't upgrade to the second gold master 8C134b. Now that iOS4.2 has been made available on iTune, the gold master image has been removed off the developer account, but I am stuck in the 8C134 build of iOS4.2 iTune check for update doesn't recognize that I don't have the latest build. Any idea how to upgrade to 8C134b, thx
You can download the 4.2.1 image directly from Apple. They just don't make the link easy to find for some reason. I expected it to be in the developer portal. Silly me!
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "ipad, ios 4.2" }
Where to get Windows 7 RTM download? I hear people are using Windows 7 even before its released and liking it. Any ideas where I can get my copy?
The RTM version is only being distributed to OEMs and MSDN or TechNet subscribers. Windows 7 will be released in 3 days. On the 22th, this Thursday.
stackexchange-superuser
{ "answer_score": 6, "question_score": 1, "tags": "windows 7, download, rtm" }
Error access when I'm trying to make request not from dev environment So I basically have sharepoint asp.net page and button that does this copy operation System.IO.File.Copy("\\\\server.name\\folder\\folder\\123.txt", Server.MapPath("\\\\WebserverTempFileCopy\\123.txt"), true); The problem is if I do this from development environment it works okay, but if I try to do this from outside 403 FORBIDDEN error pops up, basically it can't reach "\\\server.name\folder\folder\123.txt" for some reason and I have no idea why. Request is made by web server, right? But it has access when I'm trying this from development environment, even if outside user is making request he also has access for that fileserver, so I have no idea where to search for error. I'm new with asp.net and sharepoint, so maybe this is simple and stupid question, but thanks anyway.
Okay, so the main problem was that server administrators gave access to file server to wrong identity that was running different server. It took me some time to figure that out. But that at first also didn't solve the problem. I found simple way to run that part of code that makes request to file server as app pool identity. SPSecurity.RunWithElevatedPrivileges(delegate() { //Code here });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, asp.net, sharepoint" }
WordPress nav menu no longer updating I have a WordPress site whose wp_nav_menu has stopped updating. It can still read the menu and display it; it's just no longer possible to add new menu items of any type or to rearrange the items. Upon saving, eventually the request will time out or return no information. I switched to the TwentyTen theme and disabled all plugins and that had no effect. It's still possible to publish new pages/posts, as well as edit existing ones. Even ajax functions in other parts of the admin (like widgets) work fine. Has anyone out there experienced this and if so, how did you correct it?
How many menu items do you have? WP sometimes has problems with large menus; it's a known bug that is being addressed < Try increasing the timeouts and memory allocation in php.ini, i.e.: max_execution_time = 90 max_input_time = 300 memory_limit = 64M
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "wordpress, navigation" }
How do I save multiple screenshots with same name in Selenium? So I'm trying to save a screenshot with the same name for example, "Screen" and then if it already exists, save as "Screen1" and "Screen2" and so on. This is my code: driver.get_screenshot_as_file("Screen.png")
Here you can find more information about it. You could use a while loop and check for every name (Screen1, Screen2, ...), whether it exists or not. A short example: import os.path i = 1 while True: fname = "Screen" + str(i) + ".png" if not os.path.isfile(fname): break i += 1 print(fname) You could also store the current `i` and use it when saving a screenshot, this might be more efficient than this approach.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, selenium, selenium webdriver" }
Finding the closest point on a plane in $\mathbb R^3$ to the origin given its parametric equations? I have a plane in $\mathbb R^3$ and I've found its parametric and plane equations. I thought of setting variables in the parametric equations to zero but, I keep getting different values for the parameters, so this is wrong. Here is what I have: $Plane Equations: x+3y+4z=8 $ Parametric Equations: $x = t +3s$ $y = t - 5s $ $z = 2-t+3s$ How do I find the closest point on this plane to the origin?
$x+3y+4z=8$ is your plane. So then we know that $[1,3,8]$ is perpendicular to the plane. We want this vector to go through the origin, so we can construe it as a parametrically given line: (x,y,z)=(0,0,0)+t(1,3,4)=(t,3t,4t) To make sure it is on the plane, substitute $$x=t$$ $$y=3t$$ $$z=4t$$ back into the original equation for the plane: $t+3(3t)+4(4t)=8$ $t=\frac{4}{13}$ Thus, $(x,y,z)=\frac{4}{13}\cdot[1,3,4]=(4/13,12/13,16/13)$ is the closest point to the origin.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "vector spaces, vectors" }
What is the best way for a database design with fixed number of contact persons? I am currently designing a database for a project. I'd like to normalize it and I have come across a question that I would like to ask in a larger group, especially with regard to previous experiences. About the situation: An organization has 0 to 4 contact partners. Of the four contact partners, two are on-site to the organization (local) and two are available throughout the country (global). On an input mask, a user can select which contact from the contacts table is so-called "local contact partner 1", "local contact partner 2", "global contact partner 1" etc., so the order (order, "1" or "2") is relevant. What would be the best way to structure the database? I have attached three examples, but please feel free to make other suggestions. ![3 Database Examples](
I would recommend The 3rd solution. At one day in the future the business will come up with an exception and state an organization can have 5 or more contacts. If the primary key of OrganiationContacts is organizationId+ContactId you also have the guarantee the same contact cannot be both local and global or defined twice as contact. The other structures cannot guarantee this and require additional validation logic.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, database, structure, database normalization" }
Memory Management in Activity using Intent.FLAG_ACTIVITY_REORDER_TO_FRONT and getApplicationContext()? I m using below code to start another activity in my application - **Intent itab = new Intent(getApplicationContext(), TabhostScreen.class); itab.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(itab);** how can i manage memory in this context because Activity resume each time when we call Intent.FLAG_ACTIVITY_REORDER_TO_FRONT. so how would we manage memory?????
We use Intent.FLAG_ACTIVITY_REORDER_TO_FRONT flag so that multiple instances of the same activity is not created and activity is brought to the front in same state without popping out other activities from the history stack. Memory management is not the concern here so far as android documents suggests. When you are rotating the device then your activity is recreated and using different layout is perfectly fine in fact it is a **good practice** in android. Hence memory requirement will increase. You can stop this behavior by fixing the screen orientation in the manifest file.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, memory management, android intent, memory leaks, android activity" }