INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Creating a blank copy of a SQL Server 2012 database on the same Instance I'm trying to determine the best way of creating a blank copy of a SQL Server 2012 database, renaming it & placing it on the same server instance. I could restore/rename a backup copy, and then delete all the data, but there are quite a few tables/views, stored procedures, triggers, etc. Are there any drawbacks with the "generate scripts for database objects" wizard? Just trying to figure out the most efficient way to create a blank copy & would appreciate anyone's experience/wisdom on the topic. I am running a SQL Server 2012 Enterprise edition. We have a database that our colleagues like, so we are planning to create a copy & populate with their data instead of our data.
Go to Object Explorer ,Right Click the database you want to create a blank copy of. Right Click --> Tasks --> Generate Scripts Select the entire Database, you also have the option to select specific objects, In advance option select **schema only**. !enter image description here I would prefer this method over any other, as Restoring a Copy of database and then deleting data means doing a lot of work which was never required to begin with. Backing up data that was never required, restoring unwanted data and then finally making sql server to delete it, a lot of unnecessary work. Another reason why scripts are better over other options, These scripts will use fresh pages to write all of this data. Imagine you having to write something on a brand new note book as compare to a note book where you had to erase first and then use it to write data on it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "sql, sql server, database, sql server 2012" }
Angular changing ng-class on click I am trying to change a class that I am creating based on a value that I get from json, and then change it if user cliks on it, but I am not getting that to work. This is my code in the controller: $scope.like = function(){ if ($scope.class === "ion-ios-heart-outline") $scope.class = "ion-heart"; else $scope.class = "ion-ios-heart-outline"; }; And the element in the view: <i ng-click="like()" ng-class="{ 'ion-heart' : article.like == 1, 'ion-ios-heart-outline' : article.like == 0}">
You are mixing `$scope.class` (which is never used in the view) and `ng-class`, so I am not entirely sure what you want to do. But I guess what you are looking for is this: $scope.article.like = 0; $scope.like = function() { $scope.article.like = $scope.article.like == 0 ? 1 : 0; }; Then the CSS classes will be changed based on whether the article was liked or not.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, angularjs" }
How to use substring and indexOf for a String with repeating characters? I have the following `String myString="city(Denver) AND state(Colorado)";` It has repeating "(" and ")"... How can I retrieve state name, i.e. Colorado. I tried the following: String state = myString.substring(myString.indexOf("state(")+1,myString.indexOf(")")); But it give `indexOutOfBoundException` Is there any way to specify that I need the second "(" in myString? I need the result: `String state = "Colorado";`
Use `lastIndexOf`. Also increase the initial offset to allow for the number of characters in the sub-string `state(`: String state = myString.substring(myString.indexOf("state(") + 6, myString.lastIndexOf(")"));
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 4, "tags": "java, string, substring, indexof" }
How to change the order of group by column in sp list view I have a calculated column created in one of the Sharepoint list, here is the formula: = IF(DaysDifference<0,"Overdue",IF(DaysDifference<=7," 7",IF(DaysDifference<=15,"15",IF(DaysDifference<=30,"30","Over 30")))) I have then added group by this column for a view, below is the screenshot: ![enter image description here]( ![enter image description here]( the return type of this calculated column is free text. Is it possible to change the group by column order? Currently its showing Overdue, Over 30, 30,15 and 7. How can it be changed to follow this order: Overdue, 7, 15, 30, Over 30? Is this possible to do? Please advise, thanks in advance.
The "group by" is text, so if the alphabetical order does not work for your data, you can add something that is alphabetical. (letters or spaces maybe) Option one, add a sorting prefix: (A. B. etc.) A. Overdue B. 7 C. 14 I.e. IF(DaysDifference<0,"A. Overdue",IF(DaysDifference<=7,"B. 7" ... Another option, add spaces (indent): (underlines typed below to represent spaces) ___Overdue __7 _15 _30 Over 30 I.e. IF(DaysDifference<0," Overdue",IF(DaysDifference<=7," 7" ...
stackexchange-sharepoint
{ "answer_score": 1, "question_score": 0, "tags": "sharepoint online, calculated column formula" }
What do you call a 'noun' with a (s) suffix e.g. parent(s)? Is there a term for use of a combined singular / plural like _parent(s)_? For example: > Do not assume there are two parents when you pen the letter regarding baby Bob; > use _____ instead. or > use the _____ approach instead? I am not asking if _parent(s)_ is good style - that is separate issue. I have seen a question asking how to add a possessive `'s` to it but that is separate problem. I googled for this but am not sure what to even search for.
Many sites refer to this convention as the **_parenthetical plural_**. For example, at the Grammarphobia Blog, the American Medical Association, and the Chicago Manual of Style. This site discusses the merit of "parenthetical plural," and points out that > _The Gregg Reference Manual_ calls them "plural endings in parentheses." You might also find them called **_optional plurals_**.
stackexchange-english
{ "answer_score": 7, "question_score": 4, "tags": "single word requests, parenthetical plural" }
Grouping by multiple coefficients Good day! I have an output equation that has a very large amount of coeff. `b(x,y)`, like so: 8*b(0,0) + 2*x*b(0,0) + 3*y*b(0,0) + 5*x*y*b(0,0) + 4*b(0,1) + 3*x*b(0,1) + ... I need to group by b, so each `b(x,y)` was seperate. I can `Collect[]` by `b(0,0)`, but what abut the other coeff.? I'm trying to get something like this: (8 + 2*x + 3*y + 5*x*y) * b(0,0) + (4 + 3*x + ... Any ideas about how to do this? To clarify: each `x,y` in `b(x,y)` is written as a Subscript. Not all `b(x,y)` have a "full" group.The grouping i'm trying to achieve will correspond to a cell in a matrix. The equation is a matrix row, and there are several equations which will form an equation group. I'm new to Wolfram, so any general advice is very welcome. Thank you all in advance!
Like this? expr = 8*Subscript[b, 0, 0] + 2*x*Subscript[b, 0, 0] - 3*y*Subscript[b, 0, 0] + 5*x*y*Subscript[b, 0, 0] - 4*Subscript[b, 0, 1] + 3*x*Subscript[b, 0, 1]; Collect[expr, _Subscript] > > (8 + 2 x - 3 y + 5 x y) Subscript[b, 0, 0] + (-4 + 3 x) Subscript[b, 0, 1] > ( `_Subscript` is the `Blank` pattern that matches any expression with head `Subscript`. )
stackexchange-mathematica
{ "answer_score": 4, "question_score": 0, "tags": "algebraic manipulation" }
Send ajax request on click event in backbone js Here's the code This is **model** var TodoItem = Backbone.Model.extend({ url: 'list.php', DeleteTabItem: function (child, parent) { jQuery.ajax({ url: 'delete.php', }); } }); This is **view** var TodoView = Backbone.View.extend({ el: '.entry-title', template: _.template(''), KeyPressEvent: function () { this.model.DeleteTabItem(); } }); Is this correct way of sending **ajax** request. Thanks in Advance
In backbone model, instead of url, use : `urlRoot`: "yoururl", Backbone.Model.extend({ urlRoot: 'list.php' }); `url` would be used in `collections` For sending data through view : this.model.save(sendData, { success, error }); where **sendData = { data preferably in json }** You will have to bind the model with your view like : var todoView = var TodoView(model:TodoItem);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "backbone.js, backbone model" }
Detect whether one Turing machine invokes another Given two Turing machines $M,M'$, is it possible to check whether $M$ invokes $M'$? In other words, is the following problem computable/decidable? Inputs: Turing machines $M,M'$ Question: Does $M$ ever invoke $M'$? Perhaps we can look whether $M$ includes the code of $M'$ in it? In a C program we can check whether a function `f` invokes a function `g`, right? Can we do this for Turing machines too?
The notion of "one machine invokes another" is ill-defined. To emphasize the point of @AbdousKamel, let us observe an even trickier example: function g(): do_something; And now: function f(): k = 0 while not "k encodes a proof of Riemann hypothesis": k = k + 1 "simulate the Turing machine encoded by k" In order to tell whether `f` "invokes" `g`, you have to: 1. Decide whether Riemann hypothesis is provable, and 2. Calculate whether the smallest `k` which encodes a proof of Riemann hypothesis also happens to encode a Turing machine whose behavior is equivalent to the behavior of `g`. Question: does `f` invoke `g`?
stackexchange-cs
{ "answer_score": 2, "question_score": 1, "tags": "turing machines, computability" }
How can we model intrinsic curvature? Can it only be done in Euclidean space? Doesn't Euclidean space only model extrinsic curvature?
No, Euclidian space is not necessary. You can "model" intrinsic curvature using the beautiful language of Riemannian geometry, whose great triumph was formulating a vocabulary that lets you talk about the curvature of a space without making reference to an extrinsic space in which the curved space is embedded: hence the term intrinsic. This is crucial to general relativity, since embedding a curved 4-space in flat Euclidean space requires that the Euclidean space be ten-dimensional, and dealing with that embedding would suck.
stackexchange-physics
{ "answer_score": 0, "question_score": 0, "tags": "general relativity, curvature" }
My signed .pkg file is not accepted I'm struggling with signing my installer to keep _Gatekeeper_ happy. ![enter image description here]( When building i sign the .pkg: productsign --sign "3rd Party Mac Developer Installer: GNXXXXXXXXXX (XXXXXXXXXXX)" UnsignedJaXXXXXXXXXX0.5.pkg JaXXXXXXXXXXt0.5.pkg using this certificate: ![enter image description here]( When checking with _pkgutil_ I can see that the file is signed: ![enter image description here]( However still _Gatekeeper_ is not happy. _spctl_ gives this result: ![enter image description here]( What am I missing? **Update** _spctl_ with verbose: ![enter image description here](
You're using a signing identity that can only be used for Mac App Store distribution. You cannot sign with that identity and test it on your own Mac before submitting it to the Mac App Store - it won't pass GateKeeper validation. If you want to create an installer for distribution outside the Mac App Store, you'll need to use a signing identity prefixed "Developer ID Installer".
stackexchange-apple
{ "answer_score": 6, "question_score": 4, "tags": "macos, install, certificate, gatekeeper, pkg" }
If I create a ServerSocket on Android without specifying an IP to bind to, is it safe to assume this port is unreachable via the cellular network? I'm using ServerSocket to create a listening port on Android, so that other clients in my local network can connect to it while the phone is providing a personal hotspot. I probably can't specify the IP of the personal hotspot interface, because there seems to be no reliable way to determine this IP on Android. Therefore I bind to all IPs by creating the ServerSocket without specifying an IP. Is it safe to assume that access to open ports is blocked by the cellular network's firewall?
> Is it safe to assume that access to open ports is blocked by the cellular network's firewall? Nothing in letting the system choose the port makes the port magically blocked by firewalls. There might not even be an explicit "cellular network's firewall" in the first place. There might be some implicit protection due to the use of CG-NAT in many mobile networks - see Why is NAT referred to as "the poor man's firewall"?. But this is not an actual requirement for mobile networks, so there might be some which don't do CG-NAT. Or it's only done for IPv4 due to the scarcity on IPv4 addresses but not for IPv6. And, like CBHacking commented: NAT or CG-NAT does not protect against attacks from devices which are inside the same network behind the NAT. In summary - it depends on the specific mobile provider. And it might change without notice unless it is an explicitly promised feature. Thus don't rely on it.
stackexchange-security
{ "answer_score": 2, "question_score": 0, "tags": "android, cellular" }
SQLite Exception near "from" I am just fetching data from my SQLite Database and it is saying that Syntax error near 'from' when compiling select from smss group by contactnumber. Here is my code: public ArrayList<Sms> fetchScreenedSms() { ArrayList<Sms> smsInbox = new ArrayList<Sms>(); String query_fetchSMS = "select from smss" + " group by contactnumber " + "\"" ; DBtableforNotSpam smsD = new DBtableforNotSpam(this); SQLiteDatabase dbw = smsD.getWritableDatabase(); I tried with this too but it still says the same: String query_fetchSMS = "select from " + "smss" + " group by contactnumber " + "\"" ; Please Guide me whats the issue here
Specify `columnName` or *(for all columns) String query_fetchSMS = "select * from smss group by contactnumber";
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "android, sqlite" }
Memory layout of union of different sized member? typedef union epoll_data { void *ptr; int fd; __uint32_t u32; __uint64_t u64; } epoll_data_t; Here `int` and `__uint32_t` are 4 bytes,while the others are 8 bytes. When we set `fd` to an `int`,does it lie on the first 4 bytes or the last 4 bytes,or does it depend on endianness? Some reason is appreciated.
It lies on the first 4 bytes. From the C99 standard §6.7.2.1/14 (§6.7.2.1/16 in C11 and C18): > The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit-field, then to the unit in which it resides), and vice versa. This implies that the address of all members of a union is the same.
stackexchange-stackoverflow
{ "answer_score": 40, "question_score": 25, "tags": "c, unions" }
python pdfpage.extract_words throws error I have this code in my project to get all the words from pdf. words = pdfPage.extract_words(0.5,0.5) which throws the below error: Cannot convert to Decimal. Thanks in advance.
Try to downgrade the Pdf-minder version. Since i had this same issue resolving by downgrading.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python 3.x, text extraction, python pdfkit" }
ASP.NET Authentication Here is my .config <authentication mode="Forms"> <forms loginUrl="~/LogOn" path="/"/> </authentication> <authorization> <deny users="?"/> </authorization> When I do that on IIS7 it's ok, but on IIS6... Under IIS7: * Browse /Home/ * Redirect to /LogOn (because anonymous) * Display /LogOn page It's OK, But under IIS6 * Browse /Home/ * Redirect to /LogOn (because anonymous) * Can't display /LogOn page because anonymous :( What is the solution?
You are denying anonymous users acces to your login page. Add to your web.config <location path="login.aspx"> <system.web> <authorization> <allow users="?"/> </authorization> </system.web> </location> substitute login.aspx with your login page.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net, asp.net mvc 2, web config" }
Algorithm for calculating a distance between 2 3-dimensional points? I have two 3-D points. Example: float[] point1 = new float[3] {1.3919023, 6.12837912, 10.391283}; float[] point2 = new float[3] {48.3818, 38.38182, 318.381823}; Anyone an idea for an algorithm to calculate the distance in float between the points?
The Euclidean distance between two 3D points is: float deltaX = x1 - x0; float deltaY = y1 - y0; float deltaZ = z1 - z0; float distance = (float) Math.Sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ); And in N dimensions (untested and vulnerable to overflow): float DistanceN(float[] first, float[] second) { var sum = first.Select((x, i) => (x - second[i]) * (x - second[i])).Sum(); return Math.Sqrt(sum); } **Edit:** I much prefer the `Zip` solution posted by dasblinkenlight below!
stackexchange-stackoverflow
{ "answer_score": 25, "question_score": 8, "tags": "c#" }
Find a particular solution for second order ODEs using undetermined coefficients method Match the appropriate form of the particular solution labelled A through J with the differential equations below. Enter K if all of the particular solutions are incorrect. $$y''-5y'-24y = 3xe^{2x}, (1)$$ $$y''-4y'+4y = -3xe^{2x}, (2)$$ $$y''-2y' = -8e^{2x}, (3)$$ $$y''-25y = -3x^3e^{2x}, (4)$$ $A. y_p = Ae^{2x}$ $B. y_p = Axe^{2x}$ $C. y_p = (Ax+B)e^{2x}$ $D. y_p = Ax^2e^{2x}$ $E. y_p = (Ax^2+Bx)e^{2x}$ $F. y_p = (Ax^2+Bx+C)e^{2x}$ $G. y_p = Ax^3e^{2x}$ $H. y_p = (Ax^3+Bx^2)e^{2x}$ $I. y_p = (Ax^3+Bx^2+Cx)e^{2x}$ $J. y_p = (Ax^3+Bx^2+Cx+D)e^{2x}$ K. None of the above I chose C for (1), G for (2), B for (3) and J for (4). But none of them are correct, can anyone help me here?
Let $a_ny^{(n)}+a_{n-1}y^{(n-1)}+\cdots+a_1y'+a_0y=Q(x)$ wherein $a_n\ne 0$ and $Q(x)\ne 0$ in an interval, say $I$. Let we take $y_c(x)$ as the general solution of the related homogeneous equation: $$a_ny^{(n)}+a_{n-1}y^{(n-1)}+\cdots+a_1y'+a_0y=0$$. Now if no term of $Q(x)$ is the same as a term in $y_c(x)$ then, $y_p(x)$ is constructed by a linear combination of all terms of $Q(x)$ and all its linearly independent derivatives. This means that if we have, for example $y_c(x)=C_1e^{ax}+C_2e^{bx}$ and $Q(x)=x^{t}e^{dx}$ such that $$a\ne b\neq d\ne a$$ then $$y_p(x)=A_tx^te^{dx}+A_{t-1}x^{t-1}+\cdots A_1xe^{dx}e^{dx}+A_0e^{dx}$$ It seems that for $4$ we can count on $J$.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "ordinary differential equations" }
MVC3 with Rhino mocks I am trying to use Rhino mocks in my MVC3 Project. Can someone provide me links how to start up? Thanks in Advance.
< would be a good start.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net mvc 3, rhino mocks" }
Поиск LIKE в PostgrSQL SELECT * FROM "main_user" WHERE ((UPPER("main_user"."bio"::text) LIKE UPPER('we'))) Есть такой код и он находит в ячейке био есть конкретный текст 'we' но есть одна проблема `bio: 'We'` `bio: 'We are Family'` В первом варианте алгоритм его находит но во втором нет Как мне сделать так чтоб он находил это слово и в ячейке био не с одним а с множеством слов но именно по слову а не по корневой основе Я знаю что есть %we% но они берут много мусора если будет допустим слово 'wear' он и его возьмет
Для того, чтобы найти точное слово "we" в поле bio, можно использовать регулярное выражение. Например, можно использовать следующее выражение: SELECT * FROM "main_user" WHERE ("main_user"."bio"::text ~* '\mwe\M') В этом запросе используется функция ~* (оператор "соответствует регулярному выражению"). Регулярное выражение \mwe\M означает "слово 'we'", где \m означает "начало слова", а \M означает "конец слова". Помимо этого, можно также использовать функцию split_part() для разбиения текста на слова и поиска нужного слова в массиве слов. Пример запроса может выглядеть так: SELECT * FROM "main_user" WHERE ('we' = any(string_to_array(split_part("main_user"."bio"::text, ' ', 2), ' '))) В этом запросе функция split_part() разбивает текст на слова, разделенные пробелами, а затем преобразует этот массив слов в строку
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "postgresql" }
iPhone sdk how to UIButton in UIToolbar? Is it possible to add an `UIButton` with `UIToolbar`? or we can use only `UIBarButtonItem`? If so how to add an `UIButton` in `UIToolbar`?
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; [btn setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal]; [btn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *barBackButton = [[UIBarButtonItem alloc] initWithCustomView:btn]; [toolBar setItems:[NSArray arrayWithObject:barBackButton]];
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "iphone, uibutton, uibarbuttonitem, uitoolbar" }
Polygon with dash-dot-dash border style I'm developing a WPF application. One of my requirements is to have polygon borders drawn with a dash-dot-dash style. Is there a way to accomplish that in the client side? So far I've tried: var graphic = new Graphic(); graphic.Symbol = new SimpleFillSymbol { BorderBrush = new SolidColorBrush(Color.FromArgb(255, 255, 0, 255)), BorderThickness = 5 }
You should define a CartographicLineSymbol with a custom DashArray. If you have adjacent polygons, I recommend you to first convert your polygons to lines because two adjacent polygons each have a borders and the patterns could overlap in a wrong way. Display those lines on top of polygons without outlines and the rendering will be as you want. Below is an illustration on the use of dashArray to create dash-dot-dash lines. ![enter image description here]( the "grammar" for this line would be 5,2,1,2 (stroke of 5 (=dash), gap of 2, stroke of 1 (=dot), gap of 2 )
stackexchange-gis
{ "answer_score": 1, "question_score": 1, "tags": "symbology, arcgis api wpf" }
iPhone SDK Simple Question Is it possible to add a UIActivityIndicatorView to the left side of a UITableViewCell? We're already using the right side of a UITableViewCell for a disclosure indicator. Thanks.
Sure. Just instantiate a UIActivityIndicatorView, give it a .frame that sets it where you want it, add it as a subview of cell.contentView, and call `startAnimating`. UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0,0,20,20)]; //or whatever--this will put it in the top left corner of the cell [cell.contentView addSubview:spinner] [spinner startAnimating]; [spinner release];
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "iphone, objective c, uitableview, uiactivityindicatorview" }
Regex for parsing version number How can I write a regex for parsing version numbers. I want to match numbers like: `1.000`, `1.0.00`, `1.0.0.000` but not integers `1`, `10`,`100`
I think you want something like this, (?:(\d+\.[.\d]*\d+)) OR (?:(\d+\.(?:\d+\.)*\d+)) DEMO >>> import re >>> str = 'foobar 1.000, 1.0.00, 1.0.0.000 10 100 foo bar foobar' >>> m = re.findall(r'(?:(\d+\.(?:\d+\.)*\d+))', str) >>> m ['1.000', '1.0.00', '1.0.0.000']
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, regex" }
Scala web frameworks' security I am choosing a Scala web framework. Among frameworks I am considering are Play, Scalatra and Lift. In the project I am preparing for, security is important. However, web security is a blurry subject for me, and I would like my framework to handle it to a reasonable extent. I seem to be drawn to Play. I am not asking what is the most secure framework (according to ads – Lift), but, rather, do Scala frameworks handle security for me, and how do they compare in that respect? I don't want to solely rely on my knowledge to make the web-app secure.
To answer my own question, I have to learn this stuff, no one is going to do it for me. There's OWASP cheatsheets; and also OWASP Enterprise Security API or ESAPI. ESAPI looks promising, though I haven't used it yet.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 3, "tags": "scala, playframework 2.0, lift, web frameworks, scalatra" }
SQL replace data in table1 from table2 Hello i have 2 tables in MySQL DB status id, name, date, status 1 server1 datum 0 2 server2 datum 999 3 server3 datum 999 4 server4 datum 0 cis id, ,url 0 img/offline.png 1 img/server1.png 2 img/server2.png 3 img/server3.png 4 img/server4.png 999 img/online.png i want to select id and status from status and i want to replace both server_id a and status with url from cis. But i dont know fi this is posible to do or do i need to create a third table for the online/ofline url? i want to join the tables so that the select returns as this id, status img/server1.png, img/offline.png img/server2.png, img/online.png img/server3.png, img/online.png img/server4.png, img/offline.png
According to your comments, you tried the following query: select s.id,s.name,s.date,s.status,c1.url as serverurl,c2.url as statusurl from status s left join cis c1 on s.id=c1.id left join cis c2 on s.status=c2.id This returns the correct resultset, but if I understand what you are looking for, you want this query: SELECT c1.url AS id, c2.url AS status FROM `status` s LEFT JOIN `cis` c1 ON s.id = c1.id LEFT JOIN `cis` c2 ON s.status = c2.id `c1.url` is aliased as `id` and `c2.url` is aliased as `status`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "mysql, sql, select, join" }
For SQL row count, is it more efficient to use PDO rowCount or count(*) AS? On my script, I have about 15 SQL queries just for counting the number of rows and displaying them to the user. What is the most efficient way? Should I use: $stmt=$cxn->prepare("SELECT id FROM items WHERE seller=?"); $stmt->execute(array($username)); echo $stmt->rowCount(); Or this: $stmt=$cxn->prepare("SELECT count(*) as count FROM items WHERE seller=?"); $stmt->execute(array($username)); while($row=$stmt->fetch(PDO::FETCH_ASSOC)) echo $row['count']; Thanks in advance.
The short answer is Count(*) will be faster. However, that assumes your not using the data, if you are going to select the data, and you want a count, then use your first method. ("SELECT id FROM items WHERE seller=?"); If you have an index on the table, then that will return almost instantly.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "php, mysql" }
Number of ways of choosing courses An economics student must choose 4 courses to attend in the forthcoming academic year. There are 8 courses offered by different lecturers. Prof. V. Lowmark: Microeconomics,Macroeconomics and Game theory. Prof. A. Greedman: Banking and Stock markets. Dr. T. Kantan: Asian economics. Dr. U. Workmore:Developing countries and Labor economics. Prof. Lowmark is the head of the department, so the student thinks it may be a good idea to take his course. However, his exams are very difficult, so the student does not want to take more than one of his courses. Given this, in how many ways can he choose the courses?
**Hint:** The student wishes to take four of the eight available economics courses. Since Professor Lowmark offers three of them and the student wishes to take exactly one course from Professor Lowmark, the student must choose one of the three courses offered by Professor Lowmark and three of the five courses offered by the other professors in the economics department.
stackexchange-math
{ "answer_score": 1, "question_score": -1, "tags": "combinatorics" }
CakeEmail::viewVars - CakePHP I am trying to set the variable $purchase to use in my email template per the following configuration: App::uses('CakeEmail', 'Network/Email'); $email = new CakeEmail(); $email->emailFormat('html'); $email->template('new_order_email', 'default'); $email->from(array('[email protected]' => 'A Great Site')); $email->to($this->request->data['email']); $email->subject('Order details'); $email->viewVars($purchase); $email->send(); But this doesn't work when I attempt to use the $purchase variable in the template. Instead, the email which is sent contains the following error: > Notice (8): Undefined variable: purchase [APP/View/Emails/html/new_order_email.ctp, line 2] This indicates that $purchase is not available, even though I did set that variable using the CakeEmail:viewVars(); function. Any ideas why I am having this problem?
the quickest and shortest way: $email->viewVars(compact('purchase')); it will pass the var `$purchase` as the same key 'purchase' into the email viewVars and is exactly what you need here. you can also quickly add more variables this way: $html = 'foo'; $url = '/my/url'; $email->viewVars(compact('purchase', 'html', 'url'));
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "email, cakephp, cakephp 2.0" }
.NET Portable - Calling .Select() on a string I am trying to call the `.Select()` Linq extension method on a string from within a PCL, but I'm unable to compile the project. Calling `.Select()` on a string from a separate, non-portable project is compilable. I can see that `.Select()` takes in `this IEnumerable<TSource> source`. The string (and String) types implement `IEnumerable` inside of the .NETPortable assembly, so why should `.Select()` be unavailable? Can the compiler not implicitly convert strings to character arrays with PCLs for some reason?
The compiler needs to implicitly convert a `string` to an `IEnumerable<char>`. Whether this works depends on the platform(s) you are targeting with the portable library and thus what subset of the .NET Framework is available. If you target .NET Framework 4 and for instance Xamarin, you have a different subset than if you were targeting .NET Framework 4.5.1 and Xamarin. In the former case, the compiler will reject an implicit cast from `string` to `IEnumerable<char>`, while in the latter case it is accepted. So the simple solution (if it is viable for you) would be to target .NET Framework 4.5.1 and higher. Otherwise, you may cast your string to a sequence of characters, e.g., using `.Cast<char>()`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c#, .net, string, linq, portable class library" }
Help with modeling I've been modeling the sentry turret from the Portal game and I'm struggling on creating a part of the mesh. Here's a small montage I made of what I want to do: ![The images in the top are reference and the bottom ones are mine]( I'd like to learn how to model it :D
A great modifier for getting objects to wrap around curved surfaces is the _Shrinkwrap_ modifier. Take a flat plane and apply the _Shrinkwrap_ modifier to it with the turret wall as a target. This essentially flattens it onto the inner wall of the turret. Take note, you will need to subdivide the plane so that the _Shrinkwrap_ modifier can bend the mesh. From there, you can add a small _Solidify_ modifier so that it sticks out a bit.
stackexchange-blender
{ "answer_score": 2, "question_score": -1, "tags": "modeling" }
How to bake a texture from shader nodes? The other one that I looked at is outdated, So I need to open up a new question, Anyways, I made a texture from shader nodes, And I want to convert it into a texture so I can use it on other things, (Basically an image I think) And I can't find a way to do it, I tried tutorials but it only gives me a blacked out square. (Also just a quick question, Can ignore if wanted, What's the different between material and textures?)
# TL;TR The baking of materials and textures are mostly the same with the exception that specular / meticallic values are mostly static in the end and act like fake tints in your baked texture. # How to bake properly * Have 2 or more UVs. * 1 for texturing, 1 for baking. # Setup #1 Have an extra Image Texture node + UV node to indicate which texture you wish to bake to. Likewise have the extra UV node be set to the UV that you wish to be used in the baking process, otherwise Blender defaults to the UV that you have selected in your `Properties Editor -> Object Data Properties` (mesh tab). ![enter image description here]( ### No specified UV node for baking - defaults to selected UV ![enter image description here]( # Setup #2 Having your material's roughness and/or metallic is also known to cause black areas if their values are set to a value _other_ then **0.0** or **1.0**.
stackexchange-blender
{ "answer_score": 1, "question_score": 1, "tags": "texturing, materials, texture baking" }
How to get the cpu utlization percentage for each user in ubuntu by a command I've typed this command to get the memory usage for each user : ps aux | awk 'NR>2{arr[$1]+=$6}END{for(i in arr) print i,arr[i]}' I want to know if there is a command or a way to get the cpu usage or in other words "cpu utilization percentage" for each user like the above command which its output : !enter image description here
I might be wrong, but isn't it just this ? ps aux | awk 'NR>2{arr[$1]+=$3}END{for(i in arr) print i,arr[i]}' The response is in % of CPU usage.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 1, "tags": "12.04, command line, cpu load" }
Удаление из БД SQLite записей старше 7 дней Не удаляются почему-то устаревшие записи. Что неправильно у меня, подскажите, пожалуйста: $db->query("DELETE FROM `property` WHERE strftime('%s',created_at)<(strftime('%s','now')-(3600*24*7))"); Мне нужно, чтобы при загрузке новых данных в БД одновременно удалялись записи старше 7 дней из таблицы property . Спасибо Я использую SQLite, там есть strftime. created_at - тип поля DATETIME
Заданное время относительно указанной даты в SQLite возвращает функция datetime() Записи старше 7 дней находятся и удаляются так: DELETE FROM property WHERE created_at < datetime('now','-7 day')
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, sqlite" }
React map - returning value how can I return just one element from an array from another file where element (let say it's `"2"`) is equal to id in that file import { AnotherFile } from './AnotherFile' const element = exFunc(element) const exFunc = (val) => { {AnotherFile.map((data) => data.id === parseInt(val) && return {data} )} } This is the other file with data: export const AnotherFile = [ { id: 1, text: 'Num 1', }, { id: 2, text: 'Num 2', }, { id: 3, text: 'Num 3', } ] Ps. More exactly i need a "text" value alert("The text is: " + <>text value of data with id=2 from AnotherFile<>)
**It doesn't work with`&&` like that in the function, you would need to do a proper logic block:** const exFunc = (val) => { AnotherFile.map((data) => { if (data.id === parseInt(val)) return { data }; }); };
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, reactjs" }
Short story about discovering planet inhabited by self-organising, metallic, swarming creatures The plot: explorers find a planet, it has lots of metallic structures that exhibit regularity and pattern, but apparently nothing living. The explorers feel very secure - they have lots of force-fields etc. to keep them safe. However they start disappearing, and it becomes clear a swarm of metallic creatures inhabit the planet that are somehow wiping peoples' minds. The story ends with most/all of the explorers dead - a hubris tale. Would love to find the story again, can't Google for clashes with plots of grey-goo stories/nano technology research!
This is almost certainly The Invincible by Stanislaw Lem. It's a short novel, not a short story. He didn't really use "Nanotech" (the bots were insect sized) in the way we think of it now, but the machines were self organizing, and quite scary.
stackexchange-scifi
{ "answer_score": 19, "question_score": 15, "tags": "story identification, aliens, space exploration" }
What kind of addition rule will be non-commutative? A linear vector space $\mathbb{V}$ is set of elements $|\psi\rangle,|\phi\rangle,|\chi\rangle...$, called vectors, defined on a field $\mathbb{F}$ of scalars $(a,b,c,...)$ such that it satisfy (among other properties) that for any two elements $|\psi\rangle,|\phi\rangle \in\mathbb{V}$, there exist a definite rule of addition such that $$|\phi\rangle +|\psi\rangle=|\psi\rangle +|\phi\rangle \in \mathbb{V}$$ My question are: 1. What kind of addition rule will be **non-commutative**? I want an example. 2. How can the associative law of addition fail? 3. What could be an example where $|\phi\rangle +|\psi\rangle$ does not belong to $\mathbb{V}$ but $|\phi\rangle,|\psi\rangle\in\mathbb{V}$?
Note that _a priori_ the symbol $+$ doesn't mean anything; it is just any operation that takes two inputs and produces an output. We usually use $+$ only for operations that are commutative and associative, so any $+$ that is not associative or commutative will not, intuitively, feel like an operation that deserves to be called $+$. 1-2) An easy example of an operation that is non-commutative and non-associative is subtraction of numbers. So if the symbol $+$ means $-$ (so, for example, "$5 + 2$" in this context will be the number 3), then it is not commutative: $$ 2 +1 = 1 \neq -1 = 1 + 2, $$ and it is not associative either; $$ (1 + 1) + 1 = -1 \neq 1 = 1 + (1 + 1). $$ 3) For example, you could have (stupidly) defined $V = \\{-1,0,1\\}$ and have $+$ be ordinary addition. Then $1 + 1 = 2 \notin V$.
stackexchange-math
{ "answer_score": 4, "question_score": 1, "tags": "linear algebra, vector spaces" }
Airdrop without Gas Fees I'm new to smart contracts. is it possible to credit ethereum addresses with ERC20 tokens? basically "write" the balance instead of airdropping them via transactions. asking because gas-fees are so high
You _could_ initialize your `_balances` mapping in the ERC20 contract with several addresses: < However, depending on how many addresses you want to airdrop to, you might end up exceeding the contract code size limit: < Also, note that initializing your `_balances` array will add to your deployment costs: What is the real price of deploying a contract on the Mainnet? In particular: > More bytecode means more storage, and each byte costs 200 gas. This adds up very quickly. and: > If the constructor requires a lot of computation to generate the bytecode, then it'll be extra expensive.
stackexchange-ethereum
{ "answer_score": 0, "question_score": 1, "tags": "airdrop" }
SVN Merge - Client or Server? When 2 users change the same file (in the same branch) and check their code into SVN, SVN will (after asking the second user to do an update) auto merge the files and try to resolve any conflicts. Does this merge process happen on the client or on the server? (more info: I am using Tortoise SVN 1.7.11 on the client, and the server version is 1.5.1, we recently had an auto-merge delete some data and I'm wondering if this is an issue with the code merge in Tortoise or the older server code)
This is a Tortoise SVN thing, and thus on the client. The SVN server will actually kick it back and tell you youre not up to date. Weird that tortoise does that... Doesnt seem like a feature anyone in their right mind would ever want...
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "svn, merge, tortoisesvn, svn merge, data loss" }
Laravel 4 - Require packages on Laravel install I looked around for an answer to this question, but couldn't find anything. Just wondering, is there a way to tell Composer to require additional packages during a laravel 4 installation? For example: If I want to always use the Entrust package in all my laravel projects, instead of having to require it every time I create a new laravel project, can I tell my Composer to also require the Entrust package when I run `composer create-project laravel/laravel --prefer-dist` Thanks
I'm not aware of such thing in Composer, but you can add `require` statement to the same command: `composer create-project laravel/laravel --prefer-dist ./ && composer require zizaco/entrust `
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "laravel, laravel 4, composer php, package" }
For which $n\in \mathbb N$ does $n^n$ end with a $3$ in its decimal form? > For which $n\in \mathbb N$ does $n^n$ end with a $3$ in its decimal form? I didn't really know where to go from here, but I thought I might be able to use that $n^n \equiv 3 \text{ (mod } 10)$ , $n^n \equiv 3 \text{ (mod } 5)$ and $n^n \equiv 1 \text{ (mod } 2)$. Since the $gcd(2,5)=1$ I thought I might be able to do something with the Chinese remainder theorem, but so far I'm not sure how. I'd prefer a hint over a full answer :) Thank you in advance!
You are correct : if $k \equiv 1 \mod 2$ and $k \equiv 3 \mod 5$ then $k \equiv 3 \mod 10$ must happen by CRT. Therefore, it is sufficient to find $n$ such that $n^n \equiv 3 \mod 5$ and is odd. Of course, $n^n$ is odd if and only if $n$ is odd. Additionally, $n^n$ now breaks into cases when we go into five. If $5$ divides $n$, of course $n^n$ can't end with $3$. Therefore, $n$ cannot be a multiple of $5$. Then, $n^4 \equiv 1 \mod 5$, by Fermat's theorem. Therefore, let $n \equiv k \mod 4$, $0 \leq k \leq 3$, then $n^n \equiv n^k \mod 5$. Finally, if $n \equiv l \mod 5$ then $n^n \equiv n^k \equiv l^k \mod 5$ ,where $0 \leq l < 5$. Now, there are not too many cases to check : only $k = 1$ or $3$ and $l = 1,2,3,4$ are to be checked. Can you finish?
stackexchange-math
{ "answer_score": 7, "question_score": 4, "tags": "number theory" }
About an order of a p-group I'm trying to show that if G is a Group, then $|G| = p^2 \Rightarrow G$ is abelian. The path I'm taking relies on supposing that $|Z(G)| = p$ and forming the quotient group $\overline{G} = G/Z(G)$. Then we got $\overline{G}$ as a cyclic group, because it has order p. $\overline{G}=<a.Z(G)>, \ a \in G$. By that way, on the texts I saw, it's said that I can assume every element in **$G$** is in the form of $(a^n)b$, $a \in G$ and $b \in Z(G)$. Why can I assume this? Thank you
**Proposition**. Let $G$ be a group of order $p^n$, with $p$ prime and $n \ge 1$. Then $Z(G) \ne \\{e\\}$. _Proof_. By contrapositive, suppose $Z(G)=\\{e\\}$; so, all the centralizers are proper subgroups of $G$ and have then order of the form $p^\alpha$ with $\alpha < n$. Therefore, the Class Equation reads: $$p^n=1+\sum_i p^{\beta_i}$$ where $\beta_i \ge 1, \forall i$. But then, $p \mid p^n-\sum_i p^{\beta_i}=1$: contradiction. $\quad \Box$ **Corollary**. Let $G$ be a group of order $p^2$, with $p$ prime. Then $G$ is abelian. _Proof_. By contrapositive, suppose $G$ non abelian; then, $\exists \tilde a \in C_G(\tilde a) \setminus Z(G)$, so that $Z(G) \lneq C_G(\tilde a) \le G$. By the Proposition, $|Z(G)|=p$ and $|C_G(\tilde a)|=p^2$, whence $C_G(\tilde a)=G$ and $\tilde a \in Z(G)$: contradiction. $\quad \Box$
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "group theory, p groups" }
Rails 4 issue with mysql database tables after upgrading from Rails 3.2 I have upgraded recently my app to Rails 4 (from Rails 3.2). But seems that the app doesn't find anymore some mysql tables, for example a table called `Accidents`. In the app I find this error: Mysql2::Error: Table 'gms.accidents' doesn't exist: SHOW FULL FIELDS FROM `accidents` Ok, it seems that the table doesn't exists anymore, then (seen that is in dev mode and there is no problem to reset the DB), I run in the terminal `rake db:schema:load`, but: -- create_table("accidents", {:force=>true}) rake aborted! Mysql2::Error: Tablespace for table '`gms`.`accidents`' exists. Please DISCARD the tablespace before IMPORT.: CREATE TABLE `accidents` [...] What happened? The table doesn't exists but exists?? Why the app doesn't find anymore some tables?
One option (not a fix but may let you move forward). If this is just a development or local database, drop the database manually and update the schema_migrations table and then rake:db migrate to recreate from scratch.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ruby on rails 3.2, rails activerecord, ruby on rails 4, mysql2, ruby 2.0" }
Add New column in pandas Ok so i have data something like ![enter image description here]( i want to add a new column in the end 'Drug_NAme' and the value should be the column name for example,in the picture, the value for cocaine says "Y", so the value in the newly added drug_name = 'Cocaine" Trying in Pandas python
You can use this simple pipeline: s = df.rename_axis('drugs', axis=1).stack() df.join(s[s.eq('Y')].reset_index(1)['drugs'] .groupby(level=0).apply(list)) Input: A B C D 0 Y N N Y 1 N N N N 2 N N N Y 3 Y N Y Y 4 Y Y Y N 5 Y N N Y Output: A B C D drugs 0 Y N N Y [A, D] 1 N N N N NaN 2 N N N Y [D] 3 Y N Y Y [A, C, D] 4 Y Y Y N [A, B, C] 5 Y N N Y [A, D]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, pandas" }
Display all rows of same value if either of row matches a where condition I have been sitting for so long on this! Sorry I'm pretty new to this. Do have a look at this image ![enter image description here]( My requirement is: If `BaseItem = APO_Product` I would like to show all the rows of `NLLLFLF02`. When all the rows that validate the `where` condition, I would like to delete the ones that don't match. I have been trying this for long but nothing has worked out to me. HELP!!. Table Name:`W93zE8Z8`. I would like this to be my output: ![enter image description here](
> If BaseItem = APO_Product I would like to show all the rows of NLLLFLF02. When all the rows that validate the where condition, I would like to delete the ones that don't match. It seems that you need in DELETE t1 FROM W93zE8Z8 t1 LEFT JOIN W93zE8Z8 t2 ON t1.GROUP_4 = t2.GROUP_4 AND t2.BaseItem = t2.APO_Product WHERE t2.GROUP_4 IS NULL
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, sql" }
How do I refer to the current directory in functions from the Python 'os' module? I want to use the function `os.listdir(path)` to get a list of files from the directory I'm running the script in, but how do I say the current directory in the "path" argument?
Use os.curdir, and then if you want a full path you can use other functions from os.path: import os print os.path.abspath(os.curdir)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "python, path, working directory" }
"Enter your passcode" without a passcode My iPhone 6 is running iOS 9.1 (13B143), not jailbroken. Installed one app, f.lux, which is sideloaded, everything else is from the App Store. Occasionally, about once per day, while charging or after unlocking the screen, the phone will present the "Enter your passcode" screen. _Just to be clear: I have never set a passcode, yes I know the "skip" step during upgrades, I do not have roommates or other people touching my phone, I do not use Touch ID or Apple Pay, and I have never set a passcode._ The passcode screen includes a full QWERTY keyboard, not the digits one. And entering anything in there will just shake the screen (incorrect passcode). I have not attempted experimenting with 4 or more incorrect attempts in a row. The workaround is to simply lock and unlock the screen once or twice and then slide to unlock. This method will unlock the phone without a password 100% of the time. Has anyone seen this before and can it be cured?
It's an issue of f.lux, but it seems there's no solution for the problem. And sadly I don't think this issue will be patched soon as Apple stopped f.lux team developing the app for iOS.
stackexchange-apple
{ "answer_score": 2, "question_score": 3, "tags": "iphone, ios, password" }
Casting from Object[] to String[] gives a ClassCastException The `getStrings()` method is giving me a `ClassCastException`. Can anyone tell me how I should get the model? Thanks! public class HW3model extends DefaultListModel<String> { public HW3model() { super(); } public void addString(String string) { addElement(string); } /** * Get the array of strings in the model. * @return */ public String[] getStrings() { return (String[])this.toArray(); } }
The value returned by `toArray` is an `Object` array. That is, they've be declared as `Object[]`, not `String[]`, then returned back via a `Object[]`. This means you could never case it to `String` array, it's simply invalid. You're going to have to copy the values yourself...for example public String[] getStrings() Object[] oValues= toArray(); String[] sValues = new String[oValues.length]; for (int index = 0; index < oValues.length; index++) { sValues[index] = oValues[index].toString(); } return sValues; }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "java, swing, java 7, jogl" }
Beacon heading calucation I am planning to create the indoor navigation system. It will provide the shortest path to user from source to destination. Suppose I know all beacons location. Is that possible to calculate user facing direction by a set of beacons?
Sorry, this is not possible. **Off the shelf beacons are omnidirectional transmitters and mobile phones are omnidirectional receivers. There is no way to determine directionality of the signal.** The good news is that phones have two other ways of getting heading information -- the compass and a velocity vector. The compass is the general approach if you are standing still. If you are in motion, just calculate a vector between the last known location and the current location to get the heading.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ibeacon, beacon, indoor positioning system" }
Do I need an "it" in this sentence? > The wrappers can be used to gather information from similar websites and integrate **[it]** into an XML document. Does _integrate_ necessarily need to be followed by "it" in this sentence?
You definitely need "it". > The wrappers can be used to gather information from similar websites and integrate **it** into an XML document. _The wrappers gather information from websites and integrate **the information** into the XML document._ The implications otherwise are: > The wrappers can be used to gather information from similar websites and integrate into an XML document. _The wrappers gather information from websites and integrate **themselves (i.e. the wrappers)** into the XML document._ > The wrappers can be used to gather information from similar websites and integrate **them** into an XML document. _The wrappers gather information from websites and integrate **the websites** into the XML document._
stackexchange-ell
{ "answer_score": 1, "question_score": 0, "tags": "pronouns, syntax, ellipsis" }
How its corrected apply the Newton Rhapson metod? Im looking to apply the Newton-Rhapson method to this function: $F(t)=0.5-e^{-2t}(1+2t)$ and the derivative $F'(t)=4te^{-2t}$ but I dont understand how this is get, I did this: $F(t)=0.5-e^{-2t}-2te^{-2t}$ and $F'(t)=4te^{-2t}$ but the system isnt the same, while the book has $t_n=t_0-\displaystyle\frac{e^{2t}}{8t}+\displaystyle\frac{1+2t}{4t}$ I have $t_n=t_0-\displaystyle\frac{0.5-e^{-2t}-2te^{-2t}}{4te^{-2t}}$ It is the same or it needs to be simplified? Thanks in advance!
# Update Ok, thanks for say, I havent seen why, I ever started using partial fractions..but it has no sense. Said that, this is what is done: $\displaystyle\frac{0.5-e^{-2t}-2te^{-2t}}{4te^{-2t}}$ $\displaystyle\frac{e^{2t}}{e^{2t}}$ $=\displaystyle\frac{0.5e^{2t}-1-2t}{4t}$ $=\displaystyle\frac{0.5e^{2t}-(1+2t)}{4t}=\displaystyle\frac{0.5e^{2t}}{4t}-\displaystyle\frac{1+2t}{4t}$ and voilá!. Thanks a lot!
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "calculus" }
Number constraints in JSON Schema Validation I am working of JSON Schema Validation. I wanted to know if it is possible to impose number constraints, and if it is possible, how. For example: { "$schema": " "properties": { "birthYear": { "type":"number" }, "deathYear": { "type":"number" }, "name": { "type":"string" } } } I want to do something like this: birthYear <= deathYear How can I do this? Is there a specific keyword for constraints like these? Thank you very much. João
JSON Schema does not support constraints that refer to other properties. See 5.1. Validation keywords for numeric instances (number and integer) for what is possible.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "json, numbers, constraints, jsonschema" }
Create an intro screen for iOS app I want to create an intro screen for my app. This will be around 5 pages of intro and can have animated images on it. Something very similar to Box app intro screen. !enter image description here !enter image description here So question is does IOS provides any specific view controller for this kind of intro? If not should I use uiview controller to show on first load and somehow keep a track. What are these actually called in programming term? TIA
No. You can save status by NSUserDefault. There are some open source that can help you build intro quickly. < <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ios" }
Tramp file encoding for Unix I have managed to setup Tramp to connect to a remote Solaris machine from a Windows machine using plink, which is very nice. (setq tramp-default-user "Beginner" tramp-default-host "the_host" tramp-default-method "plink") But now I have a host of new problems, which I would assume to be related to the file encoding from the tramp upload: For example I have edited the .profile and now I get strange error messages like $>. .profile bash: $'\r': command not found How can I configure tramp to format files in a Solaris-friendly way? * * * Edit: Having unix-encoding the default solves the issue for me (prefer-coding-system 'utf-8-unix)
Usually, Tramp shall respect encoding of existing files. For new files, you could set the encoding via `C-x RET f utf-8-unix RET`. You can choose also another coding system, the important point is to append the `-unix`suffix. Read also the Emacs manual about coding systems.
stackexchange-emacs
{ "answer_score": 3, "question_score": 2, "tags": "tramp, newlines" }
copying ranges from workbooks (without folder path version) I've recently been looking for ways to speed up copying data from one worksheet to another. And I came across this nice piece of code (however this was posted in 2013). Could you please help? I don't want to specify any path to workbooks (like in the example below). I have both worksheets open and would like to address them by filename. I've tried changing "workbooks.open" to "window("xxx").activate" but that doesn't work. thank you! Sub foo() Dim x As Workbook Dim y As Workbook '## Open both workbooks first: Set x = Workbooks.Open(" path to copying book ") Set y = Workbooks.Open(" path to destination book ") x.Sheets("name of copying sheet").Range("A1").Copy y.Sheets("sheetname").Range("A1").PasteSpecial End Sub
Sub foo() Dim x As Workbook Dim y As Workbook 'Replace the text between the "" with the exact name of the workbook Set x = Workbooks("ActualNameOfWorkBook.xls") Set y = Workbooks("ActualNameOfOtherWorkBook.xls") x.Sheets("name of copying sheet").Range("A1").Copy y.Sheets("sheetname").Range("A1").PasteSpecial End Sub
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "vba, excel" }
Is it possible to update a cached file from the android device w/o removing the app? I found out that the only way to run my updated preferences.xml file on the app was to remove the app from the device before running it again. Before that I tried: * rebuilding * cleaning * File->Invalidate cache / restart * delete ~/.gradle/cache/ * delete project/.gradle * restarting my machine and it would still run the old version. Is it possible to automate this? Or at least make android studio un-cache the files that were edited? Android Studio 1.5.1
You can do it just Clear data in the app setting page. Yes you can automate it by running: adb shell pm clear my.wonderful.app.package There is also an IDEA plugin that does this for you.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, caching, android studio, sharedpreferences" }
Calculate the number of identical routes and apply in another function I am doing a lab and faced with such a task: > Identify stages of the routes with the maximum length, the route with the largest number of tourists that went through it I wrote this code, but somehow it does not work correctly. SELECT Max(Stage.Length) FROM ( Route INNER JOIN Stage ON Route.id = Stage.route ) INNER JOIN Travel ON Route.id = Travel.Route WHERE Stage.route = (SELECT `Travel.route` FROM `Travel` GROUP BY `Travel.Route` HAVING count(*)>1);
SELECT Max(Етап.Довжина) AS Выражение1 FROM (Маршрут INNER JOIN Етап ON Маршрут.id = Етап.Маршрут) INNER JOIN Подоріж ON Маршрут.id = Подоріж.Маршрут WHERE (((Етап.Маршрут) In (SELECT t.Маршрут FROM Подоріж t GROUP BY t.Маршрут HAVING count(*)>1)));
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, ms access" }
Connection problems on Netgear DG834v4 ADSL modem I can't get a connection on this device using my client's ISP login, nor my ADSL login I use at home. It is syncing nicely and I have a solid DSL light, but a red Internet light for either login. I suspect something more than just the login is faulty. Any ideas?
I've since found out that the ADSL Setting: Multiplexing Mode was incorrectly set to "VC-BASED" (default), when "LLC-BASED" was the required setting. Changing that and rebooting the modem worked fine.
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "modem, adsl" }
How to groupby and sum a criteria I have a dataframe as below FAMILY TYPE REMARKS A A1 Valid A A1 Invalid A A1 Invalid A B2 Invalid A B2 Valid A B2 Valid How should I use `groupby` to make it look like FAMILY TYPE VALID INVALID A A1 1 2 A B2 2 1 I tried df['VALID'] = df.groupby('TYPE')['REMARKS'].apply(lambda remark: remark == 'Valid') but the result is not grouped into 2 rows, how can I do that?
We do `crosstab` \+ `reset_index` , it will count by two column FAMILY and TYPE over REMARKS df=pd.crosstab([df.FAMILY, df.TYPE], df.REMARKS).reset_index()
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, pandas" }
How to solve this simple problem So my younger brother asked me to solve a simple problem, but I'm not sure how to solve this. Any help would be much appreciated. $$a^3 - 1/ a^3 = 4. $$ Prove that $$a - 1/a = 1$$
Using $$\displaystyle \left(a-\frac{1}{a}\right)^3=\left(a^3-\frac{1}{a^3}\right)-3\cdot a\cdot \frac{1}{a}\left(a-\frac{1}{a}\right)$$ So we get $$\displaystyle \left(a-\frac{1}{a}\right)^3=4-3\displaystyle \left(a-\frac{1}{a}\right)\;,$$ Now Put $\displaystyle \left(a-\frac{1}{a}\right)=x$ So we get $$\displaystyle x^3=4-3x\Rightarrow x^3+3x-4=0\Rightarrow (x-1)\cdot (x^2+x+4)=0$$ So we get $x=1$ or $\displaystyle x^2+x+4 =0\Rightarrow x=\frac{-1\pm \sqrt{1-16}}{2}$ (No real values of $x$)
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "algebra precalculus" }
Contact form. Message limit I have form on my website which is contact form. I am using ReCaptcha on that. The form just sending email, no records to data base. So my question is should i put character limit on that message?
It's always a good idea to put limits on input fields. For example you could decorate the property on your view model which is bound to the message with the `StringLength` attribute to enforce validation. [StringLength(1000, ErrorMessage = "The message must be at most {1} characters long.")] [AllowHtml] public string Message { get; set; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "asp.net mvc 3" }
str.contains to match entire string - Python I am trying to check whether a certain list includes elements of another list. I am using the following line of code: check = df_1['website'].str.contains(df_2['website'].tolist()[i]) The problem that I am facing now is that I receive false positives, if the first df partially includes the strings in the second one. For example I am looking to find if the following string in df_2['website'] is contained in df_1['website']: > sample_text_to_check Since df_1['website'] contains the following string: > text_to_check It results in a positive match. I would like to check for exact matches only (i.e. the entire string is matched and not only some letters within it. How can I do that? The lists is 200k lines long and contains many different strings.
You could just place `^` and `$` boundary markers around the string: check = df_1['website'].str.contains(r'^' + df_2['website'].tolist()[i] + r'$')
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python" }
Is there a specific engineering technology/design used to replicate data across different database vendors? I have a client which has a number of websites running on a number of different databases and database vendors from Oracle to SQL server to MySQL. The databases do share some information, notably member names and contact information, etc. Due to time constraints we do not have time to merge all the data into one single database and all all sites run from the one database. So instead the mid-term solution (2-3 years) is to synchronize this data across all the databases. This would include: inserts, updates and deletes. Is there a particular technology that will provide a solution. I'm not necessarily looking for a vendor's tool, but more of an engineering practice, design pattern that provides the solution from a solutions architect's level. If this does even exist.
First, you need to be aware. Your problem is not "database replication". It is table replication and sharing. Given a diversity of vendors, you will want to write custom code yourself, using "basic" SQL. In particular, you do not want to get into a situation where different versions of databases are suddenly incompatible, so your complex heterogeneous solution no longer works. I would strongly suggest that you separate out the shared information into a separate database. All the vendors you mention support multiple databases on a single server. Separating the common information from the rest will make it easier to maintain this data and to propagate changes. It might also open up the ability to use built-in database replication for the shared data. And, you might even find that a cloud based solution can eventually solve the replication problem, by having all requests go to a central database.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "database, replication, database replication" }
ASP.net webpages for multi Language support in caption texts I am new for the ASP.net. I have to build the web pages that will support Marathi language captions. I am using DIV tag for viewing the text in English in .aspx file. Now these text is need to be replaced by Marathi text. Please guide how can i do that. Thank you.
Resource files (.resx) may help you. Store all texts in resource files, and categorize them for each language (for instance, on folder for each language). Suppose you have a folder "en" and in that folder a resource file "myResourceFile.resx". Then you can read them as follows: HttpContext.GetGlobalResourceObject("en/myResourceFile", "myDivText");
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "asp.net" }
Getting warnings for implicit conversion overflow from unsigned to signed Consider the following problematic code: #include <iostream> void foo(int64_t y) { std::cout << y << "\n"; } int main() { uint64_t x = 14400000000000000000ull; foo(x); } Typically prints `-4046744073709551616`. How can one get the compiler to help with this type of conversion/overflow issue? I have tried the following: g++ -g overflow.cpp -fsanitize=undefined -Wall -Wextra -pedantic -Wconversion -Wconversion clang++ -g overflow.cpp -fsanitize=undefined,integer,implicit-conversion -Wall -Wextra -pedantic None of which gives any compile- or run-time warning. (clang version 7.0.0, gcc version 8.2.1)
The issue here is that `-Wconversion` is only going to warn if the value, when cast back to the source type, may not be the same type. For example if `foo` were to take an `int` instead then `-Wconversion` will issue a warning because it is possible that you can't cast the value in the `int` back to the original `uint64_t` value. If we have uint64_t u = some_value; int64_t s = static_cast<int64_t>(u); uint64_t check = static_cast<uint64_t>(s) then `check == u` will always be true (so long as `int64_t` is also two's compliment) so `-Wconversion` will not issue a warning because we get the source value back. What you'll need in this case is -Wsign-conversion which will warning you that the signs mismatch.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "c++, gcc, clang, overflow, implicit conversion" }
Expo stuck on "Config syncing" while ejecting to expokit While trying to eject a project from expokit, it won't finish and get's stuck at `config syncing` for over an hour. ![enter image description here]( This also happens when I create a new project with expo and then run `expo run:android`
I solved below step. * * * remove files for new feeling. rm -rf android rm -rf node_modules rm yarn.lock rm package-lock.json * * * update node. I used nvm. * * * npm uninstall -g sharp-cli yarn install * * *
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 5, "tags": "react native, expo" }
Unlocking a vote flaw On Stack Overflow when you vote (up/down) after 15 minutes or so your vote gets locked in, and it's only through an edit that you would be able to undo your vote. Just now I downvoted a a question and, after the OP elaborated, I felt my downvote was not fair and I wanted to undo it, so I forced a silly edit on the question and was able to undo the vote. Is this OK? I feel it's too cheap or not productive; I feel that a user who has voted on a post revision should not be counted, it should be only the post owner or anyone who has not voted on the post.
If it required the OP elaborating on the question before you felt it didn't need a downvote, then that information that changed your mind is what should have been edited into the post before your downvote was removed. That's a perfect example of exactly how the system is supposed to work - if the question didn't make sense to you when you read it, then a downvote is perfectly appropriate until the asker **edits** to make their question clear. There's no reason to change this system.
stackexchange-meta_stackoverflow
{ "answer_score": 16, "question_score": -8, "tags": "discussion, feature request, bug, edits, voting" }
Does Aurelia provide any kind of Dirty indicator based on the original value of the property I have an edit form and I want the Save button to be disabled until an edit is made to one of the properties bound to an input or select element. However if the user edits the text back to the original value, the form should no longer be considered Dirty. Example: 1. Original value: "Test" -- Not Dirty 2. User edits input and changes value to: "Test 2" -- Dirty 3. User edits input again and changes value back to "Test" -- Not Dirty I saw this post that describes how to create a dirtyBindingBehavior, but it only compares the new value to what was there previously -- in which case, line 3 above would result in still listing the form as Dirty since it would be comparing the old value of "Test 2" against the new value of "Test". Any ideas on how to accomplish this?
You just have to make a copy of the object and create a getter property that compares the old-object with the new-object (use `@computedFrom` to avoid dirty-checking). For instance: import {computedFrom} from 'aurelia-framework'; export class App { oldModel = new Model(); newModel = deepClone(this.oldModel); @computedFrom('newModel.name', 'newModel.surname') get hasChanged() { return !isEqual(this.oldModel, this.newModel); } } function deepClone(obj) { return JSON.parse(JSON.stringify(obj));; //use Object.assign({}, obj) if you don't need a deep clone } function isEqual(obj1, obj2) { return JSON.stringify(obj1) === JSON.stringify(obj2); } class Model { //something from database; name = 'John'; surname = 'Doe'; } Running Example <
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "aurelia" }
Is there a line editor for Windows (like Edlin, but better) The first interactive computer I used (in 1972) was made by Prime. The only editor provided was a line editor, and despite the interface it was a powerful tool. You could do things like: t f"hello";n3;p;* which translates as "go to the top of the file, find the string 'hello', move down 3 lines, print the line to the console, repeat until the end of the file". I realise this is the sort of thing that can be done with scripts, but my favourite editor doesn't have scripting, and I regularly encounter situations where the old Prime editor would be handy. Does such a thing exist?
You could use `Vim` or `gVim` in Windows as well. Its history dates back to `ed`, which was the original Unix text editor. `ed` was used in a time when it was still common to print out source code onto pieces of paper. Computers were slow, they could easily be outpaced by quick typists. Therefore it was necessary to be very efficient when editing. This efficiency remained through all of `ed`s successors (em, en, ex, vi, vim/gvim, neovim). In Vim, you would enter `gg/hello<Enter>3j:echom(getline('.'))<Enter>` _(I don't quite understand why you would want to output text to a console you are already in)_ '. There are a ton of other commands, even a whole grammar to achieve almost exactly what you want with only two or three keypresses. Just head over to Youtube and watch some videos on Vim or try it yourself by installing it! A good way to start vim is installing it and then run `vimtutor`.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "windows, command line, text editors" }
How to create a text box in powerpoint of attached design I am trying to create the following text box in power point. Any idea how to approach this? ![enter image description here]( Basically I need text boxes with left border color and a strong padding between boxes. I was trying to use tables but wasn't successful.
I think you need to think more creatively while using PowerPoint. I would use shapes to draw a square and then a green line on the left side of the square then I can draw a textbox inside it. Then while holding ctrl, right click on all three of these objects and then push ctrl+v on where ever you like to have it again. I usually create one slide full of these objects that I know I would want to duplicate constantly. The sample: sample design Selected multiple items: selected items I hope you find this helpful!
stackexchange-superuser
{ "answer_score": 2, "question_score": 0, "tags": "microsoft powerpoint" }
Getting value of PHYS_OFFSET in ARM linux user space I have an embedded linux system running on cortexA8.I understand the kernel symbol PHYS_OFFSET represents the physical start address of RAM < I need the value of this symbol in user space for some validation purpose in some shell script that runs after kernel has booted up. The /proc filesystem doesnt have this info. Pls let me know if I can get this value by some means.
You can try to utilize I/O memory map by reading `/proc/iomem` which should tell about `System RAM` \- all address in `iomem` is real / physical addresses. This is from my Android phone which has a 1GB ram (0xbfffffff - 0x80000000). $cat /proc/iomem ... 80200000-88cfffff : System RAM 80300000-80c708cf : Kernel text 80d00000-80fb1dcb : Kernel data 88d00000-88d00fff : ramdumpinfo 88d01000-88d04fff : amsslog 88de0000-88dfffff : ram_console 90000000-ab4fffff : System RAM b9a02000-bfffffff : System RAM You somehow need to convert the range specified in **System RAM** to what you need.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "linux, embedded, arm" }
jqGrid noticeably slower in IE We've noticed that the jqGrid sort/pagination performance is noticeably slower in IE vs FFox and Chrome. Is this just 'how it is' or are there any perf improvements that can be applied?
It seems to me that the main problem why jqGrid could be slower in IE is that JavaScript in IE is slower as in other browsers. So jQuery and jqGrid must work solwer. See < for example. You can find much more more ricent tests about the same subject.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "internet explorer, jqgrid" }
Accessing GridView Cells Value I am trying to access the integer value of the first cell but I'm getting this error: > Unable to cast object of type 'System.Web.UI.WebControls.DataControlFieldCell' to type 'System.IConvertible'. And the value i have stored in that cell is an ID like 810 My Code int myID = Convert.ToInt32(GridView1.Rows[rowIndex].Cells[0]);
`Cells[0]` returns a `DataControlFieldCell` object, not the cell's value. Use the cell's `Text` property.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "c#, asp.net, gridview" }
What type of auth security implements Odoo 10 I am new in Odoo, and I don't have much knowledge of securities. I am reading about the authentication and authorization of OAuth and OpenID Connect for APIs. I like to implement some type of security in my Odoo API or know what type of security Odoo implements for its API. I look in the Odoo documentation but I can't find what kind of authentication security Odoo implements, I only found that it implements the XMLRPC protocol. I would like how to implement security in the Odoo API.
From Odoo docs: > The authentication itself is done through the `authenticate` function and returns a user identifier (`uid`) used in authenticated calls instead of the login. > > Calling methods > > The second endpoint is `xmlrpc/2/object`, is used to call methods of odoo models via the `execute_kw` RPC function. Each call to `execute_kw` takes the following parameters: the database to use, a string the user id (retrieved through authenticate), an integer the user’s password, a string ... Translation: they do not implement an industry-standard protocol such as OpenID Connect for authorizing API calls .
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "security, authentication, odoo, odoo 10" }
Using a loop to improve jquery code How can I using a loop to improve this jquery code? $.getJSON("@Url.Action("GetPainel", "Home")", {}, function(data) { var json = data; var PieData = [{ value: data[0].value, color: data[0].color, highlight: data[0].highlight, label: data[0].label },{ value: data[1].value, color: data[1].color, highlight: data[1].highlight, label: data[1].label }];
You don't event need a loop**, you can just use `map()` to build a new array of objects from the one retrieved from your AJAX request: $.getJSON("@Url.Action("GetPainel", "Home")", function(data) { var pieData = data.map(function(o) { return { value: o.value, color: o.color, highlight: o.highlight, label: o.label } } // work with pieData here... }); ** I mean _explicit_ loop. I realise that `map()` loops internally.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "jquery, loops, getjson" }
React-router issues with deploying github pages, with create-react-app I am having the hardest time deploying a simple react application to github pages. You move one file to a wrong directory and it throws the entire process off. What do I do once I run npm run build? That puts all my files into a build folder, but the browser still keeps giving me 404 errors, thinking that anything typed after the initial url route's "/" is looking for an actual file from a server. I just want to use whatever comes after the / as routes that I set up in my React Router... :(
Create-React-App has a detailed documentation on how to deploy your build to Github Pages and Heroku. You can read it here. Your specific issue is covered in "Notes on client-side routing" section.
stackexchange-stackoverflow
{ "answer_score": 23, "question_score": 17, "tags": "reactjs, webpack, react router, http status code 404, github pages" }
Is it possible to share users between a Drupal 6.x and Open Atrium database, based on organic groups or CiviCRM smart groups? I use Drupal with CiviCRM for our nonprofit's public site and CRM database, and Open Atrium for the intranet. My goal is to either sync or share specific users from the public site to the intranet, to allow single sign-on. However, only users who are part of a specific CiviCRM smart group (volunteers) should be shared/synced. I could use the module to sync CiviCRM groups with Drupal organic groups if that would make this task easier. Any thoughts?
Usually, the Domain Access module is used for synching users and whatnot, but your requirement that only certain users be synched throws a wrench into that setup. Therefore, I'd recommend that you either: * Sort through that module's documentation to see if it provides any hooks so that you can filter down the user list, and if not... * Just look at how that module does its heavy lifting and write a custom module to do the same but only with a limited set of users.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "drupal, civicrm, organic groups, open atrium" }
What are the tools to draw icon for winform application? I'm new to programming and to winform. I want to create an icon for my winform application. What are the common tools to create icon for winform?
Once I had worked in 3d animation field for few years. So I am pretty hands on with Adobe Photoshop and in general I use Photoshop to create icons for me. Its pretty simple and user friendly software for basic needs. Just create and export the icon in desired size. But its a paid software. If you wish to work on a free software, one can go for Gimp editor. But honestly i have never used it. Hope it helps.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "c#, .net, vb.net, winforms, icons" }
VSCode: Quick open using directory path I know in VSCode you can use `Ctrl+P` to quick open a file, though it only seems to work for file names. That's not really useful for large python projects when every directory has `__init__.py` files. Is there any way I can quick open files by typing in `directory/__init__.py` to target files more specifically? Sublime Text includes this functionality so it seems strange that VSCode would exclude this.
Figured out the issue. Seems the parent folder names are excluded. For example, if I add a folder named `directory` to the project, I can't search using `directory/folder/filename`, but only `folder/filename`. Still not very useful multiple directories in project with similar file structures.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "visual studio code" }
Reading \r (carriage return) vs \n (newline) from console with getc? I'm writing a function that basically waits for the user to hit "enter" and then does something. What I've found that works when testing is the below: #include <stdio.h> int main() { int x = getc(stdin); if (x == '\n') { printf("carriage return"); printf("\n"); } else { printf("missed it"); printf("\n"); } } The question I have, and what I tried at first was to do: `if (x == '\r')` but in testing, the program didn't catch me hitting enter. The `'\n'` seems to correspond to me hitting enter from the console. Can someone explain the difference? Also, to verify, writing it as `if... == "\n"` would mean the character string literal? i.e. the user would literally have to enter `"\n"` from the console, correct?
`\n` is the newline character, while `\r` is the carriage return. They differ in what uses them. Windows uses `\r\n` to signify the enter key was pressed, while Linux and Unix use `\n` to signify that the enter key was pressed. Thus, I'd always use `\n` because it's used by all; and `if (x == '\n')` is the proper way to test character equality.
stackexchange-stackoverflow
{ "answer_score": 61, "question_score": 35, "tags": "c, console, newline, getc" }
prevent user from submitting form I have my website in which I have **email pdf** functionality **Procedure is :** * when user enters email and then he has to click on submit button * after clicking submit button , form will not submit and form will hide and * there is another hidden div contains **thank you message** which appears with **Ok button**. * When User Click on **OK button** then form will submit. _**But Now the Problem is :_** When User enter email and if he press **ENTER** accidentally then form gets submitted without showing thank you message. I want to Disable **ENTER** when user Press **Enter** key.
Use this code, will surely work for you: var class = $('.classname'); function stopRKey(evt) { var evt = (evt) ? evt : ((event) ? event : null); var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); if ((evt.keyCode == 13) && (node.type=="text")) {return false;} } class.onkeypress = stopRKey;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "php, jquery, html, forms, wordpress" }
Get second highest salary, return null if no second highest Null must be returned if: \- There are less than 2 rows in table \- There isn't a second highest salary because everyone has the same salary Everything I look up seems to be aimed towards older versions of Sql Server DECLARE @find int = (Select COUNT(*) from Employee); IF (@find = 1) select null as 'SecondHighest' else select Salary as 'SecondHighest' from Employee order by Salary desc offset 1 rows fetch next 1 rows only; I have managed to return null if there is less than 2 columns, although I think there may be a better way to do this. However, I can't fix the second problem: "There isn't a second highest salary because everyone has the same salary"
Here's a similar approach to @alx (which was nice and simple btw, so +1) but it will be easier to generalise to pick the nth highest salary: SELECT MAX(Salary) FROM ( SELECT Salary, DENSE_RANK() OVER(ORDER BY Salary DESC) AS Rank FROM Employee ) E WHERE (Rank = 2);
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "sql, sql server, tsql" }
Physical Device does not show up in Android Device Chooser I posted this in stack overflow, but I figured it would be more relevant here. When I open the DDMS, it shows the device there. !shows the device is there However, when I try to run my program, Eclipse opens the Android Device chooser. The Android Device Chooser has nothing under it. !picture of the error I'm running it on a mac. I've tried installing the drivers for the phone. I've enabled downloading from unknown sources and downloading from USB. Adb confirms that it is there too. The emulator runs fine. Don't know if this will help or not, but on the phone, there are two notifications. "Connected as a media device" and "USB debugging connected" That should be normal? The minimum API level is set to 8, so I don't think it's an API level problem. I've searched everywhere and I can't figure out the reason.
It seems to be a layout bug. Drag one of the column headers in the device chooser where the device should be and change the column width and it magically appears! !enter image description here You can also double click the device's row even when it's hidden, so you don't have to resize the column each time. Source: stackoverflow:
stackexchange-android
{ "answer_score": 2, "question_score": 3, "tags": "adb" }
Should I use != or <> for not equal in T-SQL? I have seen `SQL` that uses both `!=` and `<>` for **_not equal_**. What is the preferred syntax and why? I like `!=`, because `<>` reminds me of `Visual Basic`.
Technically they function the same if you’re using SQL Server AKA T-SQL. If you're using it in stored procedures there is no performance reason to use one over the other. It then comes down to personal preference. I prefer to use <> as it is ANSI compliant. You can find links to the various ANSI standards at... <
stackexchange-stackoverflow
{ "answer_score": 588, "question_score": 878, "tags": "sql, sql server, tsql" }
windows server 2012 internet zone I'm setting up a EC2 instance on Amazon AWS running Windows Server 2012. I'm going to have users remote into this server to run Quickbooks Enterprise. I'm having issues with Quickbooks because it wants to use the internet connection and the Internet Zone setting is set to High, Quickbooks recommends Medium. I've tried the following: * Turning off IE Enhanced Security Configuration * Setting up Users in Domain * Setting Zone in Group Policy * Setting up Users Locally * Setting Zone in Local Group Policy None of which worked. The closest I've gotten is when I set it in Local Group Policy, if I look at the Security tab for the Internet Options for the user it has a notice at the bottom that says "Some settings are managed by your system administrator."
You'll need to use the Internet Explorer Administration Kit The IEAK is available for multiple versions of IE, and is usually required when you want to customize IE settings post-deployment.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "windows server 2012 r2" }
Checking the blockchain within Solidity contract I want my contract to check a given range of blocks and see whether there are any transactions between a given pair of addresses. Is this possible to do in Solidity? Otherwise how would I do it?
No, its not possible the EVM is pretty isolated. Alternative way is to watch the blockchain with a `web3.js` script and notify your contract. Of course this is a potential security hole. The opcodes of the EVM do only have limited access to the current block.
stackexchange-ethereum
{ "answer_score": 6, "question_score": 6, "tags": "solidity, blockchain" }
How to store settings for a JavaScript/jQuery page being tracked by git? As a server developer, I would get my PHP code to access environment variables for deployment settings. How would you approach the same problem for a purely HTML/JavaScript/jQuery page? For example, would you load in a JSON file? I'm tracking the page in git, and I don't want to save person-specific information in the main repo.
Use some build system (ant, phing, shell-scripts...) and create the template for config file. On the build step just fill the template with real values (taken from environment or wherever you want) and prepend the real script with the configuration object. As a result of building process you'll have the specific file for particular client.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, git" }
How to put trunk into branche and completely update it? I currently have a repositorie with the standard trunk/tags/branches structure. The repositorie for "myApp" contains only few tags but no branches. The v2 of myApp have been developped without performing any commit into the repositorie (big mistake i know). The changes in the code are major (almost everything has been changed / refactored). I would like to keep the same repositorie for the 2 versions of "myApp"; so i would like to put the current trunk in a branche (for maintenance fix , in case some people don't update to v2) and put my new version in the trunk. How should i proceed ? (using tortoisesvn on Windows) Is there a better solution ? Thanks
Simply 'Create tag/branch' to put the trunk to a branch. And than I'd probably replace the old sources in a trunk checkout with the new ones and commit, adding/removing files as necessary, so subversion will be able to show the changes (though it's not that big use). To replace the files, first delete all files in the checkout, but make sure to leave the .svn directories intact. Than copy in the new sources and select "commit" and mark all files, including unversioned and deleted.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "svn, tortoisesvn" }
I am trying to share a post on Facebook and WhatsApp only is there any way to limit platforms for sharing on social media in expo, for example, I want to share only one Facebook and WhatsApp and don't show other platforms on the dialogue box
you can use the official dependencies `react-native-share` here's the link :- < These can be assessed using Share.Social property For eg. import Share from 'react-native-share'; const shareOptions = { title: 'Share via', message: 'some message', url: 'some share url', social: Share.Social.WHATSAPP, whatsAppNumber: "9199999999", // country code + phone number(currently only works on Android) filename: 'test' , // only for base64 file in Android }; Share.shareSingle(shareOptions); if you have any problem then feel free to ask me. Thank You.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "react native" }
Compile iOS app against older Mono framework version in Xamarin Studio I'd like to debug my iOS app using an older version of the Mono framework so that I can see how things behaved with an older version of the Mono.Data.Sqlite assembly. How can I tell Xamarin Studio to use an older version?
You can assign `MD_MTOUCH_SDK_ROOT` to point to an alternative install location. This should be the root directory that contains `bin/mtouch`. * You can set/export this as an env. variable to points to your alternative `Xamarin.iOS` framework and then launch Xamarin Studio (or VS4M) from the same shell. * Or you could assign it within your `.csproj` file. Ref: `Xamarin.MonoTouch.CSharp.targets`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ios, xamarin, mono, xamarin studio" }
How to overcome Drawback of Inverse Document Frequency (IDF) Please tell me how to overcome the problem of negative weighting in IDF. Can someone give a small example?
IDF is defined as N/n(t) where n(t) is the number of documents that a term 't' occurs in and N is the total number of documents in the collection. Sometimes, a log() is applied around this fraction. Please observe that this fraction N/n(t) is always >= 1. For a word which appears in all documents, a likely case of which is the English word "the", the value of idf is 1. Even if a log is applied around this fraction, the value is always >= zero. (Recall the graph of the log function which monotonically increases from -inf to +inf with log(x)<0 if x<1 log(1)=0 and log(x)>0 if x>1). So, there's no way in which a standard definition of idf can be negative.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "search engine, information retrieval" }
Prove using Propositional logic laws | Killer question! I'm stuck on this for 2 hours. Can't start with R.H.S also due to less no of variables. > Q. $(p \land q \land \neg r) \lor (p \land \neg q \land \neg r) \equiv p \land \neg r$ **Here I started:** $(p \land q \land \neg r) \lor (p \land \neg q \land \neg r)$ $p \land (q \land \neg r) \lor p \land (\neg q \land \neg r)$ **using Associative Law** $p \land (\neg q \land \neg r) \lor p \land (q \land \neg r)$ **using Distributive Law** What else can we do with it? Any idea? Much appreciated.
You have $$(p \land q \land \neg r) \lor (p \land \neg q \land \neg r) \equiv p \land \neg r \iff (p\land \neg r)(q\lor \neg q)$$ by invoking the distributive law.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "logic, propositional calculus" }
C++/CLI: KeyValuePair<> Key and Value don't exist I'm writing my first class library using C++/CLI and I've encountered an error when trying to access Key and Value properties of KeyValuePair class. KeyValuePair<String^, LONG>^ params = gcnew KeyValuePair<String^, LONG>(readerName, hContext); When I make a breakpoint on it and check using Visual Studio 2010, what's in `params` variables, it correctly shows two private variables that hold key and value, but for Key and Value properties it shows an error saying something like "Key does not exist". ошибка: "System::Collections::Generic::KeyValuePair<System.String ^,int>(params.Key" не существует
LONG is probably not the best thing to use as an argument type for any generic class. It may or may not even be defined depending on how you are building. Use int or long, or better yet, Int32 or Int64 instead. The latest versions of Visual Studio don't support Intellisense for C++/CLI and often watch variables cannot be deciphered at all, let alone partially as you're seeing. Bottom line: Don't expect the IDE/Debugger to work well at all for C++/CLI code. Just output to a debug stream or otherwise test the variable in your own code to see if it looks/works as expected. Don't trust the debugger when it comes to Managed C++.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c++ cli, managed" }
Why do I get "System.Data.DataRowView" instead of real values in my WinForms Listbox? Whenever I run my code and try to view a `highscore` all I get back in my listbox is `System.Data.DataRowView`. Can anyone see why? Code: MySqlConnection myConn = new MySqlConnection(connStr); string sqlStr = "SELECT CONCAT(Name, ' ', Score) as NameAndScore " + "FROM highscore ORDER BY Score DESC"; MySqlDataAdapter dAdapter = new MySqlDataAdapter(sqlStr, myConn); DataTable dTable = new DataTable(); dAdapter.Fill(dTable); dAdapter.Dispose(); lstNames.DisplayMember = "NameAndScore"; lstNames.DataSource = dTable;
I always have to deal with this problem, even if I set the `DisplayMember` and `ValueMembers` of the List Box. Your current code is correct and should work, if you need access to the current selected item value of any column of your `dTable` you can get them doing this: DataRowView drv = (DataRowView)lstNames.SelectedItem; String valueOfItem = drv["NameAndScore"].ToString(); What I like about getting the entire `DataRowView` is that if you have more columns you can still access their values and do whatever you need with them.
stackexchange-stackoverflow
{ "answer_score": 22, "question_score": 13, "tags": "c#, mysql, winforms" }
Scala reflection: can I see if something is a (case) object? Is there a way in Scala to see if a class was defined as an object? def isObject(c: Class[_]): Boolean = ??? object X class Y val x = X val y = new Y isObject(x.getClass) == true isObject(y.getClass) == false
Using `scala-reflect`, following seems to work: object ObjectReflection extends App { import scala.reflect.runtime.universe._ def isObjectT(implicit tag: TypeTag[T]): Boolean = PartialFunction.cond(tag.tpe) { case SingleType(_, _) => true } object AnObject case object ACaseObject class AClass case class ACaseClass(i: Int) trait ATrait println("new AClass " + isObject(new AClass)) println("ACaseClass(42) " + isObject(ACaseClass(42))) println("new ATrait {} " + isObject(new ATrait {})) println("AnObject " + isObject(AnObject)) println("ACaseObject " + isObject(ACaseObject)) } Prints: new AClass false ACaseClass(42) false new ATrait {} false AnObject true ACaseObject true Depends on: libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "scala, reflection" }
Network Register a Headless Device I have a Raspberry Pi (but also applies to any headless machine). I SSH into the machine, but I can't go anywhere else unless I share my internet with it via OS X. To use the internet, each device has to enter a username/password through a webform. What are the recommended ways to performing this?
I would be surprised this question has not been asked before... In any case: the basic command is: curl --user name:password -v (the _-v_ option, for _verbose_ , is useful since you are doing this for the first time). However, it may prove useful to allow cookies, curl -b cookies.txt -c cookies.txt --data "Username=xx&Password=xx&Login=Login" Keeping cookies will allow you to appear as registered already at your next request.
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "linux, networking, raspberry pi, debian wheezy" }
How do you create reports that show the number of We need to report on various demographics (gender, age, sexuality, ethnicity, etc...) and changes over time... So far, I seem to only manage to produce lists of individuals / contacts that match each of the criteria, but how would I go about producing a report that answers these types of questions: How many new BAME* joined our charity between 1st April and 30th June (*sorry, that's british for ethnic minority) Or how many members identify as male, female, trans F, trans M, non-binary etc I am panicking that this is not even possible within Civi... I've tried creating groups, searches within groups, searches using advanced search and search builder, reports... As mentioned in my first post, I am a complete newbie thanks for any advice
Here's an example%20AS%20COUNT_id%22%5D,%22orderBy%22:%7B%7D,%22where%22:%5B%5D,%22groupBy%22:%5B%22gender_id%22%5D,%22join%22:%5B%5D,%22having%22:%5B%5D%7D) showing how you could get counts by gender using SearchKit on dmaster: ![enter image description here]( You probably want to add some 'Where' clauses to limit the counts to those of interest. In general, 'changes over time' reports are harder because you need historic data and Civi primarily reflects the current state. One option is to record the current state over time and compare it outside of Civi. Other approaches make use of logging to determine the state at a previous time - eg this blog post.
stackexchange-civicrm
{ "answer_score": 2, "question_score": 0, "tags": "reports, searchkit" }
Bind ListView to list of numeric value types? My googling is failing me this Monday morning. This should be simple, can someone help? Normally I bind ListView an object collection as in: <ListView Margin="5,10,5,10" x:Name="listViewFoo" ItemsSource="{Binding FooCollection}"> <ListView.View> <GridView> <GridViewColumn Width="50" Header="FooBar" DisplayMemberBinding="{Binding FooProperty}"/> </GridView> </ListView.View> </ListView> How can I bind ItemsSource to a collection of say, System.Int64 objects and display them in one column?
You don't need `DisplayMemberBinding`; this should work... <ListView Margin="5,10,5,10" x:Name="listViewFoo" ItemsSource="{Binding FooCollection}"> <ListView.View> <GridView> <GridViewColumn Width="50" Header="FooBar"/> </GridView> </ListView.View> </ListView>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, wpf, listview" }
MySQL LOAD DATA LOCAL INFILE does nothing when first line is enclosed by " The following MySql Query does absolutely nothing LOAD DATA LOCAL INFILE 'path/to/file.csv' REPLACE INTO TABLE `db`.`table` COLUMNS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES ( `id`, `name` ); The CSV file is as follow : "id","name" "1","Lorem" "2","Ipsum" "3","Dolor" "4","Sit" "5","Amet" "6","consectetur " "7","adipisci" "8","velit" "9","sed" "10","quia" I have checked the line separator which is LF, and the file encoding is UTF-8. I have noticed that if I empty the first line of the csv, or remove the double quotes on the first line, the query does actually affect 10 rows. Do you have any idea why this is happening ? Because I would rather I did not have to edit the first line.
Problem is with your `Escaped By '"'`, as first quote(") encounters, its considered as `Escape`. Just get rid of it, it will work. LOAD DATA LOCAL INFILE 'path\\to\\file.csv' REPLACE INTO TABLE `db`.`table` COLUMNS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES ( `id`, `name` );
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "mysql, csv" }
Tkinter GUI set to relative does not resize with window I'm trying to make a gui that resizes automatically to fit the window it's in, but it's not working out too well. I tried using relative code like this: self.console.place( relx = 0, rely = 0.1, relheight = 0.85, relwidth = 1 ) but when the window is resized, it doesn't resize the elements in it. The relative stuff works fine in the initial declaration of the widgets, it just doesn't resize after that. Am I doing something wrong, or am I just missing something?
Turns out it wasn't the fault of that code, it was simply becuase the window resizing did not automatically resize my main frame. For future reference, when trying to make an auto-resizing window, try something along these lines and make sure you weren't making my mistake: self.pack( expand = tkinter.YES, fill = tkinter.BOTH )
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, python 3.x, tkinter" }
is there any configuration or setup for ftp(file transfer protocol) SPEED on windows server 2008 (r2) i am using windows server 2008 (r2) and CuteFTP Pro 8.3.4 for transfer files to my server. on windows server i have iis,dns,ftp,websitepanel... my internet speed is 1mbps and server speed is 5 mbps! but when i want upload files on server, we have only 20kbps speed! is there any configuration or setup for ftp(file transfer protocol) SPEED on windows server 2008 (r2)? or is there any config about cuteftp for solving this issue? `I HAVAE REMOTE ACCESS TO MY SERVER` thanks in advance
What's your **upload** speed. I'm assuming this isn't a leased line, so it's almost certainly different to your **download** (I.e., quoted) speed. In short, I'm almost certain that this is a) Not an issue with your server b) Not a fault Also, I'm not understanding what the difference between "server speed" and "internet speed" is. Can you be cleared on your infrastructure? Finally, can you be clearer whether you're talking about Kilo _bits_ or Kilo _bytes_ and Mega _bits_ or Mega _bytes_. A 20 Kilobyte per second upload is 160Kilobits, which is probably average for a 1Mb domestic broadband connections.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 1, "tags": "windows server 2008 r2, ftp, performance" }