INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
checking if array[key] isset? throw: index out of range if i try to access key in array which does not exist i get throw: index out of range with a stacktrace. How do i check if tmp[key] "is set" ?
This accualy works: if len(url) > 1 { tmp := strings.Split(url[1],"=",0); if len(tmp) >1{ sess = tmp[1]; } }
stackexchange-stackoverflow
{ "answer_score": -2, "question_score": 3, "tags": "go" }
Remove vertical spacing from flex-wrap:wrap property I have this plunkr here. How to remove the vertical spacing while using `flex-wrap: wrap;` #main { width: 200px; height: 200px; border: 1px solid #c3c3c3; display: flex; flex-wrap: wrap; } <div id="main"> <div style="background-color:coral;">A</div> <div style="background-color:lightblue;">B</div> <div style="background-color:khaki;">C</div> <div style="background-color:pink;">D</div> <div style="background-color:lightgrey;">E</div> <div style="background-color:lightgreen;">F</div> </div>
You should use `align-content: flex-start;` on `#main`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, css, flexbox" }
NodeJS takes forever to build on AWS EC2 I am trying to setup NodeJS on EC2. I followed the official guide and it was successful on my local machine. However when compile the source code on EC2, it takes forever to finish (2 hours and counting). I guess it has something to do with CPU limit or timeout. I am not familiar with Linux and makefiles. Is there a way to bypass that? Thanks,
I'm guessing you're using a micro instance. Yep, it's going to take a while - micro instances get lots of CPU for a short while, then get severely capped if you use CPU for a while. Compiling node.js is CPU intensive. On the bright side, you only have to do it once. Once it's finished, make an AMI and you can launch as many servers with node.js pre-installed as you like.
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 9, "tags": "node.js, amazon ec2" }
Session values not found after redirect In the Asp.net MVC Project I am redirecting my users to another page after login. On the development environment all my session variables return null. On Production however this works fine and session variables are retrieved correctly. can some One please explain why all variables are null on the development environment. [AllowAnonymous] [HttpPost] public ActionResult Login(LoginModel model, string returnUrl) { // Some validations if (Url.IsLocalUrl(returnUrl)) { var urlDeCoded = HttpUtility.UrlDecode(returnUrl); var htmlDecoded = HttpUtility.HtmlDecode(urlDeCoded); return Redirect(htmlDecoded); } } /// Retreiveing session variables var vm = SessionData.GetCurrentObject<MembershipWizardViewModel>(); In web.Config I have the same value for sessionState on both Envirnoments i.e. "InProc"
Do you loose your session ? I think this could be a problem of cookies : session Ids could be kept in cookies, and if you redirect on a Url which is on a different server, cookies are different, so it creates you a new session... with empty variables. A common mistake is to redirect from "localhost" to "127.0.0.1", even if it is technically the same, it could cause a lot of troubles.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net, asp.net mvc, c# 4.0, session variables, redirect" }
Invariant subspace Let $T: V \to V$ linear transformation, and let $W$ to be an invariant subspace of $V$. we mark $T_w: W \to W$ the from $T$ to $W$. Prove that if T is diagonalizable, then $T_w$ is diagonalizable. How do I start to prove it? I know that if T is diaognizeable then it's factors are different from each other. but how does that help me here?
Let $\;m_T(x)\,,\,\,m_{T_W}(x)\;$ be the minimal poloynomials of $\;T:V\to V\;,\;\;T_W:=T|_W:W\to W\;$ , respectively. Since $$m_T(T)=0\implies m_T(T)(v)=0\;\;\;\forall\;v\in V\;,\;\;\text{then also}\;\;$$ $$m_T(T)(w)=m_{T_W}(w)=0\;\;\forall\;w\in W\implies m_T(T_W)=0$$ so $\;m_{T_W}(x)|m_T(x)\;$ by minimality of $\;m_{T_W}(x)\;$ . But this means that since a linear operator on a finite dimensional space is diagonalizable iff its minimal polynomial splits as the product of different linear factor, since this happens to $\;m_T(x)\;$ it also happens to $\;m_{T_W}(x)\;$ and thus $\;T_W\;$ is diagonalizable.
stackexchange-math
{ "answer_score": 4, "question_score": 2, "tags": "linear algebra" }
Is it possible in modern biology to make any person's identical twin (or genetical clone) using his DNA? I was told by a Biotech professor (who came in our college for a guest lecture) that Bio Technology has now become so advanced that if we want to make an identical twin (or Genetical DNA Twin) of a person then we can now be able to it using his DNA. I am a Mathematics Student so I don't know much about it. I just attended the lecture because I found it interesting. I am sorry, I know I should have asked this very simple question in Quora but, I wanted a precise answer which could be believed. So I asked here, where I will get answers only from the very experts. I apologize again Thank You So Much in advance **Edit 1** :- I am satisfied with @Remi.b 's answer, @Bryan 's explanation and @anongoodnurse ' references. I should also have mentioned genetical DNA Clone in the place of identical twin. Now I've added.
I will assume that by "identical twin", you refer to "clones". Individuals who share the same genetics but of course do not necessarily share the same womb. I won't pay much attention in detail epigenetic modification nor in the length of telomeres. While it has never been done for ethical reasons, we would probably be quite able to make a clone of a human being. We can take a cell from an individual, make it totipotent again, like a zygote and then, insert this zygote into a woman's uterus. The resulting individual is a clone and therefore have identical genetics, just like two identical twins. Similar technics have been used to clone Dolly the sheep). We cannot, however, modify the DNA in all cells of a living individual to make this individual a perfect cone of another one.
stackexchange-biology
{ "answer_score": 5, "question_score": 2, "tags": "genetics, dna, human genetics, biotechnology" }
How does this iterative Tower of Hanoi work? C > **Possible Duplicate:** > How does this work? Weird Towers of Hanoi Solution While surfing Google, i found this interesting solution to Tower Of Hanoi which doesn't even use stack as data structure. Can anybody explain me in brief, what is it actually doing? Are this solution really acceptable? **Code** #include <stdio.h> #include <stdlib.h> int main() { int n, x; printf("How many disks?\n"); scanf("%d", &n); printf("\n"); for (x=1; x < (1 << n); x++) printf("move from tower %i to tower %i.\n", (x&x-1)%3, ((x|x-1)+1)%3); return 0; } **Update: What is the hard-coded number 3 doing in here?**
Might be easier to see in PSEUDOCODE: GET NUMBER OF DISKS AS n WHILE x BETWEEN 1 INCLUSIVE AND 1 LEFT-SHIFTED BY n BITS SUBTRACT 1 FROM n, DIVIDE BY 3 AND TAKE THE REMAINDER AS A OR x WITH x-1, ADD 1 TO THAT, DIVIDE BY 3 AND TAKE THE REMAINDER AS B PRINT "MOVE FROM TOWER " A " TO TOWER " B ADD 1 TO x 1 LEFT SHIFTED BY n BITS is basically 2 to the power of n, 16 in the case of 4 disks. If you walk through this sequence manually, you should see the progression of movement of the disks.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 7, "tags": "c, iteration, towers of hanoi" }
How to loop through folders and rename extensions in a batch file? Selecting a single folder I could run ren *.jpeg *.png I have multiple folders. I want to create a batch file that will loop through all the folders and will rename the files within it. For example I have folders `TEST1` and `TEST2` inside root directory `TEST`. I want to create a batch that will rename all the `.jpeg` files within `TEST1` and `TEST2` to `.png`. FOR /R "E:\TEST\" %%G in (*.jpeg) DO ren *.jpeg *.png I am getting an error: > The system can not find the file specified I don't understand the issue.
You are not applying the `for` command to the `ren` action. for /r "E:\test\" %%G in (*.jpeg) do ren "%%~G" *.png You need to change `%%` to `%` if you are doing this interactively, and not in a batch file. The `~` strips quotes, which are re-added, to avoid any possible errors with paths which contain spaces.
stackexchange-superuser
{ "answer_score": 3, "question_score": 2, "tags": "windows, rename, batch file, batch rename" }
"Sold" in the meaning of "bought"? Reading the comments in this blog post I was a little confused when the first one said "sold". Why should he sell his game when they removed the copy protection with the first patch? But it seems that the meaning of the comment was "I went to the shop and bought it". (Or I completely got it the wrong way.) Can you help me? I always thought that selling is the opposite of buying.
I believe that "Sold" in the first and second comment is short for "I'm sold on ( _something_ )", meaning "I'm convinced of ( _something_ 's) value." This seems to be an American-specific phrase; a quick look at Google NGrams for the phrase "I am sold on" shows it appearing in American English around 1880 and peaking in popularity in the 1940s. The same search for British English... shows nothing at all. The earliest example I see - from 1917 - gives the sense of the phrase quite well: > "To say that I am sold on the Essex only half expresses how I feel after an eight hundred mile trip through western Tennessee," writes WH Claypool, sales manager of the Memphis Motor Car Co.
stackexchange-english
{ "answer_score": 6, "question_score": 6, "tags": "meaning" }
How to specify virtual web hosts in Nessus (host header/SNI) Say I have the web server `198.51.100.125` in Amazon cloud that I want to scan, which is hosting two domains `example.com` and `example.org`. In Nessus, I have configured the targets like so: 198.51.100.125[example.com] 198.51.100.125[example.org] This is so Nessus can send web requests with `host: example.com` and `host: example.org` when testing the two sites for vulnerabiliites, instead of scanning the default website. Ditto for SNI when using HTTPS. However, the Nessus results are showing the web vulnerabilities on the reverse DNS host of `198.51.100.125`, which is ` and ` instead of the ` ` ` and ` sites. I'm sure I've successfully done this previously, however it is not working this time. What gives? Is there anything to check in configuration?
Got a reply from Tenable Support: > The issue you are experiencing seems to be and engine issue that looks to have started in the 6.8 release, but this is something that will be addressed in a future release. this issue is being addressed at present. There was a number of systems that experienced this issue and we will be using yours as the principle issue to develop the fix. I currently do not have an ETA on the resolution deployment. But i am assured it will be fixed in the future releases.
stackexchange-security
{ "answer_score": 0, "question_score": 1, "tags": "webserver, vulnerability scanners, nessus" }
Links com LI dentro Possuo essa estrutura: <ul> <li><a></a></li> <li><a></a></li> </ul> Ok, o que acontece, é que as vezes preciso colocar o link `<a>` acima da `li` e não dentro, como está na estrutura. Como vocês fazem? Eu já utilizei `window.location`, mas queria saber se tem alguma forma de fazer sem usar **javascript**.
Não é recomendado, e literalmente não é correto você colocar algo como: <a><li></li></a> Assim, como definido nas regras de padrões do HTML, pelo w3c, dentro da tag `<ol>` ou `<ul>`, podemos conter somente tag `<li>`. O que suspeito que você queira fazer, é que o bloco do `<li>` inteiro seja 'clicável', então recomendo fazer é adicionar a propriedade **_"display: block"_** no css da tag `<a>`.
stackexchange-pt_stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "html" }
execute function after ng-repeat finishes with hidden elements here is the situation, i have this code <div data-ng-repeat="question in questions" data-ng-if="cQuestion == $index + 1" class="question-animate"> {{question.question}}-{{$index + 1}} <div data-ng-repeat="answer in question.answers"> {{answer}}&nbsp </div> <input type="button" value="next" data-ng-click="nextQuestion()"/> </div> i want to detect when the ng-repeat finishes so i can update cQuestion to show the first question. Since we have `data-ng-if="cQuestion == $index + 1"` this evaluates to false at first, and the element is not shown, this limits my options to detect when ng-repeat has finished. i have tried with a directive but since the element is not shown and the directive isn't fired. the ng-if is there because there is animation hooked to the repeated object. Now i am doing it with setTimeout, but i think this technique isn't reliable.
Let's move index `cQuestion` out of the view. Your controller should do the work. Create a variable `currentQuestion`, that represents the current displayed question. <div> {{currentQuestion.question}}-{{currentQuestionIndex+1}} <div data-ng-repeat="answer in currentQuestion.answers"> {{answer}}&nbsp </div> <input type="button" value="next" data-ng-click="nextQuestion()"/> </div> Then make sure, that `nextQuestion` does change the current question: function nextQuestion(){ $scope.currentQuestion = $scope.questions[$scope.currentQuestionIndex]; $scope.currentQuestionIndex ++; //init with 0 } Don't forget to init the `$scope.currentQuestion` with the first question at the start of your controller.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, angularjs, angularjs ng repeat" }
How to Design a SaaS Database I have a web app that I built for a trucking company that I would like to offer as SaaS. What is the best way to design the database? Should I create a new database for each company? Or should I use one database with tables that have a prefix of the company name? Or should I Use one database with one of each table and just add a company id field to the tables? Or is there some other way to do it?
faced with a similar situation about 10 years ago, we opted for a database per client. we have hundreds (not thousands) of clients. looking back it was one of the best decisions we made. backups are easy. copying a single client to our office for analysis is easy (just take the last backup). scaling is easy (moving a single big client to a different server can free up resources on a stressed sql server). joel & jeff had a discussion about this on a stack overflow podcast (not a recent one) and joel did the same thing i do ... each client gets their own database. database purists will often argue for lumping everyone into one db, but i would never do that. -don
stackexchange-stackoverflow
{ "answer_score": 31, "question_score": 22, "tags": "database, database design, database schema" }
Missing argument for parameter #1 in call I have a lazy parameter that I'm attempting to call a helper function in: class ColumnNode: SCNNode { lazy var upperColumnNode: SCNNode = { return buildColumPart() }() func buildColumPart() -> SCNNode { var node = SCNNode() ... return node } } Unfortunately on line `return buildColumPart()` I am getting: Missing argument for parameter #1 in call What exactly does this mean and how do I fix it?
You need to use `self` to access instance methods in lazy properties: class ColumnNode: SCNNode { lazy var upperColumnNode: SCNNode = { return self.buildColumPart() }() func buildColumPart() -> SCNNode { var node = SCNNode() ... return node } } Interestingly enough, the reason it's complaining about parameter #1 is that instance methods are _actually_ class methods that take an instance as a parameter and return a closure with the instance captured - instead of `self.buildColumPart()`, you could instead call `buildColumPart(self)()`.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 6, "tags": "ios, swift" }
Power Automate Filter query on created date column I have a big document library has documents for than one lakh in it. I am trying to get all documents created in certain months in year, let's say I want to get all documents created in the month of April '2021' In the Power Automate Odata filter query, how we can we add this as filter query. Similarly, in the SharePoint Online document library - want to create a view for this filter. What will be filter criteria for this?
For SharePoint out of the box view in document library, use filter conditions like this: ![enter image description here]( * * * For Power Automate flow, use filter query like: Created ge datetime'2021-04-01T00:00:00Z' and Created le datetime'2021-04-30T00:00:00Z' **Source** : Filter Created in SP REST API Also, 1. Set Top Count of "Get items" action to 5000 2. Enable pagination from settings of "Get items" action and set pagination threshold more than 10000. 3. Add indexing on "Created" column from library settings **Top Count** : ![enter image description here]( **Pagination settings** : ![enter image description here](
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 0, "tags": "sharepoint online, document library, modern experience, power automate, flow" }
Mysql - normalization of database I have a MySQL database and I want to normalize it in an efficient way. I have a table in my database in which i am getting data into column in the form of array. Actually I have three tables (details, country, material). In table "country" I have two column that are (id,country_name). In table "material" I have two column (id, material) and in table "details" i have four column (id, vendor, countries, materials). In this scenario, each vendor has multiple countries and materials and I am inserting ids of country and material in details table. Here is the screenshot: ![detail table]( so how I accurately normalize my database? Thanks in advance
Remove countries and materials columns from Details table. You can create a fourth table which will depict the relationship between vendor,country and material: vendor_id country_id material_id 1 3 5 1 6 9 1 7 24 Here all the columns will be foreign key and together they will form composite primary key
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "mysql, database" }
Replace a value in a Pandas Dataframe with condition with one line How to do this operation in one line ? df.loc[(df['A'] < 0), 'A'] = 0 df.loc[(df['B'] < 0), 'B'] = 0 Maybe it exists a Pandas function or maybe I can add arguments in this function.
Use `DataFrame.clip_lower` with subset of columns: df = pd.DataFrame({'A':[-1,20,24], 'B':[-1,2,-3], 'C':[-1,-2,-3]}) print (df) A B C 0 -1 -1 -1 1 20 2 -2 2 24 -3 -3 df[['A','B']] = df[['A','B']].clip_lower(0) print (df) A B C 0 0 0 -1 1 20 2 -2 2 24 0 -3
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "python, pandas, dataframe" }
get message from web service in android I have developed android application named VMS.I have to get messages from the webservice.The url is < Can anyone guide me how to proceed with this webservice Thanks in advance Tushar
Please check out this question: How to call a SOAP web service on Android
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, web services" }
How to run/debug Ruby Cucumber tests in IntelliJ IDEA? I launch my Cucumber tests from a shell with the command `bundle exec cucumber -p local features`. **Questions:** 1. How to do the same with help of IntelliJ IDEA? 2. How to debug the tests with IntelliJ IDEA?
There is a Ruby plugin for IntelliJ. I'm not personally familiar with it (I use RubyMine), but I expect that it has dedicated run/debug support for Cucumber like RubyMine does.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ruby, intellij idea, cucumber" }
Construct a pushdown automaton for $\{a^{2n}b^{3n}|n\ge0\}$ My idea is to (not formal) push an 'a' when we see an a, nondeterministically guess when n a's were seen from the input word, go to the next state. From there, when we see an a, push 2 'a's into the stack and again guess when n a's were seen (now there should be 3n 'a's in the stack) and go to the final state, where if we see a b, we pop from the stack. So the stack will be empty in the last state iff we saw 3n b's. The problem that with this line of thought we can construct an automaton for$\\{a^{n}b^{n}c^n|n\ge0\\}$. So where am i wrong in this thinking?
Your PDA accepts the language $$ \\{a^{i+j} b^{i+2j} : i,j \geq 0 \\}, $$ which is different from the one you are interested in. In fact, you can show that it equals $$ \\{a^kb^\ell : k \leq \ell \leq 2k \\}. $$
stackexchange-cs
{ "answer_score": 1, "question_score": 1, "tags": "automata, context free, pushdown automata" }
Is there a difference between using moment(Date.now()) and simply using moment()? Is there a difference between using `moment(Date.now())` and simply using `moment()`? console.log("Moment (now):", moment(Date.now())); console.log("Moment:", moment()); Both result in the same output: > Fri Feb 15 2019 17:26:53 GMT+0000 (Greenwich Mean Time)
`moment()` generates the current date as a moment instance, and `moment(Date.now())` casts the current Date object to a moment object, so yes it is the same!
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "momentjs" }
Using AWS, is Public accessibility within VPC safer than public accessibility without VPC I am able to use VPC + public accessible with some services e.g. RDS, but AWS Elasticsearch doesn't provide the option to use both together. So I am wondering, if: 1. Public accessibility in a VPC is same as public accessibility without VPC in terms of security, OR 2. Are we compromising on security when creating a publicly accessible cluster without VPC. There is an option to restrict access by IP within Elasticsearch configuration, which can mimic Security group like protection. **VPC Access** ![VPC access]( **Public Access** ![Public access](
Q1. Using VPC gives you much more control over public access then not-using VPC. You can use security groups (SGs), network acls, you can monitor traffic using VPC flow logs, or setup extra proxies. Q2. It does not mimic the behavior of SGs. SGs provide protection ahead of any traffic hitting your resources. In contrast, the policies that ES are using take effect only when the traffic actually gets to your ES domain, not before it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "amazon web services, elasticsearch, amazon vpc" }
Why is the data type of System.Timers.Timer.Interval a double? This is a bit of an academic question as I'm struggling with the thinking behind Microsoft using double as the data type for the Interval property! Firstly from MDSN Interval is the time, in milliseconds, between Elapsed events; I would interpret that to be a discrete number so why the use of a double? surely int or long makes greater sense!? Can Interval support values like 5.768585 (5.768585 ms)? Especially when one considers System.Timers.Timer to have nowhere near sub millisecond accuracy... Most accurate timer in .NET? Seems a bit daft to me.. Maybe I'm missing something!
Disassembling shows that the interval is consumed via a call to `(int)Math.Ceiling(this.interval)` so even if you were to specify a real number, it would be turned into an `int` before use. This happens in a method called `UpdateTimer`. Why? No idea, perhaps the spec said that `double` was required at one point and that changed? The end result is that `double` is not strictly required, because it is eventually converted to an `int` and cannot be larger than `Int32.MaxValue` according to the docs anyway. Yes, the timer can "support" real numbers, it just doesn't tell you that it silently changed them. You can initialise and run the timer with `100.5d`, it turns it into `101`. And yes, it is all a bit daft: 4 wasted bytes, potential implicit casting, conversion calls, explicit casting, all needless if they'd just used `int`.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 16, "tags": "c#, .net, timer" }
PHP str_replace to replace need with random replacement from array? I've researched and need to find the best way to replace a need with an array of possibilities randomly. ie: $text = "Welcome to [city]. I want [city] to be a random version each time. [city] should not be the same [city] each time."; $keyword = "[city]"; $values = array("Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami"); $result = str_replace("[$keyword]", $values, $text); The result is every occurrence has "Array" for city. I need to replace all of the city occurrences with a random from $values. I want to do this the cleanest way possible. My solution so far is terrible (recursive). What is the best solution for this? Thank you!
You can use preg_replace_callback to execute a function for each match and return the replacement string: $text = "Welcome to [city]. I want [city] to be a random version each time. [city] should not be the same [city] each time."; $keyword = "[city]"; $values = array("Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami"); $result = preg_replace_callback('/' . preg_quote($keyword) . '/', function() use ($values){ return $values[array_rand($values)]; }, $text); Sample `$result`: > Welcome to Atlanta. I want Dallas to be a random version each time. Miami should not be the same Atlanta each time.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "php, arrays, string, random, str replace" }
Обратиться к массиву php После парсинга поста вк возвращается массив вложений вида ( [0] => Array ( [type] => photo [photo] => Array ( [pid] => 456487 [aid] => -7 [owner_id] => -13062 [user_id] => 100 [src] => [src_big] => [src_small] => [src_xbig] => [src_xxbig] => [width] => 1200 [height] => 800 [text] => [created] => 1470723 [post_id] => 597 [access_key] => 5674fed5bad8 ) ) ) Как вообще извлечь значение допустим [src_xbig]?
Очевидно, $имя_массива[0]['photo']['src_xbig'] , не?
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, массивы" }
Audit trails and recording actions **Background** A discussion that has come up at work recently is how we handle audit logging and the recording of events. We are integrating with a 3rd party app so triggers are a no no from the off so we are handling it in code. We've written a number of prototype components for handling it but nothing feels right as yet. The main issue being we want to create Facebook style time lines for the users to see what action have happened recently but these don't seem to fit well with how we record audits. My question is how would be best to handle this type of scenario? * Should we tailor the audit log tables to fit the requirements of the front end? * Should we have separate tables to handle the "Actions" and have the events and auditing separate * Should we look to a more message based architecture so this will be more like an Event sourcing type component? Input from somebody who has done this type of system would be much appreciated.
> Should we tailor the audit log tables to fit the requirements of the front end? No. Generally this is better when you tailor the audit log tables to fit the requirements of auditors and then worry about the front-end later. > Should we have separate tables to handle the "Actions" and have the events and auditing separate Yes. This gives you more control over events, and adding new ones as you need. > Should we look to a more message based architecture so this will be more like an Event sourcing type component? I prefer to keep things simple and merely store in the db. However a message-based architecture may work well if you are integrating into a multi-tier application and your code is somewhere in the middleware. But here it depends on what you need and we'd need to talk more specific requirements than we have here.
stackexchange-softwareengineering
{ "answer_score": 2, "question_score": 2, "tags": "c#, enterprise architecture, cqrs, event sourcing, audit" }
How to declare a type in typescript based on the keys mentioned in the same type? I want to declare a type in typescript ApiResponse and mention 3 keys in it which are isError, error, and content. What I want is that type should be declared as such that either isError and error exist or content exists. type ApiResponse<T> = { isError?: boolean; error?: ErrorContent; content: this.isError ? undefined : User; // this is something I want . how should I do it. } I want this so that when I call a function which wants a parameter of User type doesn't give an error that the parameter is undefined
We can't define type based on dynamic value here, 1. one we need to use generic to get `User` type 2. Instead of isError boolean we should use `status` kind of enumeration (`success, error`) so that we represent invalid state properly. Try like below, type ErrorContent = {}; type User = {}; interface SuccessResponse<T> { status: "success"; content: T; // this is something I want . how should I do it. } interface ErrorResponse { status: "error"; error: ErrorContent; } type ApiResponse<T> = SuccessResponse<T> | ErrorResponse; const success: ApiResponse<User> = { status: "success", content: {} }; const failure: ApiResponse<User> = { status: "error", error: {}, };
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, reactjs, typescript, typescript typings" }
How to prevent double post of data from android to php file I have this android app that posts (http post) some data strings to my php file that inserts the data to a mysql table. The problem is, the android app is posting data for about 30 seconds and when the internet connection were accidentally down or interrupted during the posting of data, the user is about to repost the data and so it makes double record on mysql database. The datasource of my android app is a text file on the device sdcard. after successful posting of data (without interruption), that text file is supposedly deleted.
As @subspider pointed out. Once the app posted a specific line, it must be deleted so that when internet connection was interrupted, and the user repost data, there will be no double post. //check internet connection if( isNetworkAvailable() == true ){ //post the data postData( "sessions", sessionnumber, sessionFirstname, sessionIdNumber, sessionLastname, action, username, timestamp); //clear the line/leave the line blank whole_text = whole_text + "\n"; }else{ //0 means some failed //if internet connection not detected //leave that line as is upload_log_status = 0; whole_text = whole_text + line + "\n"; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, android, mysql, http, post" }
Solve Only variables should be passed by reference error Without Extra Variable I have seen many topics on the subject but none talk about what I want. Is it possible to resolve this error without having to create a variable? I'm trying to do this. $video["upload"]["url"] = array_shift(array_column($json, 'url')); But the error happens Only variables should be passed by reference This solves the problem $var = array_column($json, 'url'); $video["upload"]["url"] = array_shift($var); There are many occurrences, I will have to create many extra variables. I do not like having to create those variables any more. Can you solve this error without doing this?
I would say it isn't possible because the method you want to access wants the variables passed by reference. Here the target-method is the problem. If you for example write an own method you have to decide if you want to have a variable passed by reference or by value. So you cannot influence extern written methods except you own the code.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "php" }
Reduced mass and harmonic mean In two-body problems, a reduced mass has the form: $\frac{m_1 m_2}{m_1+m_2}$, which by appearance, is half of the harmonic mean of $m_1$ and $m_2$: $\displaystyle\frac{2}{\frac{1}{m_1}+\frac{1}{m_2}}$ But is this just a result purely by mathematical deduction (and nothing more) that reduced mass has the same form as that of harmonic mean? Or is there any underlying reason/explanation for this?
The harmonic mean involves averaging the reciprocals, so it is dominated by the _smaller_ of the two values. The reduced mass has the same requirement: The orbit of a small body around a large body is almost the same as the orbit of a small body about a fixed point. This also "explains" the factor of 2: in the limiting case m1>>m2, the reduced mass = m2, not twice that. By a happy "accident", the formula for the reduced mass is the simplest formula that meets these requirements.
stackexchange-physics
{ "answer_score": 0, "question_score": 2, "tags": "newtonian mechanics, newtonian gravity, mass, orbital motion" }
How to create a constant using play framework 2.0 views Hi I'm using the play framework in Java I need to create a constant in a view and use it in a loop. To illustrate this will be the code in a view @for(i <- 1 to 7){ @if(i>=wd) { //The constant wd is defined outside but in <td>@cur++</td> }else { <td></td> } } (I have to use wd many times and I think its a little ugly to pass it from the controller). Is there no way to just create a constant? I looked at @defining(user.getFirstName() + " " + user.getLastName()) { fullName => <div>Hello @fullName</div> } but this doesn't seem to help Thanks
The `defining` block should be exactly what you need for this: If your constant is limited to the template you simply wrap your whole template in the defining block: @defining( 1 ){ wd => @for(i <- 1 to 7){ @if(i>=wd) { <td>@cur++</td> } else { <td></td> } } } You're also not limited to `Integer`s in there, you can define Strings, Lists, ... in there aswell. If you want to use that constant in multiple templates, consider putting it in an `Enum` and get the value from the enum in the defining block.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "java, scala, playframework 2.0" }
Are GNU backtrace_symbols() and dladdr() thread-safe? I am writing a C++ exception class, which has to provide limited backtrace at throw site. Since my application will be multi-threaded, exceptions might be thrown at the same time. I searched the Internet for this thread-safety issue, but found none. `backtrace()` returns array of C strings. These C strings must not be freed by the application. Since it gets its information and composites these strings at runtime, I fear that it is not thread safe. `dladdr()` returns a `struct Dl_info`, with two C strings in it. Also must not be freed by the application. Oh well, I guess I should just read the source code.
From the manual > A backtrace is a list of the function calls that are currently active in a **thread**. The usual way to inspect a backtrace of a program is to use an external debugger such as gdb. However, sometimes it is useful to obtain a backtrace programmatically from within a program, e.g., for the purposes of logging or diagnostics. > > The header file execinfo.h declares three functions that obtain and manipulate backtraces of the **current thread**. Looks like they're using thread-local storage. `dladdr` is returning non-modifiable strings which belong to the loaded object file. This is thread-safe because it's read-only and the object is available until `dlclose`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c, multithreading, gnu" }
SELECT MAX() too slow - any alternatives? I've inherited a SQL Server based application and it has a stored procedure that contains the following, but it hits timeout. I believe I've isolated the issue to the SELECT MAX() part, but I can't figure out how to use alternatives, such as ROW_NUMBER() OVER( PARTITION BY... Anyone got any ideas? ## Here's the "offending" code: SELECT BData.*, B.* FROM BData INNER JOIN ( SELECT MAX( BData.StatusTime ) AS MaxDate, BData.BID FROM BData GROUP BY BData.BID ) qryMaxDates ON ( BData.BID = qryMaxDates.BID ) AND ( BData.StatusTime = qryMaxDates.MaxDate ) INNER JOIN BItems B ON B.InternalID = qryMaxDates.BID WHERE B.ICID = 2 ORDER BY BData.StatusTime DESC; Thanks in advance.
[UNSOLVED] But I've moved on! Thanks to everyone who provided answers / suggestions. Unfortunately I couldn't get any further with this, so have given-up trying for now. It looks like the best solution is to re-write the application to UPDATE the latest data into into a different table, that way it's a really quick and simple SELECT to latest readings. Thanks again for the suggestions.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 8, "tags": "sql, sql server, timeout, max" }
How to migrate from CVS to SVN by using cvs2svn tool? **I want to migrate from CVS to SVN by using cvs2svn tool**. I want a step by step process on how to migrate. I have no idea about the usage of the tools. Basically I am a java fresher. I dont have knowledge on cvs2svn tool and neither on python too. But my task is to migrate from CVS repository to SVN repository. Can any one help me how to do this? I want complete step by step in a brief way. I have downloaded **cvs2svn 2.3** tool in C:drive and **Python 2.4.4** in c: drive and **silksvn 1.7.1** tool in c:drive? Now what should I do next? I dont know how to use them to make my task complete. Please suggest me a step-by-step tutorial or a link or e-book or tell me.
Here are a couple of good tutorial: * Migrating CVS to SVN with cvs2svn – Basics for a Windows user * HOWTO: smooth CVS to SVN migration (and back again) Hope that helps!
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "svn, cvs, cvs2svn" }
Is it required to use thread wait() and notify() inside a synchronized block? In Java, is it required to use thread `wait()` and `notify()` within a `synchronized` block?
No. Java will automatically ensure the marked section is entered by one and only one thread. < see also this question: java: wait(), notify() and synchronized blocks * * * Hmm.. seems to be some language issues. You are not required to use wait and notify in a synchronized block, but if you want to use wait and notify, they must be used within a synchronized block.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "java, concurrency, wait, notify" }
Find the domain of the sequence in which it converges uniformly. Let $f_n(x)={x^n\over n}+1$. I need to find the domain of it's uniform convergence. I tried the $M_n$-test. So, I got the point limit $f(x)=1$ when $x\in [0,1]$. For $x>1$ the point limit wont exist, hence no question of uniform convergence arises. Thus, the convergence in uniform in $[0,1]$. That goes right now hopefully. **UPDATE** Also, now I observed the convergence will hold uniformly in $[-1,0]$ by similar argument. For $\vert x\vert >1$, the point limit won't exist. So, the domain of uniform convergence should be $[-1,1]$
That is not true. I'll only discuss the sequence for nonnegative $x$. The negative $x$ I'll leave it for you. For $x>1$ the limit is infinity (why?). So $f(x) =1$ cannot be the limit function for ALL $x$! For $x=1$ the limit is $1$. For $x\in[0,1)$ we have $f(x) =1$. That was all pointwise limits. Now let's check uniform convergence where there is pointwise convergence so only on $[0,1]$. So $f(x) =1$ and \begin{align} \sup_{x\in[0,1]} |f_n(x) - f(x) |\leq \frac{1} {n} \to 0 \end{align} So uniform convergence on $[0,1]$. Now do the negative half line yourself and conclude.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "uniform convergence" }
How to pass a function to a different screen I have 2 screens that I need to share a function ie //ScreenOne.js import ScreenTwo from "./ScreenTwo" ...{... function handlePress(){ Alert.alert( "", "Clicked", [{text: "ok", onPress: ()=>null}] ) } return( <> <FlatList data={source} renderItem={({ item }) => <ScreenTwo item={item} />} /> <Button onPress={handlePress}/> </> ) ...}... //ScreenTwo.js ...{... return( <> <Text>{...}</Text> <Button onPress={handlePress}/>) </> ...}... I'm working with functional components. Most of the materials I read only talk of passing data and not methods/functions to other screens. Using this example how can I call the handlePress from ScreenOne to Two...
I'm assuming you are talking about sharing the `handlePress` function. You can pass a function in the props: <ScreenTwo item={item} handlePress={handlePress}/> And then use it in `ScreenTwo` const ScreenTwo = ({handlePress, ...rest}) => { ... <Button onPress={handlePress}/>) ... }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "javascript, react native" }
Impact of having an international domain? I'm looking to get an .es domain. Just wondering how this might impact search results and rankings as I'd like to make the website available worldwide.
I don't think it makes much of a difference. Search engine rankings are now weighted more to actual page content and social presence, instead of the actual domain name.
stackexchange-webmasters
{ "answer_score": 1, "question_score": 3, "tags": "domains" }
If $E\subset[0,1]$, $|E|=0$ and $f(x)=x^3$, show $|f(E)|=0$, where $|E|$ denotes Lebesgue measure of $E$ The question is > If $E\subset[0,1]$, $|E|=0$ and $f(x)=x^3$, show $|f(E)|=0$, where |E| denotes Lebesgue measure of $E$. Can anyone provide a hint on this? Thank you!
As the set $E$ is of measure zero, for all $\epsilon > 0$ you can find a countable union of open segments $I_n$ with $$E \subset \cup_{n \ge 0} I_n$$ and $$\sum_{n \ge 0} \ell(I_n) < \epsilon$$ That is the definition of $E$ having a measure equal to zero. You have to prove the same thing for $f(E)$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "real analysis" }
GPU Fan is not spinning continuously I have NVidia GTX 550 Ti in my desktop computer. Today, while I was working on the computer, my monitors went off (I work with dual monitors). After a while, I have recognized that my GPU fan does not spin continuously. I have verified that my GPU is overheating by downloading MSI Afterburner. Even though I set the fan speed to 100%, the fan spins a bit with huge intervals. I have also reset the BIOS by taking of its battery and plugging back in. GPU is heating up to 90C degrees in 5-6 minutes, maybe less. Is my GPU fan broken? What should I do to fix it? I also think that power supply might be the issue since the fan spins. It seems the "spin" command is not given continuously.
Expanding on Hardorman's answer. Even if the fan is 3-pin it may still be controlled by the GPU. The common pinouts are: Power [red] (Always) RPM control [usually blue] (sometimes) RPM feedback [usually white] (also sometimes - more likely if there's RPM control) Ground [black] (Always) If you have the tools (depending on the connector), pull all of the wires except for red and black, and see what the fan does. It should immediately spin up to full speed when it gets power (the PWM control line is pulled high internally on most fans). If it still spins intermittently, then the fan likely needs replacing. If it doesn't spin up at all, take the blue wire, and connect it to +12V (or 5V if it's a 5V fan) somewhere on your motherboard. This should force the fan to spin up to full speed. (if you have no clue why you should do this, I wouldn't recommend doing it)
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "hardware failure, gpu, fan" }
Biztalk File Polling I want to make a receive location in Biztalk 2010 that will poll for a file just just once a day. If one file is moved it should stop polling again. Because when the file is moved another application can create a new file in that directory just 1 millisecond later, and that new file may not be moved.
You can put your receive location on a schedule to receive only within a given time frame. Dealing with milliseconds however it would be a bad idea to try to control your receive location with timing. Depending on your requirements I would configure the receive location to only pick up a file with a given name (not a wildcard *.txt) or have your other application create its file in a different location altogether.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "biztalk, polling" }
Pinging virtual host results in request for timeout I have apache2 setup with several virtual hosts, but I have it setup so that if you visit the IP address in your browser you get an error 403. When I ping the domain name of one of my virtual hosts, it always just responds with request for timeout, never the latency, why is this?
Perhaps your hosting provider (or your Linux distro) has firewalled `ICMP` protocol which is necessary for `ping` to work correctly. Note that Apache needs only `TCP` to work properly, and does not need `ICMP`, which is completely different protocol. In other words, `ping` may be completely firewalled, and yet, your website will respond correctly. Some websites actively firewall `ICMP`, most notable example is `microsoft.com`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "apache2, timeout, virtualhost, ping, http status code 403" }
Is there a compiler setting to control how floating point literals are typed in Delphi? While the the case for `e` works by default I would like to change the default casting of the literal `0.1` to allow the `r` to work without any code modifications. Is this possible through a compiler option, compiler directive, or anything else? procedure Test; var s : Single; r : Real; d : Double; e : Extended; begin s := 0.1; if (s = 0.1) then ShowMessage('s matched'); // fail r := 0.1; if (r = 0.1) then ShowMessage('r matched'); // fail d := 0.1; if (d = 0.1) then ShowMessage('d matched'); // fail e := 0.1; if (e = 0.1) then ShowMessage('e matched'); // pass end;
There is no compiler switch that does what you wish. The issue is that a floating point literal is represented as a 10 byte extended precision value by the 32 bit Windows compiler. And because `0.1` is not exactly representable, that is not equal to the 8 byte double precision representation of `0.1`. The documentation says: > If constantExpression is a real, its type is **Extended**. You can however achieve the desired result by using a typed constant. For example: const TenthDouble: Double = 0.1; var d: Double; .... d := 0.1; if d = TenthDouble then .... By using a typed constant we are able to force the compiler to make the constant be the 8 byte double precision representation of `0.1`.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 6, "tags": "delphi, floating point, literals" }
Centrifugal force effect in a rotating frame of reference If the centrepital force doesn't exist in a rotating frame of reference, then in this frame perspective, how can we explain why a ball tied to a string following a circular motion not to be pushed outward if only the centrifugal force that is acting?
> If the centrepital force doesn't exist in a rotating frame of reference The centripetal force does exist in the rotating frame. The centripetal force is a real force, so it exists in all frames. The centrifugal force is an inertial force so it only exists in the rotating frame and not in the inertial frame. So in an inertial frame the centripetal force exists and causes an inward acceleration of the object. In the rotating frame both the centripetal and centrifugal forces exist, and they cancel each other out so that the object remains at rest.
stackexchange-physics
{ "answer_score": 3, "question_score": 2, "tags": "rotational dynamics, reference frames, inertial frames, centripetal force, centrifugal force" }
Socket.IO Library Obj-C error I started implementing Sockets with Socket.IO in my apps and web applications, I tried using different libraries for iOS (`socket.IO-objc` & `RocketIO`) but they both display an error when I try to run it. Maybe someone can help me :) an image ! Thank you so much Anton
Add `libicucore.dylib` to your project. That was a issue on SocketRocket github (that I suspect to be on se same basis that the ones you're using).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ios, objective c, sockets" }
How to add variable in existing class in swift? I know that in swift we can use `Extensions` to add new methods to existing classes. **But what about if i want to add a variable?** extension UIViewController { var myVar = "xyz" } It gives like : > Extensions must not contain stored properties
We can't add the `stored properties` to `extensions` directly but we can have the `computed variables`. extension UIViewController { var myVar: String { return "xyz" } } > Extensions in Swift can: * **Add computed instance properties and computed type properties** * ... For more please visit <
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 7, "tags": "ios, swift, extension methods" }
best way to check performance of web application what is the best tool (open or commercial) currently available, that lets me send customized requests to a web server and get back a response to check the performance? i will be sending it a load of more than 20K per second, but i need to get numbers for each call made. also, the numbers might be in some microseconds or nanoseconds. How in this small measurement unit, can i work out a baseline and a benchmark?
If you're using Apache, Apache AB is a benchmarking to test how many requests your serve can serve per second and how well it handles load and concurrency. It's an open-source project - check it out here. In addition, wikipedia has a nice list of benchmarking software for testing servers.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 5, "tags": "performance" }
Where does Password Management module's files are located in SugarCRM CE version 6.5.x? I want to add some more functionality in Password Management module in SugarCRM CE version 6.5.x. I have seen functionality of SugarCRM Ultimate Edititon and I want to add same functionality in Community Edition. But the problem is I don't know where the files are located to get above mentioned features. Please guide me on this issue. Thank you.
You will find those files in the **_custom/modules/Users_** directory and also in **_Custom/modules/Administration_** directory
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "module, passwords, sugarcrm" }
Is $(x^3-x^2+2x-1)$ prime in $\mathbb{Z}/(3)[x]$? This is somewhat of a follow up on this question: [Why is $(3,x^3-x^2+2x-1)$ not principal in $\mathbb{Z}[x]$?]( I'm curious, is $\mathbb{Z}[x]/I$ a domain, with $I=(3,x^3-x^2+2x-1)$? I know $I$ is not principal. Also, I took the sequence of epimorphisms $$ \mathbb{Z}[x]\stackrel{\varphi}{\longrightarrow}\bar{\mathbb{Z}}[x]\stackrel{\pi}{\longrightarrow}\bar{\mathbb{Z}}[x]/\bar{I} $$ where $\bar{I}=(\bar{x}^3-\bar{x}^2+\bar{2}\bar{x}-\bar{1})$ is the image of $I$ in $\bar{\mathbb{Z}}:=\mathbb{Z}/(3)$. Since the kernel of $\pi\circ\varphi=I$, I know $\mathbb{Z}[x]/I\simeq\bar{\mathbb{Z}}[x]/\bar{I}$. The latter is a ring of $27$ elements, but I don't want to go through and verify by hand that it is a domain. I know it's a domain iff $\bar{I}$ is prime, but I can't tell if it is or isn't. How can I efficiently tell if $\bar{\mathbb{Z}}[x]/\bar{I}$ is a domain? Thank you.
Let $F$ be the field with $3$ elements. Since $F[x]$ is a unique factorization domain, a principal ideal $(f)$ being prime is equivalent to $f$ being irreducible. In your case $f$ is a cubic polynomial, so being irreducible is equivalent to not having any roots in $F$. Just check the three values: $f(0)=-1$, $f(1)=1$, and $f(2)=1$ (all modulo $3$). Thus $f$ is irreducible and the ideal it generates is prime.
stackexchange-math
{ "answer_score": 4, "question_score": 4, "tags": "abstract algebra, polynomials, ring theory, principal ideal domains" }
MYSQLI query to get one single result I need to get only the id of member who's username is X from the mysql database. Can this only be done with a while loop or is there any other way around this? What I'm thinking of is something like: $id = mysqli_query($con,'SELECT id FROM membrs WHERE username = '$username' LIMIT 1) Thanks,
You can use: mysqli_fetch_array(); // For Instance $id_get = mysqli_query($con, "SELECT id FROM membrs WHERE username='$username' LIMIT 1"); $id = mysqli_fetch_array($id_get); echo $id['id']; // This will echo the ID of that user // What I use is the following for my site: $user_get = mysqli_query($con, "SELECT * FROM members WHERE username='$username'"); $user = mysqli_fetch_array($user); echo $user['username']; // This will echo the Username echo $user['fname']; // This will echo their first name (I used this for a dashboard)
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 4, "tags": "php, mysql, mysqli, get" }
How to change URL of my application from localhost to server? Please guide me how to change URL of my application from localhost to server. For example for the page Active.aspx local path that I'm getting is here. and I want to get this is:
Assuming you want the site to still be on your machine: * Open notepad as Administrator * Open C:\windows\system32\drivers\etc\hosts * add a line '127.0.0.1 domain.com' without the '' * save file, close notepad * open iis * create a site and give it the hostheader domain.com * point the site root at your files BINGO! (Let me know if you get stuck and I'll update answer) (If you mean how to you put it live and available to everyone, read more of the internet!!)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net, iis, localhost, hosting" }
How to fix "System.Reflection.TargetException" error in .NET why when I get back to the page an error pops up System.Reflection.TargetException: „A target object is required for the non-static method.” public ActionResult HistoryOrder(int id) { var orderList = db.OrdersItems.SingleOrDefault(x => x.OrderItemsId == id); orderList.IsHistory = true; db.SaveChanges(); return RedirectToAction("ListYourProduct"); } public ActionResult ListYourProduct(string userId) { var user = UserManager.FindById(userId); var orderItems = db.OrdersItems.Where(x => x.UserName == user.UserName && x.IsHistory == false).ToList(); return View(orderItems); } <a href="@Url.Action("HistoryOrder", "Order", new { id = item.OrderItemsId, userId = User.Identity.GetUserId()})">Archiwizuj</a>
remove the userId = User.Identity.GetUserId() from route in link and get it in the controller by public ActionResult ListYourProduct() { var userId = User.Identity.GetUserId(); var user = UserManager.FindById(userId); var orderItems = db.OrdersItems.Where(x => x.UserName == user.UserName && x.IsHistory == false).ToList(); return View(orderItems); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, .net" }
Entity Framework generic DbSet to List I'm try to bind generic `DbSet` to `Combobox` like this: public static void BindComboboxByEntity(ComboBox combo, Type type, string displayMember, string valueMember, string orderBy) { if (combo is ComboBox) using (var db = new MyDbContext()) { combo.ValueMember = valueMember; combo.DisplayMember = displayMember; combo.DataSource = db.Set(type).OrderBy(orderBy); } } Calling: BindComboboxByEntity(MyCombo, typeof(MyEntity), "name", "id", "name"); But I know that I need to convert `IQueryable` to `List` for binding data to `Combobox`. How can I doing this?
if you are passing `Type type`, try this var result = db.Set(type).OrderBy(orderByString).ToListAsync(); combo.DataSource = result.Result; but my suggestion would be pass a generic class/entity public static void BindComboboxByEntity<T>(ComboBox combo, string displayMember, string valueMember, string orderBy) where T : class { if (combo is ComboBox) using (var db = new MyDbContext()) { combo.ValueMember = valueMember; combo.DisplayMember = displayMember; combo.DataSource = db.Set<T>().OrderBy(orderBy); } } then pass it as BindComboboxByEntity<MyEntity>(MyCombo, "name", "id", "name");
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, .net, entity framework, linq" }
I'm making an rss reader and would like to display pictures from an article if there are any. How do I go about getting those pictures? I'm new to web development and have started using JSONP and Google's Feed API to get the RSS articles using client side javascript. If I must gather the photos from my server that's alright but doing it on the client side is preferable. I have absolutely no idea how to get the relevant photo to an article. I hope its not as bad as having to download the web page's html and looking for gif and png links. Any helps is appreciated!
If I'm not mistaken the images might be returned in the RSS feed itself, and you just have to run through the feed looking for images to paste out. If they don't include the images in the feed then you are going to have to download the page and look for the links to images.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, html, json, rss, png" }
Tuple list as key of dictionary in Python I have a tuple list, File2, that its value is as below: (1,2,[3,4],2) (3,5,[2,3,4,5,6,7],3) I also have data frame that has a column named "Count" and I want to build a dictionary that have my tuple list as key and "Count" column as value: File3 = dict(zip(File2,df.Count)) But I am getting this error: unhashable type: 'list' Could you please tell me how can I solve this issue?
`[3,4]` in `(1,2,[3,4],2)` is a list. Lists aren't hashable, and only hashable objects may be the keys of dictionaries. To turn all lists into tuples, you can write a function like def make_tuples(l): return tuple(make_tuples(i) if isinstance(i,list) else i for i in l) The above fails if there is a tuple that contains a tuple that contains a list. That's probably not going to come up, but in that case do from collections.abc import Sequence def make_tuples(l): return tuple(make_tuples(i) if isinstance(i, Sequence) else i for i in l)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, dictionary, tuples" }
Get the highest value of the last 7 days with SQL I would like to fetch the highest value (from the column named value) for the 7 past days. I have tried with this sql: SELECT MAX(value) as value_of_week FROM events WHERE event_date > UNIX_TIMESTAMP() -(7 * 86400); But it gives me 86.1 that is older than 7 days from today´s date. Given the rows below, I should get 55.2 with date 2014-05-16 07:07:00. id value event_date 1 28. 2014-04-18 08:23:00 2 23.6 2014-04-22 06:43:00 3 86.1 2014-04-29 05:32:00 4 43.3 2014-05-03 08:12:00 5 55.2 2014-05-16 07:07:00 6 25.6 2014-05-19 06:11:00
You are comparing unix time stamps to date. How about this? SELECT MAX(value) as value_of_week FROM events WHERE event_date > date_add(now(), interval -7 day);
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "sql" }
It's possible to put binary files on nexus repository? At my work all development uses Java technology, and we use Nexus to manage our Maven repositories. But for a new project, the build requires dll and exe artifacts. Is it possible to put those windows binary files into a Nexus repository? Is there some plugin to make this simpler? Is what I'm trying to do crazy?
I use Nexus to store all the binary dependencies that I download from the internet. You can upload the files using the Nexus GUI or use the Maven command line as follows: mvn deploy:deploy-file \ -Durl=$REPO_URL \ -DrepositoryId=$REPO_ID \ -DgroupId=org.apache.maven \ -DartifactId=maven \ -Dversion=2.2.1 \ -Dpackaging=zip \ -Dfile=maven.zip This will generate the POM for your zip package automatically. To retrieve dependencies, you can just navigate to the Nexus URL, or use a generic dependency manager tool like ivy: java -jar ivy.jar -dependency org.apache.maven maven 2.2.1 -retrieve [artifact].[ext]
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 15, "tags": "repository, binaryfiles, nexus" }
How to store intermediate state in a Java stream processing I have the following Java loop: for (final Long orderNumber : availableOrderIds) { final List<ReservationDetailResponse> reservations = tryToReserve(orderNumber); if (successful(reservations)) { return withReservationIdFrom(reservations); } } And methods: private boolean successful(final List<ReservationDetailResponse> reservations) { return !reservations.isEmpty(); } private Long withReservationIdFrom(final List<ReservationDetailResponse> reservations) { return reservations.get(0).getReservationId(); } How do I convert it into a stream processing? Thanks for any help!
Using `map` for transformation, `filter` for conditions and `findFirst` you can do somethign like: return availableOrderIds.stream() .map(this::tryToReserve) .filter(this::successful) .findFirst() .map(this::withReservationIdFrom) .orElse(0L); // assumed as default value Additionally, provided the utilities, you can include them within the operations as well: return availableOrderIds.stream() .map(this::tryToReserve) .filter(res -> !res.isEmpty()) .findFirst() .map(res -> res.get(0).getReservationId()) .orElse(0L);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, functional programming, java stream" }
Best syntax to test event target in jQuery I have a keypress handler bound to all input elements on a form, and I need to perform different operations depending on which element received the keypress. All 3 variations below work, but I'd like to know if one (or something else) is preferred and why. $(':input').keypress(function(e) { if($(this).attr('id') === 'foo') // option 1 console.log('foo'); if($(this)[0] === $('#bar')[0]) // option 2 console.log('bar'); if(e.target === $('#baz')[0]) // option 3 console.log('baz'); }); There are few elements on the page, so performance isn't really a concern. It's more of a stylistic/standards/readability issue.
Option #4: $(':input').keypress(function(e) { if(this.id == 'foo') console.log('foo'); }); `this` will be a DOM element in the handler, no need for the jQuery object checks, just do a string comparison against the native `.id` DOM property, it's clear, concise and the fastest - win, win here.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "jquery" }
Why isn't the value echoed? I'm trying to print a value input in the form, but it's not working. If I use GET instead of POST, it works. Why is it so? Is there something wrong? Here's my code: <?php if(isset($_REQUEST['sub']) && isset($_POST["numb"])){ echo $_POST["numb"]; } ?> <body> <form name="form" action=""> <input type="number" name="numb"></input> <input type="submit" name="sub"></input> </form> </body>
You need to add the method attribute to your form, it specifies how to send form-data: <form name="form" method="POST"> Or you can change `$_POST` to (`$_GET` or `$_REQUEST`). `$_REQUEST` by default contains the contents of `$_GET`, `$_POST` and `$_COOKIE`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Situation with SQL query I have data in table in below format id brand_ids -------------- 2 77,2 3 77 6 3,77,5 8 2,45,77 -------------- (Note the brand ids will be stored like comma separated values, this is common for values in this field) Now i am trying to get a query which is capable of querying out only rows which have '77' in it.. I know i can use LIKE command in three formats `LIKE '77,%' OR LIKE '%,77,%' OR LIKE '%,77'` with or condition to achieve it. But i hope this will increase the load time of the sql. is there any straight forward method to achieve this? if so please suggest. Thanks, Balan
A strict answer to your question would be: no. Your suggestion of using LIKE is your best option with this data model. However, as mentioned, it is highly suggested that you use a more normalized model.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -2, "tags": "sql" }
Why isn't bash accepting any value for first element of array? So apparently arrays in bash have specials rules for what might be the first element, any explanation for this? jgo ~$ myarray=(-n foo) && echo ${myarray[@]} foo jgo ~$ myarray=(-v foo) && echo ${myarray[@]} -v foo jgo ~$ myarray=(-a foo) && echo ${myarray[@]} -a foo jgo ~$ myarray=(-e foo) && echo ${myarray[@]} foo
Actually, your output should look more like this: jgo ~$ myarray=(-n foo) && echo ${myarray[@]} foojgo ~$ myarray=(-v foo) && echo ${myarray[@]} -v foo jgo ~$ myarray=(-a foo) && echo ${myarray[@]} -a foo jgo ~$ myarray=(-e foo) && echo ${myarray[@]} foo The reason is that `-n` and `-e` are valid options to `echo` whereas the other ones you tried aren't.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "arrays, bash" }
Dotted border doesn't appear right at either ends Something which has been frustrating me is the CSS `border:dotted;` rule. I have been using this below: border-bottom:#1C9AD5 dotted 2px; If you take a look at my example, and look at the blue dotted line it goes a bit weird at either end (it looks as though there's two dots really close together). I know I can easily get around this by using an image but that isn't the point!
Posting my earlier comment as a solution based on Jason's comment: "Looks like it is only on certain zoom levels for Chrome. I don't know how to zoom on a mac, but on Windows, you hold CTRL and roll your mouse wheel."
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "css" }
Derivative of the inverse of a matrix in regards to a product I am having problem with: $$ \frac{\delta AX^{-1}B}{\delta X} = \space ? $$ What I did is the following: $$ I = XX^{-1} $$ $$ \frac{\delta AXX^{-1}B}{\delta X}=A \frac{\delta X}{\delta X}X^{-1}B + AX \frac{\delta X^{-1}}{\delta X}B $$ $$ AX \frac{\delta X^{-1}}{\delta X}B = -A\frac{\delta X}{\delta X}X^{-1}B $$ $$ (A) (AX)^{-1} AX \frac{\delta X^{-1}}{\delta X}B = -(A)(AX)^{-1}A \frac{\delta X}{\delta X}X^{-1}B $$ $$ A \frac{\delta X^{-1}}{\delta X}B = -AX^{-1} \frac{\delta X}{\delta X}X^{-1}B $$ $$ \frac{\delta AX^{-1}B}{\delta X} = -AX^{-1}X^{-1}B $$ But in the Matrix Cookbook the result for inverse of a trace is: $$ \frac{\delta tr(AX^{-1}B)}{\delta X} = -(X^{-1}BAX^{-1}){T} $$ From which I conclude that it should be $$ \frac{\delta AX^{-1}B}{\delta X} = -X^{-1}BAX^{-1} $$ And I cannot find the reason why the BA is inside and switched places and please do not use frobenious product for solution.
Alternative to greg's fourth-order tensor, one can vectorize and exploit Kronecker products. Using differential result of greg's solution, that is, \begin{align} dY = -\underbrace{AX^{-1}}_{:=\color{blue}{\widetilde{A}}} \ \color{red}{dX} \ \underbrace{X^{-1}B}_{:=\color{green}{\widetilde{B}}} := -\color{blue}{\widetilde{A}} \ \color{red}{dX} \ \color{green}{\widetilde{B}}, \end{align} we now vectorize#Compatibility_with_Kronecker_products) both sides such that \begin{align} \operatorname{vec}\left(dY\right) = -\operatorname{vec}\left(\color{blue}{\widetilde{A}} \ \color{red}{dX} \ \color{green}{\widetilde{B}}\right) = -\left(\color{green}{\widetilde{B}}^T \otimes \color{blue}{\widetilde{A}}\right) \operatorname{vec}\left(\color{red}{dX}\right). \end{align} Then, the gradient can be written as \begin{align} \frac{\partial y}{\partial x} = -\left(\color{green}{\widetilde{B}}^T \otimes \color{blue}{\widetilde{A}}\right) . \end{align}
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "matrices, derivatives, inverse, matrix calculus" }
How can user enter a link In a textarea, how can a user enter a link? I am using jquery mobile. Would the user just have to enter Text Or should I have a button that adds the tags when it is clicked, and will that work?
best to use a wysiwig control for this. below is a link to 10 of the best < YOu will need to make sure it is compatible with jquery mobile though
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "jquery, mobile, input, hyperlink, textarea" }
Trying to find a quote by Pema Chodron I'm looking for a quote by Pema Chodron. In my memory, she's having a discussion with a Zen master, and the quote goes something like this; Pema: "what do you do when things fall apart?" Zen Master: "I stay" I seem to remember it being in her book When Things Fall Apart, but I searched it for the word 'stay' and I couldn't find this anywhere. Does anybody recognise where it comes from? Maybe it's from a video or an audio recording of an interview with her? Maybe it exists only in the recesses of my memory?
Here is the quote I was looking for last year, > I once asked the Zen master Kobun Chino Roshi how he related with fear, and he said, "I agree. I agree." It is on page 9 of my copy, which is a 2005 edition printed on the Element imprint of HarperCollins.
stackexchange-buddhism
{ "answer_score": 1, "question_score": 6, "tags": "reference request, zen" }
AppleScript copy/duplicate only newer files I have created an AppleScript that mounts a network smb share, creates folders if they don't exist then copy files to these new folders. I am using: duplicate items of folder <source> to <destination> with replacing This will copy over and replace all the files. Is there a way to only duplicate newer files? Should I be using rsync rather than duplicate?
I'd definitely use rsync, with possibly the -a flag (archive option, it will work recursively along with other mirroring options, check the man page for better options for you) rsync -a (source) (destination) Call from applescript using the _do shell script_ command, making sure you pass in posix paths. eg, set source_path to quoted form of POSIX path to source set dest_path to quoted form of POSIX path to destination do shell script "rsync -a " & source_path & " " & dest_path
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "copy, applescript, rsync" }
Acceleration as $\frac{D\vec u}{Dt}$ in the case of unsteady flow In the book of Acheson, it is stated that the material derivative $\frac{D\vec u}{Dt}$ can be considered as an acceleration of a "fluid element" \- which is something the author never defined, but my understanding is that a "fluid element" is a physical volume that moves with the streamline it started with such that the fluid particles contained in that volume at any given become the corresponding "fluid element". However, they also mention that (see exercise 1.8) that when the flow is unsteady, the particle trajectories will not be the same as the streamlines. So, does this mean that the concept of acceleration for a fluid element via $\frac{D\vec u}{Dt}$ is only meaningful and defined for a steady-flow?
You just have to change your "definition" : a "fluid element" is a physical volume that moves along the **pathline**. (But this is the definition of a pathline !) It is simply necessary to follow a material particle of fluid between $t$ and $t + dt$ along its trajectory (pathline). the key point is to note that the velocity of a fluid material particle at time $t$ is the velocity field where the particle is at time $t$. And when time changes, the particle changes location. It is therefore necessary to take into account the variations of the velocity field in time but also in space. What the material derivative shows is that even when the velocity field is not time dependent, a fluid particle moves within the velocity field and therefore can have non-zero acceleration.
stackexchange-physics
{ "answer_score": 1, "question_score": 0, "tags": "fluid dynamics, acceleration, flow" }
Can I submit a PHP form within Cordova? I would need help with Apache Cordova. I would like to submit a PHP $ POST form within Cordova. I am tried this one, but when I send it, it goes to separate browser: Using php form inside phonegap. My PHP / HTML code is largely similar than that one: How to send copy of PHP / HTML form to sender's email? So, main thing would be that I can send the form inside the Cordova app and when I send the form, I do not need to go to separate browser but the transmission takes place inside the app. Thanks for help !
I got my problem to solved, so I answer for my own question. I used iframe to the form, that was already on the server. And then I can send PHP form inside Cordova app.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php, android, html, forms, cordova" }
Draw on Google Maps API Android Is it possible to draw over the map as it was a canvas? Or even better, is it possible to put a transparent layer over a Google Map and dinamically paint over it?
You can put any `View` on top of another `View` like here: <FrameLayout> <fragment class="SupportMapFragment" /> <CustomView /> </FrameLayout> and override `onDraw` to paint what you like.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, android, google maps" }
Docker API, remote API, Client API I would like to know when to use and the difference between Docker API, Docker remote API, Client API and Compose API. TIA.
There is only Docker Engine API, which allows you to manage Docker calling it. Docker API = Docker Engine API Docker remote API = I think this means to configure Docker CLI to connect to a remote API to manage container on other hosts. Client API = Docker CLI. A CLI to use Docker Engine API. Compose API = This doesn't exist, Compose is only a tool to use Docker Engine API. For further information, check Docker Engine API docs: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "docker, docker api" }
Is "Unless if" grammatically incorrect? A friend pointed out to me recently that I have a tendency to preface some of my sentences with the phrase "Unless if..." For example: > Unless if we take the highway, we won't make it in time. She insists that this is grammatically incorrect. Is this, and if it is, how is this sentence wrong? Would this phrasing be still incorrect if, instead, I said: > Unless, if we take the highway, we won't make it in time.
_Unless_ is a kind of negative of _if_ --think of it as very much like "if . . . _not. "_ Adding _if_ to it is thus redundant, confusingly so--it makes it seem as if the main clause is being limited by _two_ conditions, not one. For instance, your last example would only really make grammatical sense in the context of a larger sentence such as this: > Unless, if we take the highway, we won't make it in time, we really should take those scenic back roads. In other words, _if_ it is the case that _if_ we take the highway we shall arrive late, then we should take the highway; otherwise, we should take the back roads, because they are more scenic. There are _two_ conditionals operating here.
stackexchange-english
{ "answer_score": 3, "question_score": 1, "tags": "grammar" }
Why do I get a syntax error when I'm trying to restart Apache? httpd: Syntax error on line 69 of /usr/local/etc/httpd/httpd.conf: Cannot load lib/httpd/modules/mod_authn_file.so into server: dlopen(/usr/local/opt/httpd/lib/httpd/modules/mod_authn_file.so, 10): image not found
Your Apache configuration in **httpd.conf** , line 69 tries to use authn_file mod, which should be defined in the **mod_authn_file.so** at the location of > **/usr/local/opt/httpd/lib/httpd/modules/mod_authn_file.so** You will need to ensure that * the path is correct * the file is there * the file is not corrupted * the user running the webserver has access to that path or, if you do not need that mod, then you can switch it off.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, apache" }
What is the function to the following graph? What is the function to the following graphs? I am just looking for a rough estimate. It doesn't need to match the exact graph. !enter image description here
It depends on what you think is happening to the right. Clearly it goes to infinity for $x=0$ so there is a denominator of $x^n$. If they each approach a constant, I would say each is $a+x^{-n}$. The fact that the corner on the green one is sharper than the others would say it has a greater $n$. I would collect some points from each graph, estimate the asymptote, and see what $n$ fits best. If you think the rise of the red one toward the right is real, you could add a term $+bx$ for a rather small $b$.
stackexchange-math
{ "answer_score": 1, "question_score": 2, "tags": "graphing functions" }
How to open the multiple pdf files in a new windows using asp.net In my application have grid view with check boxes, **select multiple checkboxes click on print button open the pdfs in seperate windows.** my code is for (int i = 0; i < grdAdditionalInsured.Rows.Count; i++) { CheckBox chk = (CheckBox)grdAdditionalInsured.Rows[i].Cells[0].FindControl("chkAdditionalInsured"); if (chk.Checked == true) { //**some code to get the id based on values** string file = "/CertPrints/" + id.ToString() + ".pdf"; String js = @"WindowPopup('" + file + "');"; ScriptManager.RegisterStartupScript(this, this.GetType(), file, js, true); } } Above code show only last record pdf file, please give me suggestion .
Try this: StringBuilder js = new StringBuilder(); for (int i = 0; i < grdAdditionalInsured.Rows.Count; i++) { bool checked = ((CheckBox)grdAdditionalInsured.Rows[i].Cells[0].FindControl("chkAdditionalInsured")).Checked; if (checked) { //**some code to get the id based on values** js.AppendFormat(@"WindowPopup('/CertPrints/{0}.pdf');",id)); } } ScriptManager.RegisterStartupScript(this, this.GetType(), "filePopup", js.ToString(), true);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net, c# 4.0, pdf, itext, scriptmanager" }
changing repeats value of UNTimeIntervalNotificationTrigger i have a local notification that i am repeating every 60s: var trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true); i want to change the `repeats` value of the `UNTimeIntervalNotificationTrigger` from `true` to `false` if a certain condition is met i.e.: if (condition) { trigger!.repeats = true; } however this doesn't seem to work as i dont think i can change the `repeats` value after creating the object. is there any way to do what i'm trying to do?
You can remove the local notification as UIApplication.shared.cancelAllLocalNotifications() And if you want to `true` again then again assign trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true) May be this Work
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "swift, repeat, localnotification" }
Consecutive integers that can be written as the product of three distinct primes Mathematica novice here. I want to start with a list of integers that are the product of three distinct primes m,n, and o, where 2 <= m|n|o < 2000. Sort[Times @@@ Subsets[Select[Range[2000], PrimeQ], {3}]] How do I find the longest subsequence within this list that consists of consecutive integers?
Select[Split[Sort[Times @@@ Subsets[Prime@Range@PrimePi@100, {3}]], #2 == #1 + 1 &], Length@# >= 3 &] ( {{1885, 1886, 1887}, {2013, 2014, 2015}} *)
stackexchange-mathematica
{ "answer_score": 3, "question_score": 1, "tags": "prime numbers" }
In C#, what is the purpose of marking a class static? In C#, what is the purpose of marking a class static? If I have a class that has only static methods, I can mark the class static or not. Why would I want to mark the class static? Would I ever NOT want to mark a class static, if all the methods are static, and if I plan to never add a non-static method? I looked around and saw some similar questions, but none that were just like this.
Marking a class as static is a declarative statement that you only intend for this type to have static and const members. This is enforced by the compiler and prevents you from accidentally adding an instance method to the type. Other advantages * Extension methods can only be defined in static classes * Prevents users from creating an instance of the class * Prevents use of the type as a generic argument (thanks Eric!)
stackexchange-stackoverflow
{ "answer_score": 28, "question_score": 26, "tags": "c#, .net, class design" }
How to get the product count without using lambda expressions? I have a table products: product_id product_name prodcut_price My dbcontext name is `abcentity`. I want to get how many number of products (like products count) along with `product_id`,`product_name`,`product_price`. I have done using lambda expressions using `Groupby product_id` (this is for Linq to Sql, but I am using linq to entity). I don't want to use lambda expressions. Is it possible to get the product count without using lambda expressions?
Are you just trying to avoid lambda syntax? You can use the `group by` clause in LINQ query expression syntax instead of calling `.GroupBy()`. from p in abcentity.products group p by p.product_id into g select new {g.Key, g.Count()} But I should point out that this still gets compiled as a lambda expression. All you're changing is the syntax you use to represent it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, .net, winforms, entity framework, linq to entities" }
awk separator preferences I write ad hoc awk commands in cygwin to process tab delimited files. Pretty much every command starts with: BEGIN {FS="\t";OFS="\t";ORS="\r\n";} How can I make these separators the default to avoid typing them every time?
Probably the easiest way would be to use a shell alias (add it to `~/.bashrc` or your shell's equivalent): alias awktab="awk -v FS='\t' -v OFS='\t' -v ORS='\t'"
stackexchange-unix
{ "answer_score": 1, "question_score": 4, "tags": "awk" }
Prove that $\lim_{n \to \infty} \sqrt[n]{a} = 1$ using only the basic properties of sequences Prove that $\lim_{n \to \infty} \sqrt[n]a = 1$ using only the basic properties of sequences I don't have an idea on how to tackle this problem - I thought about the Squeeze Theorem but I can't think of a sequence of n which approaches 1. Could you give me some hints on how to solve this? If it is possible, please, choose the least sophisticated method to solve this as I am entirely new to Calculus.
It's easier to prove first for $a\geq 1$ and then use that to prove for $a<1$. Specifically, we use that if $x>0$ then $(1+x)^n\geq 1+nx$. This is from the binomial theorem. If $x=\sqrt[n]a-1$ this means that $$a\geq 1+n\left(\sqrt[n]a -1\right),$$ and therefore that $0\leq\sqrt[n]{a}-1\leq \frac{a-1}{n}$. The case $0<a<1$ is a little harder. You can use that $\sqrt[n]a=\frac1{\sqrt[n]{1/a}}$ and use the limit of $1/a$ to get the limit for $a$. Namely, if $b=\frac{1}{a}$: $$0\leq 1-\sqrt[n]a=\frac{\sqrt[n]b -1}{\sqrt[n]{b}}\leq \sqrt[n]b-1$$ * * * Another approach is to use that $x^n-1=(x-1)\left(1+x+x^2+\cdots+x^{n-1}\right)$. Then, with $x=\sqrt[n]a$ you get: $$\sqrt[n]{a}-1=\frac{a-1}{\sqrt[n]{a}^{n-1}+\cdots+\sqrt[n]{a}+1}$$ When $a\geq 1$ this means that $0\leq \sqrt[n]{a}-1\leq \frac{a-1}{n}.$. When $0<a<1$ you have $a\leq\sqrt[n]{a}^k$ for $k=1,\dots n-1$ so: $$0\leq 1-\sqrt[n]{a}\leq \frac{1-a}{1+(n-1)a}$$
stackexchange-math
{ "answer_score": 4, "question_score": 0, "tags": "calculus, sequences and series" }
How to export a state in react native, and import it into another file? (NOT COMPONENT) I am trying to export this state: `const [jsonText, setJSONText] = useState();` out of my file. I tried a simple `export const jsonText;`, but that did not work at all. I tried looking it up, but they were all for components. Is there a way I can do this, and to keep making sure that the constant is still updating even when it's in the other file? I tried passing it as a prop and that did not work. Thanks.
State can't be import or export and only can be passed as a prop or by using context API. I would advise you to learn about state and react in general. Here are some resources: * Official React docs * React JS Crash Course
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "reactjs, react native, state, react props" }
iOS7 changes UIView width I discovered this problem only on iOS7, so I assume that it's related to the new iOS, although I could be wrong... So, I have the main `UIView` \- `self.view`. It's `width` is set to 320.0 in IB, and nowhere in the code do I change the frame size. However, when I load the view controller for the first time (say, launch the app), the `self.view.frame.size.width` is set to 310.0 (so says the `NSLog`). Then when I leave the view controller and come back to it again, it's 320.0 again as expected. Any ideas as to why this is happening?
Be sure that there are no constraints, by using Interface Builder, causing your view to behave differently at runtime. Often IB will warn you if view elements will not appear where you would expect, and new with Xcode 5 you can easily remove all constraints, then add back in what you need one at a time.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "objective c, uiview, ios7" }
how to remove negetive value in nested list I start python programming new and I have write this code y=[[-1,-2,4,-3,5],[2,1,-6],[-7,-8,0],[-5,0,-1]] for row in y: for col in row: if col<0: row.remove(col) print(y) In this code I want to remove elements that have negative value, but when two negative value is together the code does not delete or remove the second value, what can I do? please help me.
You may never remove items form a list while iterating it, you'd keep the ones you need, the positive ones y = [[col for col in row if col>=0] for row in y]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 8, "tags": "python, list" }
How do you change the textcolor of the list items in an AlertDialog Hello I am trying to change the text color of the items in a list on a `ListPreference` pop up window. I have spent over an hour looking through all of the various style names but I can't find `TextAppearance` or anything that goes to this particular text. Thanks for your help!
You can't and you shouldn't. `*Preference` uses styles from `com.android.internal.R.styleable` which might be changed by manufactures. The idea of using the default ones is that every preference screen in your device look alike. On the other hand you can try doing an `Activity` with `android:theme="@android:style/Theme.Dialog"` in your app's `AndroidManifest` and place a `ListView` styled as you want.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 6, "tags": "android, coding style, themes, android alertdialog, listpreference" }
Was the "Earthrise" witnessed by Apollo 8 the first available "full" photo of the Earth? Was the video/photos taken during the earth-rise on the Apollo 8 flight the first "blue marble"-esque photo? I've heard the image equated to the "earth's first selfie" and question the technical accuracy of that premise. ![ *Note to pedants: Seeing other similar type questions on the site, please understand the _concept_ of what I'm asking, if not the accuracy. Yes, you can only take, at best, a photo of only half the earth at a given time, and yes, during Apollo 8 the Earth was partially in shadow....
No; the first full views of Earth from high-altitude satellites predate Apollo 8 by at least two years. This web page has a nice progression of pictures of Earth from space from 1959 on. A Soviet satellite (possibly Molniya-1-3) took this crude picture on May 30, 1966: ![enter image description here]( DODGE) took this picture in September of 1967; this is believed to be the first full-color, full-Earth picture: ![enter image description here]( ATS-III sent this photo in November of 1967, which famously became the cover image for the first edition of the Whole Earth Catalog (Apollo 8's much prettier Earthrise photo adorned later editions): ![enter image description here](
stackexchange-space
{ "answer_score": 44, "question_score": 36, "tags": "history, photography, earth" }
TransferOwnership in Tezos Is there an analog of transferOwnership in Tezos? It looks like it's possible to make custom FA2 contract and change owner. Is this correct? Looking for an authorative answer
There is no notion of owner of a smart contract in Tezos (anymore). However, smart contracts can implement some custom logic to describe what managing them means (and typically store some admin address in their storage).
stackexchange-tezos
{ "answer_score": 1, "question_score": 0, "tags": "smart contracts, smartpy, ligo" }
How can i trigger a sharepoint designer workflow using javascript on multiple list items Is it possible to run single workflow instance for multiple items? I have spd 2010 workflow i have created and I would like to trigger the workflow via a button on a sharepoint page. The trigger should cause the workflow to update each items not just one I have read that my my options could be to use rest api/spservices Will SPServices work with sharepoint online? Any resources would be appreciated
There is rest api `/_api/SP.WorkflowServices.WorkflowInstanceService.Current/StartWorkflowOnListItemBySubscriptionId(subscriptionId='subscriptionId',itemId='item id')` to start workflow for single item, so you could iterate the items and start one by one. You could check this thread for sample code.
stackexchange-sharepoint
{ "answer_score": 2, "question_score": 3, "tags": "sharepoint online, workflow, designer workflow" }
Change in behavior in Tomcat when redirecting to an empty string The code below generates a different response when running under different releases of Tomcat. response.sendRedirect(""); Under Tomcat 7.0.47, Location header in the respons is set to Under Tomcat 7.0.69, Location header is set to an empty string. Is this configurable? Is the difference in behavior due to different configurable settings int the two Tomcat instances? Or is it a deliberate change in behavior and requires code change to compensate for?
Tomcat change the behavior after version v7.0.67/v8.0.30, due to this bug. You can set `useRelativeRedirects="false"` in Context config or add system property `org.apache.catalina.STRICT_SERVLET_COMPLIANCE=true`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jsp, tomcat, redirect" }
How to notify user on job completed I would like to display a popup when job is finished. I have servlet which is using executor for executing long jobs. Tasks can take 20 minutes how can I display popup when job is completed to any jsp view where user is right this time(session)? For example user submitting form in servlet job is submitted to executor, servlet send some response and redirect to /view1 user is using another modules of web (/view2 /view3 etc), when job is completed and user is at /viewX he in the middle of page get popup "Your task _SUPER TASK_ has finished". I know it's possible to do because this mechanism is implemented in Jira atlasian Thank You in advance
This functionality shouldn't be done in JSP or servlet, you could write few lines of javascript that will periodically ask a server for a status of the job. When the job is done it should display the popup. If for whatever reason you prefer to do it in JSP then the user will only get the popup if he refreshes the page.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jsp, servlets, jakarta ee" }
How to edit or add names after assigning Suppose my code is this ranks <- 1:3 names(ranks) <- c("one","two","three") Running 'ranks', Output will be like this one two three 1 2 3 Now I am able to change values 1, 2, 3. But I am unable to change or add - one or two or three. Why? and how to replace them? for suppose replace 'three' with 'third'. Thanks in advance!
Just change the names vector > names(ranks)[3] <- "third" > ranks one two third 1 2 3
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -3, "tags": "r" }
How to programmatically retrieve the total number of Google +1's for a URL Now that Google has officially released their +1 button for websites, I'd like to find a way to retrieve the total number of +1's for a specific URL programmatically. For example, I'd like to access this value independently of the +1 button for use in tooltips, as shown for RSS subscribers below. !Social Widget More information on the +1 button: <
**Google+ metrics: Activity by URL** gives the sum total of all +1's for a URL, as well as the number of +1's for a specified time frame. It is only accessible via Google Analytics on the webmaster dashboard. EDIT Google now has an API for retrieving Google +1's. It is still in early developer preview though. **Google+ History API** tells you how to sign up for the preview.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 5, "tags": "api, google plus one" }
how to get value of a jquery cloned textbox? I'm creating a survey question that has multiple answers. There is a `button` to clone the existing `textbox`. however, how do I get the value of those cloned `textbox`, especially from the codebehind. Here is my code: function generateRow() { if (totalans == 9) { $('#<%= label2.ClientID %>').html('<b>Maximum of 10 answers per questions reached</b>'); } else { $("#ans").clone().prependTo("#ans2"); totalans = totalans + 1; } //#ans is a division. Could anyone help me please. I tried to get it. //c# code behind `String bla = tb_ans.ToString(); String[] splitAnswer = bla.Split(','); int a = splitAnswer.Length;` //tb_ans is my textbox id. I tried to use an array, but it seems it only took the first `textbox` value while dumping the others.
After viewing your comment i've revised my answer: function generateRow() { if (totalans == 9) { $('#<%= label2.ClientID %>').html('<b>Maximum of 10 answers per questions reached</b>'); } else { totalans = totalans + 1; // same as totalans++; $("#ans").clone().attr({id: "ans_clone_" + totalans, name: "ans_clone_" + totalans}).prependTo("#ans2"); // then you can loop through each input using the totalans variable. }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "jquery, textbox, get, clone" }
Property 'toDate' does not exist on type 'Date' Angular firestore I am trying to convert `timestamp` object from Firestore to `Date` object in TypeScript using `toDate()`. import { AngularFirestore } from '@angular/fire/firestore'; ... constructor(private database?: AngularFirestore) {...} ... const someVariable = a.date.toDate(); Although the functionality is working fine in development mode but I am getting TypeScript compile check error. Also I am not able to build prod version (using `ng prod`) because of this error. > a.date.toDate() ~~~~ src/app/project/some.service.ts:74:36 - > error TS2339: Property 'toDate' does not exist on type 'Date'. Any suggestions how do I resolve this?
toDate() does not work on Date, String, Number etc. Change type of your **date** to **any** for Timestamp. date: any; Btw, i would use toDate() usually in html files. It would show error but could compile. Type **any** also will clear html errors.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "angular, typescript, timestamp, angularfire" }
Name for type that has the same width and height I know monospaced type (font) means all characters have the same width. Is there a similar name for fonts where all character have the same width and height?
[As far as I know] **There is no name** for such fonts, because there are too few of them to create a categorization. As mentioned in the comments, _square_ or perhaps _geometric_ could be possible search terms. Your best option is to look for perfectly square uppercase fonts, as these are easier to find. Here is a font with lowercase and a close-enough width-height ratio: **Panoptica** !enter image description here
stackexchange-graphicdesign
{ "answer_score": 9, "question_score": 13, "tags": "fonts, terminology" }
Which matrix represents the similarity between words when using SVD? Two words can be similar if they co-occur "a lot" together. They can also be similar if they have similar vectors. This similarity can be captured using cosine similarity. Let $A$ be a $n \times n$ matrix counting how often $w_i$ occurs with $w_k$ for $i,k = 1, \dots, n$. Since computing the cosine similarity between $w_i$ and $w_k$ might be expensive, we approximate $A$ using truncated SVD with $k$ components as: $$A \approx W_k \Sigma W^{T}_{k} = CD$$ where $$C = W_{k} \Sigma \\\ D = W^{T}_{k}$$ Where are the cosine similarities between the words $w_i$ and $w_k$ captured? In the $C$ matrix or the $D$ matrix?
You can find some material here and here but the idea (at least in this case) is the following: consider the full SVD decomposition of the symmetric matrix $A = W \Delta W^T$. We want to calculate the cosine similarity between the $i$-th column (aka word) $a_i$ and the $j$-th column $a_j$ of $A$. Then $a_k = A e_k$, where $e_k$ is the $k$-th vector of the canonical basis of $\mathbb{R}$. Let's call $\cos(a_i,a_j)$ the cosine between $a_i,a_j$. Then $$\cos(a_i,a_j) = \cos(Ae_i,Ae_j) = \cos(W \Delta W^T e_i,W \Delta W^T e_j) = \cos(\Delta W^T e_i,\Delta W^T e_j)$$ where the last equality holds because $W$ is an orthogonal matrix (and so $W$ is conformal, i.e. it preserves angles). So you can calculate the cosine similarity between the columns of $\Delta W^T$. A $k$-truncated SVD gives a well-enough approximation. In general, columns of $W \Delta$ and rows of $W$ have different meanings!
stackexchange-ai
{ "answer_score": 0, "question_score": 0, "tags": "machine learning, natural language processing, math" }
Autosize jQuery-dialog I have a jQuery UI dialog that is now set to a specific height: $(".event").click(function () { var id=$(this).attr("data-id"); $("<div></div>") .addClass("modal-dialog") .appendTo("body") .dialog({ close: function() { $(this).remove(); }, modal: true, height: 600, width: 700 }) .load("/Home/users?xid=" + id); }); I would like for my dialog to resize its height depending on the content in it. I tried changing to `height: auto` but then it would not open at all. I also found this thread: Automatically resize jQuery UI dialog to the width of the content loaded by ajax But i do not understand how to apply it to my own code.
What i would do is load into a child element, and then set the dialog height to the child's height in the `load` callback: $(".event").click(function () { var id=$(this).attr("data-id"); var dialogElement = $("<div></div>") .addClass("modal-dialog") .appendTo("body") .dialog({ close: function() { $(this).remove(); }, modal: true, height: 600, width: 700 }); $("<div></div>").appendTo(dialogElement).load("/Home/users?xid=" + id, function(){ dialogElement.dialog("height", $(this).height()); }); }); You might want to actually make it slightly bigger than the child, so that there's room for all the UI.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "jquery, jquery ui dialog" }
Finding coordinate in radius Hello i have two points (Vector3) `A` and `B`. And have a radius `r` !enter image description here How can i find a coords of point `P` in a circle by angle?
Solution for 2D vectors: Vector2 AB = B - A; // Vector from A to B Vector2 A0 = r * AB.normalized; // Vector from A to 0° Vector2 A90 = new Vector2(A0.y, -A0.x); // Vector from A to 90° Vector2 P = A + Sin(alpha) * A90 + Cos(alpha) * A0; // Coordinate of arbitrary point on a circle For arbitrary 3D vectors A and B in 3D space you need coordinates of at least one more point on the same plane (but not located on the A-B line).
stackexchange-gamedev
{ "answer_score": 2, "question_score": 3, "tags": "mathematics, vector, linear algebra" }
O365 Send as another user via graph api I am struggling to get a succinct answer. Has anyone had to send emails from an Azure hosted website using the graph api? If so i realise i can use delegated permissions and send as the logged in users. I am also familiar about the fact i can assign application permissions for the Mail.Send property. What i am struggling to understand is that if i create a new user like ServiceAccount1@mytenant.com do i then have to assign the "SendAs" permission on that mailbox for all users of my website? Background: I am creating a pretty standard website hosted in Azure that performs a basic sign off process. The email i am sending is part of a workflow and should come from a generic account, not a user account. Thanks
Based on your description, if you want to use delegated permissions to send emails on that mailbox on behalf of all the other users, you have to assign the "SendAs" permission for all the other users. The answer is **Yes**. In this case, now that you are familiar about the fact you can assign application permissions, you should use **Application permissions** instead of **Delegated permissions** to send the emails.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "email, asp.net core, azure ad graph api" }
SOLR field fallback behavior (using solr 4.10.3) I have a solr schema with three dates: 1. requiredDate (a required field) 2. optionalDate (not required) 3. resolvedDate (populated by #1 or #2) Because I need to use ResolvedDate for sorting, it is multiValued="false". I am trying to populate resolvedDate using the behavior; "Use the optional field value if available, else fallback to the required field value". My attempt with: <copyField source="requiredDate" dest="resolvedDate" /> <copyField source="optionalDate" dest="resolvedDate" /> has failed due to trying to copy multiple values to a single value field. Can I implement a field with this fallback behavior in either the schema or the UpdateRequestHandler definition? How?
You can use a StatelessScriptUpdateProcessor (cf. Update Request Processors) which allows the use of scripts to process documents during update requests. Several global variables are provided for each script defined so you can easily perform the operation you want. You will have to define an UpdateRequestProcessorChain where you can put the script processor definition, and declare the use of your processor chain in your update requestHandler (solrconfig.xml).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "solr" }