INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Extract a substring that is common in ending of first string and beginning of second string Given 2 strings For example: `"Hello World"` and `"World Is Awesome"` It's not exactly union. I need to extract a substring that common in ending of first string and beginning of second string. In example above it would be `"World"`, because the first string is ending with this list of characters and second string starts with it. What is the most efficient way to do it? Could be any language but I'm mostly curious in python and c#. Here is my solution def union_chars(head, tail): match = None for i in range(len(head)): if tail.startswith(head[-i:]): match = head[-i:] return match
Here is how you can use a `for` loop and indices: def union_chars(head, tail): for i in range(len(head)): if tail.startswith(head[i:]): return head[i:] print(union_chars("Hello World", "World Is Awesome")) Output: World Explanation: First, iterate through each index of the `head` string, and check if the `tail` string begins with the index of the `head` string to the end of the `head` string.Template
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -4, "tags": "python, c#, string, substring" }
Is it possible to run function in a subprocess without threading or writing a separate file/script. import subprocess def my_function(x): return x + 100 output = subprocess.Popen(my_function, 1) #I would like to pass the function object and its arguments print output #desired output: 101 I have only found documentation on opening subprocesses using separate scripts. Does anyone know how to pass function objects or even an easy way to pass function code?
I think you're looking for something more like the multiprocessing module: < The subprocess module is for spawning processes and doing things with their input/output - not for running functions. Here is a `multiprocessing` version of your code: from multiprocessing import Process, Queue # must be a global function def my_function(q, x): q.put(x + 100) if __name__ == '__main__': queue = Queue() p = Process(target=my_function, args=(queue, 1)) p.start() p.join() # this blocks until the process terminates result = queue.get() print result
stackexchange-stackoverflow
{ "answer_score": 138, "question_score": 100, "tags": "python, function, subprocess, popen, python multiprocessing" }
Delete to end of line after a match, keep lines not matched I have a file of the following form: interesting text-MIB blah blah blah VERY INTERESTING TEXT interesting text-MIB blah blah blah In each line containing the "-MIB" string, I would like to delete the text following this string, until the end of the line. The following command seems to work as intended: sed -i -n -e 's/-MIB.*$/-MIB/p' ./myfile My problem is that it also deletes the lines where my pattern is not found. Here, the line "VERY INTERESTING TEXT" would be deleted. I am not really familiar with sed. What am i doing wrong? Is sed appropriate for this kind of treatment?
You need to leave out the `-n` option. Check out <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 16, "tags": "sed, line, string matching" }
Mysql query to find out which id is having both french and german !enter image description here what will be the query to find out which id is having both languages french and german?
You can use this statement: SELECT id FROM st where name in ('german','french') Group by id having Count(*)=2 You should rename the column `id` in `student_id`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -5, "tags": "mysql" }
NHibernate - Exclude subclass using Criteria with Joined Subclass I have a fluent nhibernate configuration in my app. Running latest of both. I am trying to create a criteria statement to pull back a specific class in a joined subclass hierarchy. This is an example of my inheritance structure: Admin is an Employee is a Person (Admin : Employee, Employee : Person) What I am trying to get is the Employees but not the Admins, but since admins are employees, they are coming back in the query. I do not have a discriminator column to use. Is there any way to accomplish this using the Criteria API? Thanks in advance. Schema as requested (just an example): Person table: Id, Name Employee table: PersonId, EmployeeNumber Admin: PersonId, AdminNumber NHibernate relates those properly. Everything else works except this specific type of query.
It appears that Criteria does not support that functionality. I was able to solve the issue by adding a SQL Restriction to the query to filter out the subclass results. criteria.Add( Expression.SQL("{alias}.MyPrimaryKey NOT IN (SELECT MyPrimaryKey FROM Admin)")); This essentially excludes and results from the Employee SQL query where that Employee exists in the Admin table, thus returning only Employees that are not Admins. I originally tried separately querying the Admin table via Criteria to get a list of Ids which I then fed into the Employee query using a NOT IN Criteria statement `Restrictions.Not(Restrictions.In())` but SQL Server restricts the number of parameters to 2100 and blows up if that collection of Ids that you are trying to exclude has more than 2100 items.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "asp.net, nhibernate, c# 4.0, .net 4.0, fluent nhibernate" }
Will small random dynamic snippets break caching I am busy writing a WordPress plugin. Now most users have cache plugins installed, they cache the pages. I know also some webservers as nginx have php caching and whatnot. There are also things like memcached. Now I have to admit I do not know exactly how they work, if anyone have some good links on how they work I would be glad. Some links where it's explained simple, not to technical. Now the question. My plugin **displays different statistics** on posts, they are always different, will this break the caching of the page. To take is a step further, sometimes the statistics of the post needs updating, and there is a **small javascript snippet** added to the page. Now will these two action result in the page not caching, or am I ok.
From what you have described I would be less worried about your plugin breaking caching and more worried about someones caching setup breaking your plugin, this isn't something you can control but it is something you can try and mitigate against by using the common best practices on plugin creation. If you are worried about a specific caching plugin my suggestion would be to test it, it is the only way to know for sure.
stackexchange-webmasters
{ "answer_score": 0, "question_score": 0, "tags": "cache" }
How to determine if date entered by the user is in future? How do I know in PHP that the date entered by the user in future than the current date. i.e if($current_date<$future_date) { //do all the success actions here } else { //show the user that they have selected a date in the past. }
Well you first need to convert the date string using strtotime() function and then check if future date value is greater than current date value. Here is the code snippet: $today_date=date('Y-m-d H:i:s'); $current_date=strtotime($today_date); $future_date=strtotime($future_date);//retrieved from user's input Now you can call your function: if($current_date<$future_date) { //do all the success actions here } else { //show the user that they have selected a date in the past. }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, date" }
Prevent next fragment (tab) from preload with ViewPager I am developing an app in Android using Fragments. I have this three tabs: !User app screenshot I know that is not possible to prevent the load of one fragment on each side (previous and next) as far as the minimum value of `setOffScreenPageLimit()` is 1 but does it mean that if I want to show a `ProgressDialog` on the `onPreExecute` method of an `AsyncTask` running within _Descargas_ Fragment this will cause that when I nav to the _Capturador_ that ProgressDialog will be necessarily loaded? If yes I have no idea of how to let the user know that I am downloading the packages (that's what Descargas does, to parse some XML). Thanks in advance ;)
Embed a ProgressBar on the Descargas fragment. Or overlay an indeterminate progressbar over the center of the fragment while it loads. Dialogs are really part of the activity, it wouldn't make sense that it's only applicable to one of the pages. At the end of the day though if you must insist on using dialogs, you can implement an onPageChangeListener viewPager.setOnPageChangeListener(OnPageChangeListener); And you can pull up the appropriate dialog when the designated fragment is selected and the opposite when you navigate away.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 7, "tags": "android, android fragments, android fragmentactivity" }
MATLAB : access uigetdir's internal java methods When using the standard dir dialog box from MATLAB uigetdir, double-clicking on a directory leads to the dialog box entering it and displaying its contents. To actually select it, you have to click on the "select directory" button. What I would like is a way to add specific rules on what to do when double-clicking on a directory : basically, I would like to change/override the internal 'method/callback' associated to this action. Problem is, said dialog box is NOT your usual Matlab figure - that I would know how to do easily (retrieve the handle, look at properties and edit/modify the corresponding callback). This looks like a raw Java object and I find no way to access this information from Matlab. Thanks for your help.
You could try this, instead of `uigetdir`: fc = javax.swing.JFileChooser('/initial/path') % then customise the dialog using Java methods, as you please! fc.setFileSelectionMode(javax.swing.JFileChooser.FILES_AND_DIRECTORIES) chosenfile = fc.showOpenDialog([]) You could even add listener callback to handle specific events if needed.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, matlab, matlab java" }
How to do slow motion effect in side view flash game with box2d As i am working on side view bike stunt game in which am trying to add slow motion effect when a bike performs stunts. Is there any solution for showing such kind of slow motion effect in Box2D. can anybody help me in this regard Thanks and regards, Chandrasekhar
As mentioned already, changing the length of the time step can give a slow motion effect. It also has the side-effect of altering the way gravity affects bodies, and can complicate other things like recording a replay or syncing state across multiplayer games for example. Another option is to use a fixed time step length for every time step, and keep track of the previous position and angle for all bodies. Then you can interpolate between the last frame and the current frame to draw them at an in-between frames position. This means that you are always drawing things a tiny bit behind their current position in the physics engine, but it should not be noticeable with typical frame-rates of 30-60fps.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "actionscript 3, flash, box2d" }
Use dynamic wallpaper as app background Is it possible to preset one of the dynamic wallpapers supplied to be used as background for my app? It doesn't have to be the one the user is using at the moment since I know there is no public API for that, but anyone selected by me whilst coding would do.
I'm not sure, but I think there are not public APIs to access programmatically dynamic wallpapers from an app. Your best try could be mimicking dynamic wallpaper by creating your own animation: NSArray *frames = [NSArray arrayWithObjects:[UIImage imageNamed:@"firstFrame.png"], [UIImage imageNamed:@"secondFrame.png"], // add other frames , nil]; UIImageView *dynamicWallpaper = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 480.0f)]; dynamicWallpaper.animationImages = frames; dynamicWallpaper.animationDuration = 60.0f; // seconds dynamicWallpaper.animationRepeatCount = 0; // 0 = loops forever [dynamicWallpaper startAnimating]; [self.view addSubview:dynamicWallpaper]; [dynamicWallpaper release]; Anyway, doing so you need a lot of images...
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "iphone, dynamic, background, ios7, wallpaper" }
.net-traceprocessing How Can WaitAnalysis Be Used? In the library .net-traceprocessing is a namespace Microsoft.Windows.EventTracing.WaitAnalysis which contains many types related to Wait Analysis. How can that be used? Based on the name it sounds useful. Has anyone experience with that one and has a sample at hand? I know that there is a WaitClassifcation Graph in WPA. Which events need to be recorded to make this one show up as graph and how useful is that one?
We'd like to make wait analysis available in our public version, but unfortunately we weren't able to do that for our first public release. As you noticed, we removed the top-level entry point but had not cleaned up other types exposed in that namespace. Apologies for the teaser; we'll remove the other remnants of wait analysis in public surface area. It would take a bit of work to get this feature made public, but we'll put it on our backlog, and let us know if there's more interest here, and that will help raise the priority.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": ".net traceprocessing" }
i am facing ,data manipulation error, it must be atomic number in r? When I run the code cols_name <- c(10:15) for(i in 1:ncol(df_churn[,cols_name])) { df_churn[,cols_name][,i] <- as.factor(mapvalues + (df_churn[,cols_name][,i], from =c("No internet service"),to=c("No"))) } I get the error Error in mapvalues(df_churn[, cols_name][, i], from = c("No internet service"), : `x` must be an atomic vector.
It seems as though you are attempting to replace all "No internet service" responses in columns 10:15 of your dataset with "No"? Without adjusting your syntax too much try this: cols_index <- 10:15 for(i in cols_index){ df_churn[,i] <- as.factor(mapvalues(df_churn[,i], from ="No internet service",to="No")) } Let me know how it goes!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "r" }
Android page control like book? I want to develop page control like **book** ,means when user drags over page(left or right) control will **move next page or previous page(with view also move)** , depending on which way the user dragged using their finger.
Take a look at GreenDroid's `PagedView` UI element, it does exactly what you want
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "android" }
How to get the minimum id from the table in MySql I have written a MySql query to get the columns related with minimum id . Looks something like this SELECT min(id) as ID,feed , idpropiedad FROM `registrofeed` WHERE feed=21 The table has 4 rows looks like this !enter image description here So according to the function that I have written function setLC() { $sql = " SELECT min(id) as ID , feed , idpropiedad FROM `registrofeed` WHERE feed=21 "; $result = $this->localDb->execute($sql); $row=mysql_fetch_array($result); echo $sql; echo $row['idpropiedad']; $this->lastCode = $row['idpropiedad']; } It returns empty string for idpropiedad Can any one help me out where I am going wrong Thanks in advance
I'd think the query you're actually looking for is this: SELECT id, feed, idpropiedad FROM registrofeed WHERE feed = 21 ORDER BY id ASC LIMIT 1 `MIN()` is giving you the generally lowest value in the column, it does not affect the rest of the columns. If you want the whole _row_ with the lowest `id` it doesn't help. To illustrate, if you really wanted to use `MIN` here, you'd have to do: SELECT id, feed, idpropiedad FROM registrofeed WHERE id = (SELECT MIN(id) FROM registrofeed WHERE feed = 21)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "php, mysql" }
Application to continuously recognize popular songs on Android I am looking for an application that **continuously** recognizes popular songs on Android, like Shazam on iPhone. The Android version does not provide this specific feature (we have to click manually each time we hear a new track). A description of the basic concept from Wikipedia: > Shazam uses a mobile phone's built-in microphone to gather a brief sample of music being played. An acoustic fingerprint is created based on the sample, and is compared against a central database for a match. If a match is found, information such as the artist, song title, and album are relayed back to the user. A solution is preferred that: * is gratis * has an option to send the playlist by email
The Auto Shazam feature was added to the Android app in June 8, 2016. ![Long press to Auto Shazam](
stackexchange-softwarerecs
{ "answer_score": 2, "question_score": 12, "tags": "android, music recognition" }
PHP: COM object not created in schedule task (instead hangs) I have a PHP script that runs a process to generate letters on a Windows server. The file is current set up as a Scheduled Task. In the script, the COM object is instantiated to work with the appropriate files. When it is run as a Scheduled Task, the line to instantiate the COM object does nothing and hangs the script (rather than returning any result). The script will never terminate. $this->word = new COM("word.application"); I believe that there is no issue with the script itself, as I can run the batch file directly (with no issue). This problem only seems to come up when we try to automate it. I think there is some permissions issue going on, but I'm not entirely sure. Thanks for any help! Edit: More information about the system: Windows 2008 Server Standard without HyperV Microsoft Office Word 2007 PHP 5.3.10 Attempting to Automate
I have found the solution. It was a profile issue. In: C:\Windows\SysWOW64\config\systemprofile check to see if the `Desktop` folder exists. If it doesn't, create it. It has this issue because it is expecting the folder, but hangs when it can't find it.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php, com" }
Simplifying a complex term How can I simplify this term $\frac{7+5i}{i-1}$? I've tried multiplying both numerator and denominator with $-1-i$, but in results in a division by zero.
$$\frac{7+5i}{i-1}=\frac{(7+5i)(i+1)}{(i-1)(i+1)}=\frac{(7+5i)(i+1)}{-2}=\frac{2+12i}{-2}=-1-6i$$
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "complex numbers" }
remove slashes jquery from json I send data via ajax so: $res = array(); foreach($series as $i){ //print_r($i); array_push($res, $i); } //print_r ($res); print (json_encode($res, JSON_UNESCAPED_SLASHES)); Get data: success: function(json){ alert(JSON.stringify(json)); json = json.replace("\\", " "); alert(JSON.stringify(json)); It is alerting same datas, why? How can I remove slashes from json? Thanks
Your PHP code returning JSON in to String not in Object Use `JSON.parse` instead of `JSON.stringify()` Replace success function like this: success: function(json){ alert(JSON.parse(json)); //json = json.replace("\\", " "); alert(json); console.log(json);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, jquery, json" }
How to get received whatsapp messages programmatically? What is the best way to get whatsapp messages in the moment messages are received. Is the easiest way to read the notifications of the phone or is there a better way? Root permissions are allowed.
I may have 2 solutions: 1. Check every x seconds for unread messages and save the id of this message. Next time check again for unread messages which have an id higher than the previous one. Then the app knows which message is new and can read all new ones. 2. Use AccessibilityService to get notificated when a new message from whatsapp was received and follow the same steps. Tell me if it helped or if it's a bad idea :D
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 5, "tags": "java, android, root, whatsapp" }
Difference Between Spotfire Web player client and Spotfire Web player server I want to configure the Tibco Spotfire and confused with 2 terms - 1) Spotfire Web player client 2) Spotfire Web player server Can anyone help to know the difference between Spotfire Web player client and Spotfire Web player server. As per my understanding, I can install Spotfire Server and Spotfire Web player on one machine. And Spotfire developer on various machines. Now I am confused with a new term as 'Spotfire Web player client'. How I can use this client for the Spotfire configuration?
The Spotfire Webplayer Server is the machine that will interact with the Spotfire Server, much like the Professional(Pro) client does. It should reside in the same data center as the Spotfire Server. The Spotfire Webplayer Client (consumer) is the interface from any machine to the Spotfire Webplayer. It is accessed via your local browser. Data communication happen between the Webplayer and Server. The client will just have mostly pictures and JavaScript, etc. While with the Business Author license you can now do some authoring from the Webplayer Client, most of the Authoring would normally be done with the Spotfire Professional Client. So in a sense you can think of the Spotfire Webplayer Server as a remote 'Professional client' with stripped down functionality that is accessed remotely via your browser (the Webplayer client).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "configuration, tibco, spotfire" }
Тригонометрические функции .net framework Есть статический класс _Math_. Есть в нем тригонометрические функции. Возьмем _Cos_ и _Acos_. Наверное, я забыл тригонометрию, потому что ожидаю что эта строка `Console.WriteLine(Math.Acos(Math.Cos(ang)));` выведет мне значение _ang_ , а она выводит непонятные вещи. Объясните почему?
Вероятно, вы забыли, что тригонометрические функции в C# принимают угол не в градусах, а в радианах. Сначала вам надо аргумент функции Cos сконвертировать в радианы: double rad = ang *(Math.PI / 180.0); а затем уже провести обратное преобразование в градусы для результата функции Acos: Console.WriteLine(Math.Acos(Math.Cos(rad))*(180.0 /Math.PI)); Пример
stackexchange-ru_stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "c#, visual basic" }
Mongo DB installation issue I installed mongo DB by using `docs of mongo DB`. But when I tried this command in ubuntu terminal, I got this error: `Command used:` sudo mongod Error: ********************************************************************* ERROR: dbpath (/data/db) does not exist. Create this directory or give existing directory in --dbpath. See ********************************************************************* How can I fix this error?
Run this command to create a directory - sudo mkdir /data/db and then run sudo mongod
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "mongodb, ubuntu 14.04" }
Symfony2: Twig detect noscript I want to render a table which holds all entity data. There should be a noscript version which additional renders two colomns with editing and deleting operations and a default javascript version where it gets solved dynamicaly over a sidebar. Is there a way to let this decision to twig? So that twig detects if javascript is supported and if not renders the additional fields? Regards
Twig-specific code? No HTML code? Yes You can make use of the `<noscript>...</noscript>` tag to display something to browsers without JavaScript support. Alternatively, you can display the two additional columns to everybody and use JavaScript to hide them. This way, people without JavaScript see them, people with JavaScript don't.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, symfony, twig, detect" }
Turn plot around in R Currently I am doing research to chatbot interfaces and make use of eyetracking to test my prototypes. My eyetracking device creates a csv file with a x and a y coordinate every 16 mili seconds. I want to plot this information with: * The X-axis on the top * The Y-axis on the right (starting with zero at the top) Currently I have the following code: dataleft = data[c(3,4)] dataleft_matrix = data.matrix(dataleft) plot(dataleft_matrix, main="Eyetracking Left Eye", xlab="X-as", ylab="Y-as")` However, this does not create the axes as I want them to be. Can someone help me, please?
I'd recommend using ggplot for this, rather than base R. Of course, you may have good reason to prefer plotting using base R, but I find ggplot easier (and faster) to use. library(ggplot2) xleft <- c(2,3,4,2,1,2,3,4,5) yleft <- c(2,3,4,3,2,1,6,5,3) leftdata <- data.frame(xleft, yleft) ggplot(data = leftdata) + geom_point(aes(x = xleft, y = yleft)) + scale_y_reverse(position = "right") + scale_x_continuous(position = "top") + ggtitle("Eyetracking Left Eye") + xlab("X-as") + ylab("Y-as") I think this is what you want it to look like, right?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "r, plot, scatter plot, axes" }
html helper included in elements in cakephp not working with wamp I am working with cakephp.i have designed a homepage for a website.here i have inluded elements viz header.ctp, main.ctp and footer.ctp.And i call them in default.ctp using $this->element. in each element i have used html helper likeHtml->image('Logo.png');?> now when i deploy it on xxamp its working as expected but when i migrated the same onto wamp its not giving the output instead of showing image for <? echo $this->Html->image('Logo.png');?> it is showing text Html->image('Logo.png');?> i am using cakephp 2.4.2. xamp php 5.3.5 wamp: php 5.3.0
i got it working... I just replaced <? ........ ?> with <?php ...... ?> while declaring the php code. :)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, html, cakephp, xampp, wamp" }
Finding strings which contain a given substring Using the following commands (which may be inefficient) I can generate all words of length $j$ on the alphabet $\\{0,1\\}$: `sd[st_]:=StringDelete[st, " "]` `name[j_]:=Map[sd,Map[StringRiffle,Tuples[{0, 1}, j] ]]` Suppose I want to find all words on length 6 which contain as a substring `101`, how do I do this? I have tried using `StringCases` but this seems to only give me strings that start or end with `101`. Is there a way to do this?
Two additional methods (both faster than `Select[strings, StringContainsQ["101"]]`): strings = Map[StringJoin, Tuples[{"0", "1"}, 6]]; Pick[strings, StringContainsQ["101"] @ strings] > > {"000101", "001010", "001011", "001101", "010100", "010101", > "010110", "010111", "011010", "011011", "011101", "100101", "101000", > "101001", "101010", "101011", "101100", "101101", "101110", "101111", > "110100", "110101", "110110", "110111", "111010", "111011", "111101"} > A slower alternative: Pick[strings, StringMatchQ["*101*"]@strings] > same result
stackexchange-mathematica
{ "answer_score": 4, "question_score": 4, "tags": "list manipulation" }
MVC why is UpdateModel sometimes used in Edit and sometimes not I'm new to MVC and I've been looking through a bunch of examples. For the `HttpPost` on some edits they call `UpdateModel(entity)`. In other examples such as: < `UpdateModel(entity)` isn't called at all. What's the point of calling this function when it appear unneccessary in MVCMusicStore? Apparently it " Updates the specified model instance using values from the controller's current value provider." However I've found from the MVCMusicStore example the updated values are already posted through? Could someone please explain this to me?
i don't think ModelBinding is only introduced in newest version of asp.net mvc (newest version is 3). it was present at least in v-2 so far as i can tell. when you call the updatemodel you call Modelbinding explicitly. when you receive at as action method parameter Modelbinder is called implicitly. In Edit scenario updateModel is used when we fetch original entity from db and tell controller to update it using UpdateModel like public ActionResult Edit(int id) { var entity = db.GetEntity(id); UpdateModel(entity); db.SaveChanges(); } Other scenario is when you are not fetching db entity but ModelBinder gives you an entity created from form fields etc. and you tell you db that object is already there and it has been modified outside the db and you better sync with it like in MusicStore tutorial.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "asp.net mvc" }
Python assign sign of number to variable I have a variable of type int, it's Python, so it can be positive and negative. Now, I want to make another variable have the same sign as the first variable1. It's easy to do this by using an if statement and then assign -1 or +1 to a variable and multiply every variable I want to have this sign by the -1 or +1. But then I thought maybe there is another way to do this (e.g. a built-in function). Is there something like "sign = getsignbit(value)"? edit: Solved! math.copysign did the thing, cmp(x,0) works too, but I don't only want -1, 0 or 1, but also turn a 5 into -5.
There's no built in `sign` function (see this answer for some explanation: Why doesn't Python have a sign function? ), but `math.copysign` might be useful to you. <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, function, if statement, sign, built in" }
n-th: как написать/произнести? If I want to write the word "n-th" (as in n-th solution, n-th derivative,...), is it more conventional to write `n-ый/n-ая/n-ое` or `n-й/n-я/n-е`, or are both styles equally common? In terms of _pronunciation_ , is it always `э́ный/э́ная/э́ное` (e.g., someone who writes n-я wouldn't actually say that as `э́ня`)? EDIT: I found out later that for every variable `x` it's acceptable to express " _x-th_ " as " _xтый_ " (e.g., `m-ый = эмтый, n-ый = энтый, j-ый = житый, q-ый = кутый`), and since this works in all cases while the ending _-ный_ for _n-ый_ doesn't apply to variables ending with a vowel sound, I'll use the _-тый_ version.
While both written styles are grammatically correct, the more common one is > n-ый, -ая, -ое, -ые In addition, you could see sometimes the `n-` part spelled out in Russian as: > энный, энная, энное, энные The pronunciation in all cases would be > э́нный / э́нная / э́нное / э́нные (Note the double `н`) pronunciation _э́ня_ is wrong and it's more than likely that people will not understand what you're referring to.
stackexchange-russian
{ "answer_score": 10, "question_score": 9, "tags": "прилагательные, математика" }
How to export JAVA_HOME in Lambda Linux Docker image? I'm using the Lambda Linux AWS image. I'm trying to install Atlassian Bamboo that requires JAVA_HOME to be exported. I've been able to install java and verify it is installed properly. I can't get the JAVA_HOME to export though. I created a file named jdk_home.sh in /etc/profile.d #!/bin/sh export JAVA_HOME=/usr/lib/jvm/java/bin I have done this successfully on another AWS instance, but not in a Docker container. I've also executed the script directly and it still doesn't export. What else can I do to troubleshoot this?
In your Dockerfile for the container, you can specify various environment variables to be persisted through containers. For example, in this case, you would add this snippet before the `CMD` entrypoint: [...] ENV JAVA_HOME /usr/lib/jvm/java/bin [...] See this link for more details: <
stackexchange-unix
{ "answer_score": 2, "question_score": 1, "tags": "bash, docker, amazon ec2, container" }
Others => '1' statement in Verilog I have used VHDL all my life and only been using Verilog for a short time, I have to create a logic in Verilog for a very large array and assign it to 1 or 0 depending on the condition of an input. Here is my VHDL code if (data_track == '1' ) then my_array(MAX-1:MIN) <= (others=> '1'); else my_array(MAX-1:MIN) <= (others=> '0'); end if; MAX and MIN are parameters for the block, set during the synthesis depending on the type of system we are accessing. Is there a way to do this in Verilog easily?
A mix of parameter with curly braces will help in resolving (the inner curly brace will act as replication operator) Code eg: parameter MAX = 16; assign high_val = 1'b1; assign low_val = 1'b0; if ( data_track ==1'b1) my_array[MAX-1:MIN] <= {MAX{high_val}}; else my_array[MAX-1:MIN] <= {MAX{low_val}}; Here in the above code the if statement with curly brace will propogate MSB to LSB with 1 values resulting in all 1's in our case 16 then result will be a 16'b1111111111111111 and it is the vice versa for else condition
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "vhdl, verilog" }
Surface reference faster than Surface object I recently changed the surface reference of my algorithm for a surface object. Then, I noticed that the program runs slower. Here is a comparison for simple example where I fill a 3D floating array [400*400*400] with a constant value. ### Surface reference API Time: 9.068928 ms surface<void, cudaSurfaceType3D> s_volumeSurf; ... surf3Dwrite(value, s_volumeSurf, px*sizeof(float), py, pz, cudaBoundaryModeTrap); ### Surface object API Time: 14.960256 ms cudaSurfaceObject_t l_volSurfObj; ... surf3Dwrite(value, l_volSurfObj, px*sizeof(float), py, pz, cudaBoundaryModeTrap); This was tested on a GTX 680 with Compute Capability 3.0 and CUDA 5.0. Does anyone have an explanation for this difference?
In the surface object case, surface descriptors are fetched from global memory. In the surface reference case, these descriptors are compiled into constant memory. Fetching these descriptors may be much faster than global memory access. If your kernel is small enough or L1 cache is disabled, you could observe significant performance loss. You can diff the SASS code to see the difference.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 5, "tags": "cuda" }
A " triple-sum-free " sequence? Consider the strictly increasing integer sequence $f(n)$ defined as : $$f(1) = 1$$ $ M $ is in the list If and only if $M$ is not of the form $ f(a) + f(b) + f(c) $ for Some integers $a,b,c > 0$. So the sequence starts as $$1,2,7,8,...$$ This resembles the A-sequence. < What is known about $f(n) $ ? In particular : How fast does $f(n)$ grow ?
The sequence continues $$1,2,7,8,13,14,19,20,...,6n+1,6n+2,...$$ The integers in the sequence are all of the form either $6n+1$ or $6n+2$. When these are added together in threes the sums that can be made are restricted to the forms $6n+3,6n+4,6n+5$ and $6n$. Since all such positive integers can be made, none of these appear in the sequence. Conversely, integers of the form $6n+1$ and $6n+2$ can never be the result of a sum. Hence the sequence contains all positive integers of the form $6n+1$ and $6n+2$ and no others. Therefore, the function grows linearly.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "sequences and series, number theory, asymptotics, sieve theory" }
Why list ++ requires to scan all elements of list on its left? The Haskell tutorial says, be cautious that when we use "Hello"++" World", the new list construction has to visit all single elements(here, every character of "Hello"), so if the list on the left of "++" is long, then using "++" will bring down performance. I think I was not understanding correctly, does Haskell's developers never tune the performance of list operations? Why this operation remains slow, to have some kind of syntax consistencies in any lambda function or currying? Any hints? Thanks.
In some languages, a "list" is a general-purpose sequence type intended to offer good performance for concatenation, splitting, etc. In Haskell, and most traditional functional languages, a list is a very specific data structure, namely a singly-linked list. If you want a general-purpose sequence type, you should use `Data.Sequence` from the `containers` package (which is already installed on your system and offers very good big-O asymptotics for a wide variety of operations), or perhaps some other one more heavily optimized for common usage patterns.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "performance, list, haskell, concatenation" }
7zip command line archive folder in subfolder without the first subfolder inside the archive having a folder structure like this: archive.cmd sub1.zip // create sub2.zip // create foos sub1 sub2 I want to generate `sub1.zip` and `sub2.zip` inside the main folder. the problem is that `sub1.zip` inside will contain `\foos\sub1\files` but I need `sub1\files`
solved it by adding `.` before the path 7z a sub1.zip .\foos\sub1 7z a sub2.zip .\foos\sub2 this creates `sub1.zip` that contains only `sub1` folder with its contents
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "command line, 7 zip, archiving" }
Issue with jquery toggle I am using jquery toggle to show a div with content. Not sure how to explain the issue I am having, but if you go to my test page and click on the first link for Similar Movies (it coincides with the movie 500 Days of Summer) you'll see a panel open with the similar movies. If you go to the next Similar Movies link (coinciding with 10 Things I Hate About You) you'll see that it still controls the first set of movies, meaning it toggles the panel up and down. In fact, all of the Similar Movies links control the first panel. Not sure how to fix this. ***REMOVED LINK- NO LONGER NECESSARY- THANKS!** <script type="text/javascript"> $(document).ready(function(){ $(".flip").click(function(){ $("#panel").slideToggle("slow"); }); }); </script> <div class="flip">Similar Movies </div><!-- end of flip--> <div id="panel"> similar movies are echoed here from a database using php... </div>
Instead of using an ID for your panels, use a class, like this: <div class="panel"> similar movies are echoed here from a database using php... </div> Then in your jQuery: $(document).ready(function() { $(".flip").click(function() { $(this).siblings(".panel").slideToggle("slow"); }); }); Using the same ID on more than one element is not recommended, and will especially present problems when using jQuery.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, javascript, jquery, toggle" }
Cannot push Git to remote repository with http/https I have a Git repository in a directory served by apache on a server. I have configured WebDAV and it seems to be running correctly. Litmus returns 100% success. I can clone my repository from a remote host, but when trying to push over http or https, I get the following error: _error: Cannot access URL< return code 22 fatal: git-http-push failed_ Any idea?
It is highly suggested NOT to use WebDAV if possible. If you must use HTTP/HTTPS then usage of the git-http-backend CGI script is recommended over WebDAV.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 25, "tags": "git, http, https, push" }
Printing a board in Commodore Basic 4.0? I'm having trouble with printing a board of dots in Commodore Basic 6502. This is what I have to far: (it's a subroutine) 10 INPUT "Please enter a number:", X 20 DIM A$(X, X) 30 FOR I = 0 TO X 40 FOR J = 0 TO X 50 A$(I, J) = "." 60 NEXT 70 NEXT 80 PRINT A$ END Can anyone help me out with it because when I paste it into the emulator, type END, and press enter literally nothing happens? Any help is much appreciated. I'm trying to build a word search game.
Just for laughs, here is some code that does what I think you want to do: !C64 screen shot Just type `RUN` and hit enter!
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 12, "tags": "basic, commodore" }
Weird heights and widths on input box in html css I'm trying to format an input box but im running into problems where the height of the input ends up being weird. When I look in the developer tools at the height the input isn't made up of clean numbers, instead it is made up of odd decimal figures, for example the border isn't 1px it's 0.909. What is causing this, and how can I get back to clear, whole numbers. input { padding: 8px 15px; border: 1px solid rgb(204, 204, 204); border-radius: 3px;} <form class="search left"> <input class="input" placeholder="K"> <input class="input" placeholder="L"> <input type="submit" class="button"> </form>
You're zoomed in on your browser. Hit `Ctrl` \+ `0` or `Ctrl` \+ `-` to reset the zoom level to 100%. At 110% zoom level you will see something like this: !Zoomed In Whereas at 100% you'll see what you're expecting: !Normal Zoom Level
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "html, css" }
DirectSoundCreate how to release the handle? when i call the function of "DirectSoundCreate" to get "IDirectSound" pointer, but i couldn't release it when exit the process at the destructor. Like this: IDirectSound* m_pDirectSound; IDirectSoundBuffer* m_pDsSoundBuffer; HRESULT hResult = DirectSoundCreate(NULL, &m_pDirectSound,NULL ); hResult = m_pDirectSound->SetCooperativeLevel (hWnd,DSSCL_NORMAL|DSSCL_EXCLUSIVE|DSSCL_PRIORITY); here release: if(m_pDirectSound) { m_pDirectSound->Release(); } the program will block at here forever! so anyone can help me? shall i release the pointer `m_pDirectSound`? thanks a lot!
Make sure you are not calling `CoUninitialize()` too soon. If there are still COM objects active when COM is unloaded, calling `Release()` afterwards can exhibit all kinds of undefined behavior, including crashes and deadlocks.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, windows" }
Meaning of てはならない I understand that `` means 'must not/should not'. However,I cannot make any sense out of the above sentence that I read in a book. Would appreciate if someone could assist with the meaning.
Quite simply, > = "You must not ~~." > > = "You must ~~." means: "One must make a/the presentation based on correct information."
stackexchange-japanese
{ "answer_score": 2, "question_score": 1, "tags": "grammar" }
How to access Aache SOLR custom request handler /suggest from solrj or spring data for solr? I'm new to Solr. I'm implementing auto complete functionality for my application. I have configured the required fields in solr and created a custom request handler /suggest. I'm finding it tricky to access it via solr java client solrj. I'm even fine with the spring data for solr. Please somebody help to access my custom request handler from solr java client.
With spring-data-solr you might add `@Query(requestHandler = "/suggest")` or use `query.setRequestHandler("/suggest")`. In case you're doing autocomplete you might also give `/terms` and the `SimpleTermsQuery` a try.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "solr, lucene, spring data" }
MATLAB return image frames from video I have a function that processes a video and return a couple of images from it. I am doing so by creating a new video inside the function containing the frames I want and returning the video and is the next function I read the video again to process it. Is there any faster way to do it? For e.g. returning an array with the images and reading them?
You can pass the decoded frames as a 3-D array. For instance, if you have two 2-D frames `frame1` and `frame2`, you can concatenate them along the third dimension like so: M = cat(3, frame1, frame2); To extract the frames from the 3-D array, just specify the third coordinate. For example, to get `frame1`, you write: frame1 = M(:, :, 1); This allows you circumvent the issue of encoding and decoding the frames between function calls, as well as prevent any loss in video quality due to successive encoding.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "matlab, video processing" }
Django rest framework returning base64 image URL encoded I have my viewset that returns a basse64 encoded image in the `image` variable: with open(f"image_file.jpg" , "rb") as image_file: order.image = base64.encodebytes(image_file.read()).decode('utf-8') The thing is, if this code is executed locally like `python script.py` it returns the right base64 and I can display it, but this viewset is returning a base64 that's URL encoded. Instead of returning something like `NMR//9k=`, it's returning `NMR/9k%3D%0A`. How can I change this? I need the proper base64 encoding to display the image on the front.
I managed to solve this issue by creating a dict for the base64 images outside the serializer of the model, which was the one doing that URL encoding. I also had to remove new line characters as the response was drawing them as characters. with open(f"image_file.jpg" , "rb") as image_file: images_dict["image_1"] = base64.encodebytes(image_file.read()).decode('utf-8').replace("\n", "")
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, django, django rest framework, base64" }
Need old version of readline for activator? I am on a Mac and have run `brew install typesafe-activator`. Then I tried it out by running `activator` and got the following message: `dyld: Library not loaded: /usr/local/opt/readline/lib/libreadline.6.dylib Referenced from: /usr/local/bin/bash Reason: image not found Trace/BPT trap: 5` Sure enough, there is no `libreadline.6.dylib` at that location. I have version 7 instead. I have tried to find a way to install the old version, but no luck so far. In particular, `brew` doesn't seem to have old versions available. Is there a way around this? Either a way to install the old version of `readline` or a version of `activator` that supports the new `readline`?
I ended up making and installing `readline 6.3` from source. Here's the link. Just download `readline-6.3.tar.gz`, unzip it, navigate to the unzipped folder, and run ./configure make make install
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "macos, readline, typesafe activator" }
getting downvoted for no reason in several minutes > **Possible Duplicate:** > Serial downvotes in quick succession on all my posts That is just my opinion but I think somebody keeps downvoting me for no reason.Questions, answer everything.I do not know why.Here is an image of my reputation tab !in approximately 1 or 2 minutes I guess I have several upvotes with those answers and questions, and some of them are my solutions to my questions. I don't really care about the reputation so much, but I really want to know my fault so I can correct it. Any ideas about anything wrong with those questions and answer will be appreciated and I will immediately edit them. My reputation tab
It happens all the time. There must be a hate voter out there. Not to worry. There's a nightly script that will recalc your rep. back again. If you still have the problem tomorrow, post here and a moderator will take care of it. Cheers.
stackexchange-meta
{ "answer_score": 5, "question_score": 0, "tags": "discussion, support" }
Resource loading into ArrayList for tile-based game. (Java) So i'm attempting to develop a tile-based game using eclipse, and i have run into a problem on how to load the resources from the resource folder into an ArrayList. I have a file reader that can load all of the needed files into a list, but i can't use class folders for each tile type (grass, stone, etc) because an ArrayList can only store one class type. Is there a way to load all sub-classes of the tile super-class into a single ArrayList.
If you have a parent class (or interface) that all of the other classes extend from, then you can simply use an ArrayList of that parent class. Just create an ArrayList of Tiles. List<Tile> tiles = new ArrayList<Tile>(); Tile a = new GrassTile(); //GrassTile extends Tile Tile b = new StoneTile(); //StoneTile extends Tile tiles.add(a); tiles.add(b); for(Tile t : tiles){ t.doTileStuff(); } Edit: You could also reconsider your design and try to favor composition over inheritance. Instead of having a bunch of classes that extend Tile, have a single Tile class that contains attributes that determine how it behaves and looks.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, arraylist, resources, tile" }
How to adjust menu color in Sublime Text After downloading a Sublime update months ago, the menu text all turned white, along with the backgrounds, making them virtually unreadable. What I've looked up on fixing this, seems to do everything but change the background color of the menus, so regardless of what the editor field looks like, the menus are still unreadable. I'm curious if anyone knows how to adjust this feature. ![enter image description here](
Unfortunately, this is the result of custom themes on Windows, so sadly there is no "fix" with Sublime. Go to your Windows Settings > Theme and choose the one that just says "Windows", which should be a default blue color. Click on that and give it a minute to change everything. Then go back and double check Sublime. It's a bummer there isn't another way, but this should resolve it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "settings, sublimetext4" }
TCPWrapperで、Host名を使ってwrappingする OSRedhat7.1 hosts.allow A(IP 100.200.30.40 (DDNS ieserver)aserver.com)BBhosts.allow sshd : aserver.com ... Bhosts.deny ALL : ALL A hosts.deny B localhost sshd[11010]: refused connect from xx-xx-xxx-xxx.yyy.yyyy.yyy.jp (xx.xx.xxx.xxx) (A, B) ssh [email protected] AB TCPWrapping
TCP IPhosts.allowaserver.com IPIP > AB > DDNS IP SSH
stackexchange-ja_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "linux, tcp, dns" }
How to access state scoped to current behaviour from postStop I have an online game, with an actor that represents a user's state. State updates via recursive `become` calls: private PartialFunction<Object, BoxedUnit> updatedUser(final User user) { return ReceiveBuilder. ... matchEquals("update", s -> { context().become(updatedUser(new User(...))); }).build(); } Now when the user leaves the game (actor stops), I need to save its state to a database. I think the ideal place for this would be sending a message from `postStop`. But user's state is out of scope. public void postStop() throws Exception { //user state out of scope Database.tell(user, self()); } I don't want to have state as an actor field. What would be the best way to solve this problem?
There's no way to access the `user` value outside of the `updatedUser` function. Just make your user state an instance variable of the actor.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "functional programming, akka, actor" }
iMessage stuck in Notification Center I have this weird situation where I was using the reply-from-Notification-Center Messages feature and it got stuck in the write-the-message state, as in the screenshot below. !enter image description here The message was sent, but ever since it got stuck and it’s unusable. How can I reset it without restarting the computer or logging out? (I’m on Mavericks.)
I was able to fix this by killing Notification Center with the following command: killall NotificationCenter You could also force-quit it from Activity Monitor. Source.
stackexchange-apple
{ "answer_score": 1, "question_score": 0, "tags": "macos, messages, ui" }
How can I get email notifications for exceptions? How do I setup email notifications for exceptions that are either logged or thrown on the site? UPDATE: A few people have commented on the fact that you may expect to get way too many emails if you have every exception emailed to you. I tend to like to keep my exception log pretty light. Anything that goes in there I view as, well, an exception. If it's expected functionality and not a problem, then I like to catch the exception, possibly log it to another file (maybe system.log) if needed, but not log it to exception.log. But if you have a lot of noise in your exception.log that you don't want to clean, you're likely not going to want to do this.
You can use the Magento Hackthon Logger for this job: < It is not the question, but there are extensions for the extension: < What I want to say: It is easy to implement your own "Writer" :-)
stackexchange-magento
{ "answer_score": 4, "question_score": 14, "tags": "email, exception" }
Random access and update of an stl::set I'm using a stl::set to keep elements sorted as they are inserted. My question is about the random access. If I have a complex class(difficult to init, for example), I found that is easy to insert, because I define the less operator into class. But if the key is the class itself, how do I need to access to the class? With a find()? I need to init a complex class only to find my class? So my question is: how to random access to a set elements when elements are complex classes difficult to initialize? Thanks
I don't think it is possible : as you already noticed, the `std::set<>::find` member function expects a `const key_type &` (which, in a `std::set` is identical to `value_type`). If you object is expensive to construct, chances are that you should better use a `std::map` (which also is a sorted container), possibly with values being (smart) pointers on your type.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++, stl, set" }
ASP.NET MVC4 - Session_End - How can I get the currently logged on user's name in Session_End of Global.asax? My issue is that once Session_End executes in my Global.asax, the `HttpContext.Current` object no longer exists- probably as expected, I would imagine. So, what I'm trying to do is once the session ends, update my Logins table for the user currently logged in and set their LoggedIn status to False. Here's my Session_End: protected void Session_End(object sender, EventArgs e) { Helpers.OperationContext.UpdateIndividualLogin(); } As you can probably guess, I can try to pass in: System.Web.HttpContext.Current.User.Identity.Name But this object no longer exists because I can only imagine that it's already been disposed of. So, is there any way I can grab the currently (or previously current) user's name?
You can do this by storing the information you want (in this case the user name) in Session. You can store it when the user is authenticated.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "c#, asp.net mvc, session state, global asax, httpcontext" }
JavaScript Array of Key/Value Pairs Uses Literal Variable Name for Key I'm trying to create an array of key/value pairs by using the `push` method, but getting unexpected results. `console.log` prints this: > books: [{"bookTitle":"Mark Twain"}] Whereas I would expect this: > books: [{"Tom Sawyer" : "Mark Twain"}] Here's the code: var books = []; var bookTitle = "Tom Sawyer"; var author = "Mark Twain"; books.push({bookTitle : author}) console.log("books: %s", JSON.stringify(books)) I've tried `books.bookTitle = author` and `books[bookTitle] = author`, but the result is the same. Any help is appreciated.
Bracket notation is the correct way to use a dynamic key name: books[bookTitle] = author However, you need to use an intermediate object: var books = []; var bookTitle = "Tom Sawyer"; var author = "Mark Twain"; var foo = {}; foo[bookTitle] = author; books.push(foo); console.log("books: %s", JSON.stringify(books))
stackexchange-stackoverflow
{ "answer_score": 35, "question_score": 20, "tags": "javascript" }
fade on background image change i have a botton which is for changing the background image with jquery, as the following code shows $("#button").click(function() { $('#div1').css("background-image", "url(images/newBG.jpg)"); }); it works very fine! but i want to fade in the newbg-image... is it possible to add a jquery fade method to it. Any help would be very appreciated. Thanks Ted
Try this: $("#button").click(function() { $('#div1').hide().css("background-image", "url(images/newBG.jpg)").fadeIn(500); });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, html" }
Date format conversion in python Would someone know how to convert this matlab code into python ? for i=1:100 RefTime = datenum('01-Jan-1900 00:00:00'); MyTime=97847+i; t0=addtodate(RefTime,double(MyTime), 'hour'); date(i)=datestr(t0,'yyyymmddHH'); end I am trying here to convert an hourly numerical date format (MyTime) which reference point (e.g. origin) is 01-Jan-1900 at 00:00 to a YYYYMMDDHH format.
Something like this: import datetime RefTime = datetime.datetime(1900,1,1,0,0,0) OneHour = datetime.timedelta(0,3600) date = [] for i in range(100): #python loop starts at 0, so add 1 to your magic number below MyTime = 97847 + 1 + i t0 = RefTime + OneHour * MyTime date.append(t0.strftime("%Y%m%d%H")) #now 'date' is a list with 100 strings like "1911030200", etc.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, matlab, date" }
List index out of range and I can't figure out why? I've been trying to solve problems on code wars and for this problem my code returns an > "IndexError: list index out of range" in Line 13. Can someone explain why? > You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions. [7, 1] => [1, 7], [5, 8, 6, 3, 4] => [3, 8, 6, 5, 4] , [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] => [1, 8, 3, 6, 5, 4, 7, 2, 9, 0] def sort_array(source_array): dup_arr = [] for i in range(len(source_array)-1): if source_array[i]%2 != 0: dup_arr.append(source_array[i]) dup_arr = sorted(dup_arr) j = 0 l = 0 for j in range(len(source_array)): if source_array[j] %2 != 0: source_array[j] = dup_arr[l] l += 1 return source_array
If you have debug your program and `print(">>", dup_arr)` you'll see that you were missing the last odd numbers, because of your wrong range, it should be `range(len(source_array))` for i in range(len(source_array)): if source_array[i] % 2 != 0: dup_arr.append(source_array[i]) Know that you can iterate on values directly, that makes syntax nicer when indice isn't needed for val in source_array: if val % 2 != 0: dup_arr.append(val)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python, arrays, python 3.x, list" }
Why aren't javabean features built into the root JAVA object? I'm having a hard time understanding why javabeans are necessary and why they didn't just place the javabean features directly into the object class(root class) in java? My understanding is you turn an object(instance) into a java bean and that way you get all the benefits like serializable and so on for all the objects in the bean. But if that is the case, why even have a separate bean class for this, why not just have built into the root object class? Or am I not understand this?
You are not understanding it correctly. There is no actual Java class or interface that is a bean. It is merely a pattern, a convention. The bean convention is basically that a class will publicly expose some or all of its properties via public getXxx and setXxx methods, where XXX is the name of the property. Beans generally should be serializable, but any class can be serializable, and does not need to follow the bean convention.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, spring, class, object, javabeans" }
Is it possible to reduce maturity time of plants with biotechnology? I've heard of speed breeding which makes use of optimal circumstances in glasshouses and growth chambers. Is it also possible to shorten a plant's maturity time (i.e. the time it needs from being planted until the time its yield can be harvested) using genetic modifications?
Perhaps investigate the families of YUC genes that synthesize the growth hormone auxin (ncbi.nlm.nih.gov/pmc/articles/PMC6941117) and ARF genes (ncbi.nlm.nih.gov/pmc/articles/PMC4737911) that respond to auxin. Auxin overproduction or changes to ARFs might speed growth. But some herbicides are synthetic auxins (e.g. 2,4-D) and work by exhausting and killing weeds (en.wikipedia.org/wiki/2,4-Dichlorophenoxyacetic_acid), so modifying these pathways may have unwanted side effects, depending on the crop.
stackexchange-biology
{ "answer_score": 3, "question_score": 4, "tags": "botany, biotechnology, gene editing" }
Why does umount /dev/sdc1 for example not remove/eject an external harddrive? I just plugged in an external harddrive to a device running Ubuntu 12.04 LTS and when I attempt to umount the drive e.g. `umount /dev/sdc1` or `umount /media/harddrive` the drive is still accessible via the menu that appears on the left. The only time it disappears from the menu or is no longer accessible when I right-click on the harddrive and select the option `Safely remove`. Why does not umount not work? Does `safely remove` umount and then poweroff? How do I use the same command (safely remove) in the terminal?
`umount` only removes the mount; the device is still being seen by the system and is available for remounting. You can remove it safely. `eject` will actually eject your device, removing it from the list of devices.
stackexchange-superuser
{ "answer_score": 4, "question_score": 2, "tags": "ubuntu" }
Sed command and regular expressions I need to change 'bind a.b.c.d:80' to 'bind x.b.f.d:80'. I wrote below command for this purpose but it is not working, i don't know why? sed -i 's,bind *:35357,bind x.y.z.a:35357,' haproxy-sample.cfg Any help would be appreciated. Thanks in advance.
Executed from bash $ echo bind 12.54.36.165:35357 | sed "s/bind [^:]\+:35357/bind a.y.z.a:35357/" bind a.y.z.a:35357
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "regex, sed, ubuntu 14.04" }
Struggling with has_many :through Suppose I have 3 Models like this (not sure if this is correct): class User < ActiveRecord::Base has_many :lessons has_many :points, through: :progress end class Progress < ActiveRecord::Base belongs_to :user has_many :lessons end class Lesson < ActiveRecord::Base belongs_to :progress end (The Progress table has `user_id` and `lesson_id` fields.) How would I make it so calling `@user.points` would return the amount of entries into the `Progress` table. Also, how would I build a relationship?
class User < ActiveRecord::Base has_many :progresses has_many :lessons, through: :progresses end class Progress < ActiveRecord::Base belongs_to :user belongs_to :lesson end class Lesson < ActiveRecord::Base has_many :progresses end
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails, foreign keys, associations" }
Sending array value as parameter retrofit android I need to send a parameter as array in retrofit. This is the required key-value: "country":["Canada","India"] Now, when i pass it, It changes the whole array into string. This is how i am passing the value: "country":"["Canada", "India"]" The code i am using is here: ArrayList<String> countriedAplied = new ArrayList<>(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("country", countriedAplied); }
ArrayList<String> countriedAplied = new ArrayList<>(); JSONArray jsonArray = new JSONArray(); JSONObject jsonObject=new JSONObject(); jsonArray.put(countriedAplied); try { jsonObject.put("Country",jsonArray); } catch (JSONException e) { e.printStackTrace(); } JsonParser jsonParser = new JsonParser(); JsonObject gsonObject = new JsonObject(); gsonObject = (JsonObject) jsonParser.parse(jsonObject.toString()); sendtoDB(gsonObject);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, arrays, json, retrofit" }
What does "Uncaught Error: NOT_ALLOWED_ERR: DOM OperationNotAllowed Exception 1" mean? I encountered this error in Google Chrome: Uncaught Error: NOT_ALLOWED_ERR: DOM OperationNotAllowed Exception 1 I didn't find any results with Google. Anyone know what it means?
Check this site: < Dom Exception 1 refers to `INDEX_SIZE_ERR`. For ex: If an index is negative, or larger than the allowed value; for example using splitText with an offset argument larger than the length of the string.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, google chrome" }
Euclidean domain in which the quotient and remainder are always unique Let $R$ be a Euclidean domain in which the quotient and remainder are always unique. Does it follow that the ring $R$ is either a field or a polynomial ring $F[X]$ for some field $F$?
Yes, that characterization is correct, see M. A. Jodeit, Jr., Uniqueness in the division algorithm, Amer. Math. Monthly 74 (1967), 835–836.
stackexchange-math
{ "answer_score": 5, "question_score": 5, "tags": "abstract algebra, ring theory" }
mysql select column from view problem i create a view table like : CREATE VIEW ViewManager AS SELECT us.UserId AS 'Account Manager', ......... after that, when i run a query to select data from this view like : SELECT 'Account Manager' , .. from ViewManager then the data i get in this column is the text **'Account Manager'** and not the value of the this columns. Is there a way to solve this ? Of course I can change the field name , but i want to know if there is another solution, thanks.
You need to use backticks to escape column and table names. SELECT `Account Manager` , .. from `ViewManager`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, view" }
TCP_NODELAY for an SSL tunnel? I'm tunneling an HTTP connection over stunnel. The client side does not natively support HTTPS, so stunnel in client mode is used. Would setting TCP_NODELAY=1 help responsiveness in typical web browsing? The way I understand it, Nagle's algorithm bunches up packets and sends data in whole multiples of the packet size. My own benchmarking seems to have shown zero difference, though probably because my internet link to the server is too good.
Nagle's algorithm only really impacts applications which send many small packets and are latency sensitive (such as SSH or telnet). Since web browsing involves relatively large packets with both sides sending multiple packets without waiting for a response there won't be a significant change when setting `TCP_NODELAY`.
stackexchange-serverfault
{ "answer_score": 4, "question_score": 1, "tags": "ssl, tcp, tls" }
Optimal way to win at Damath !empty board !board with chips As you can see, this is an example of a DaMath board with Integers. See this Wikipedia article about DaMath with its rules. Is there any optimal way to win if you are the first or second player? Like a set of moves or strategies to keep in mind of when playing this game? Or an opening trap to score high and make your opponent get negative points?
A partial answer: since Damath is a two-player game of complete information and no randomness, Zermelo's Theorem) says that one of the following is true: * There is a dominant strategy for 1st player. * There is a dominant strategy for 2nd player. * There are strategies for both players that guarantee they don't lose, i.e. perfect play results in a draw (like Tic-Tac-Toe). As far as I can tell, no one has yet determined which of these three is true. Checkers (aka Draughts or Dama, the game Damath is based on) was 'solved' in 2007) with the aid of computers: two perfect players will always draw. Thus I would assume that modern computers are powerful enough to 'solve' Damath as well, but I don't know what the result would be.
stackexchange-boardgames
{ "answer_score": 4, "question_score": 3, "tags": "damath" }
Matrices inversion proof: $A(I-A)^{-1}=(I-A)^{-1} A$ > Let $A$ be a square matrix such that $I-A$ is non-singular, prove that > > $$A(I-A)^{-1}=(I-A)^{-1} A$$ I can prove that $A(I-A)=(I-A)A$. But I don't know where to go next.
Since $I - A$ is non-singular, we know $(I - A)^{-1}$ exists. So... $$A(I-A) = (I-A)A$$ $$(I - A)^{-1}{\bf A (I -A)}(I - A)^{-1} = (I - A)^{-1} {\bf (I - A)A}(I - A)^{-1}$$ $$(I - A)^{-1} A \cdot I = I \cdot A(I - A)^{-1}$$ $$(I - A)^{-1} A = A (I - A)^{-1}$$
stackexchange-math
{ "answer_score": 4, "question_score": 2, "tags": "linear algebra, matrices" }
How to subscribe to DOMContentLoaded event in Angular 2? I'm porting UI theme from angular 1 to 2. In 1-st version I have `$viewContentLoaded` event and I want remake it to angular 2. I'm trying to use `@HostListener('DOMContentLoaded')`, but it doesn't work (without any errors). How can I resolve it? Or what is the best approach to handle that?
You can't, `DOMContentLoaded` was emitted long before the first component is created. You can use class AppComponent { ngAfterViewInit() { // your code here } }
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 7, "tags": "angular, typescript2.0" }
Laravel4+Bootstrap: Redirect::back() - not at the top, but at the bottom of the site I have made a site with Laravel 4 and Bootstrap 2.3.1. It is a one page site with four section: <li><a href="#home" class="">Home</a></li> <li><a href="#portfolio" class="">portfolio</a></li> <li><a href="#services" class="">services</a></li> <li><a href="#contact" class="">Contact</a></li> At the bottom of the site, section contact, there is a form to send an email. If there are validation error, i redirect back with the errors. It works properly, except for the fact the it REDIRECT AT THE TOP OF THE PAGE. i want instead that remain there, at the bottom of the page. How can i do this in laravel 4? This the simple Redirecting code: return Redirect::back()->withInput()->withErrors($validation); Thank you!
Since the anchor tag with hash tag (#) is used to scroll through sections in one page using ID, you will need to re-append your hash tag (#). You can use `URL::previous()` to go back to previous URL and append `#contact`: return Redirect::to(URL::previous() . '#contact') ->withInput() ->withErrors($validation);
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "twitter bootstrap, redirect, laravel, laravel 4" }
How do I upgrade to Istio 1.1.3 on GKE using the Istio add-on? According to this documentation on Google Cloud's website, the supported GKE version for Istio 1.1.3 is `1.13.5-gke.15`. However, even a fresh GKE install using the `$ gcloud beta container clusters create ... --cluster-version "1.13.5-gke.15" ...` command gets the following error: `ERROR: (gcloud.beta.container.clusters.create) ResponseError: code=400, message=Master version "1.13.5-gke.15" is unsupported.`. According to the GKE release notes, `v1.12.7-gke.17` of GKE should "Upgrade Istio to 1.1.3" (the first bullet point). However, it still had version `1.0.6-gke.3`. You can easily find the version installed on GKE using the following command: $ kubectl get deployment istio-pilot -o yaml -n istio-system | grep image: | cut -d ':' -f3 | head -1 1.0.6-gke.3 **How do I get the GKE Istio add-on version 1.1.3 installed on my cluster?**
That GKE version is still in alpha, so you need to pass the `--enable-kubernetes-alpha` flag. Also, you don't need to use `gcloud alpha`. e.g. try the following: gcloud container clusters create mycluster --enable-kubernetes-alpha \ --zone us-central1-c --cluster-version=1.13.5-gke.15 See also the documentation on installing alpha clusters.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "google cloud platform, kubernetes, google kubernetes engine" }
Why npm keep asking me for license information even though it set "UNLICENSED"? I have already set the package.json with following code for my company private project. { ... "license": "UNLICENSED", "private": true, ... } but npm seems not giving up asking me for the license. yarn run v1.22.19 warning ../../../package.json: No license field
Thanks comment from @jonrsharpe. I found the package.json actually from different path, which is actually from `~/` path. For visual studio command, when I click the link it prompt, it actually jump to current path package.json file. That's why it confused me.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "npm, licensing" }
How does c3p0's JdbcProxyGenerator work (metaprogramming in Java‽)? I've been using c3p0 with hibernate for a couple of years. When looking at exception stack traces, I see classes such as `com.mchange.v2.c3p0.impl.NewProxyPreparedStatement` in the stack. I went looking for the source code for these classes and came across the curous `com.mchange.v2.c3p0.codegen` package. In particular, it looks like JdbcProxyGenerator is metaprogramming in Java. I'm having a hard time understanding the codegen mechanism and why it is used. The built jar contains these generated classes, so I'm assuming these classes are built during the build, perhaps as part of a two-phase build. The codegen package does not appear to be in the generated jar. Any insight would be appreciated, just for my own curiosity. Thanks!
yes, you are absolutely right. c3p0 uses code generation to generate non reflective proxy implementations of large JDBC interfaces, "java bean" classes with lots of properties, and some classes containing debug and logging flags (to set up conditional compilation within the build). You can always see the generated classes by typing ant codegen in the source distribution, and then looking at the build/codebase directory. The latest binary distribution of c3p0 (0.9.2-pre2) includes the generated sources in a src.jar file, which you can also find as a maven artifact at < I hope this helps! * * *
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c3p0" }
JSON JQ if without else I use the following JQ command to filter out the JSON. My requirement is to filter out the JSON message if the expected node is present. Or else, do nothing. Hence, I use if, elif, .... sed -n "s/.*Service - //p" $1/response.log* | jq "if (.requests | length) != 0 then .requests |= map(select(.id == \"123\")) elif (.result | length ) != 0 then .result |= map(select(.id== \"123\")) else " " end" > ~/result.log Looks like else is mandatory here. I dont want to do anything inside the else block. Is there anyway, I can ignore else or just print some whitespce inside else. In the above case, it prints double quotes " " in the result file.
You may want to use the idiom: if CONDITION then WHATEVER else empty end `empty` is a filter that outputs nothing at all -- not even null, which is after all something (namely a JSON value). It's a bit like a black hole, only blacker -- it will consume whatever it's offered, but unlike a black hole, it does not even emit Hawking radiation. In your case, you have an "elif" so using "else empty" is probably what you want, but for reference, the above is exactly equivalent to: select(CONDITION) | WHATEVER P.S. My guess is that whatever the goal of the sed command, it could be done more reliably as part of the jq program, perhaps using `walk/1`. ## UPDATE After the release of jq 1.6, a change was made so that "if without else" has the semantics of "if _ then _ else . end", that is: `if P then Q end` === `if P then Q else . end`
stackexchange-stackoverflow
{ "answer_score": 82, "question_score": 42, "tags": "json, if statement, syntax, jq" }
Image URL preg_match failing, can't figure out why So I tested this pattern at regex101, and it works, but when I load it up into PHP I keep getting false, can someone please explain to me why? `preg_match('/^(https?|ftp):\/\/.*(jpeg|png|gif|bmp|jpg)/gi', $_POST['damageImage'])` the `$_POST` would be equal to ` for example sake. I have also tried this with `preg_match_all()` still recieving a false. All I want to do is a simple if-else statement and I can't get past this simple thing. Its got me stumped, what is the overall pitfall I am tripping over here?
Remove g modifier $url = ' preg_match('/^(https?|ftp):\/\/.*(jpeg|png|gif|bmp|jpg)/i', $url, $match); var_dump($match);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, regex" }
Why do hackers inject hidden links? I discovered a hacked site recently which has a `div` in it with a bunch of links to casinos at the top and the `div` is `display:none;`. I understand that black hats may hack sites in order to gain backlinks, but what is the purpose if the links are `display:none` ? I thought Google disregards these links? Are these hackers smart enough to hack sites but too stupid to read up on SEO basics? So what is there to gain by injecting hidden links?
Google does not just ignore links in sections that are `display:none`. Consider DHTML multi-level drop down menus. In such a menu, you hover over the top level menu item and a list of links drops down. That is a case in which the links are in `display:none` initially, but user interaction with the page shows them. Using drop down menus like this is common practice and absolutely fine with Google. It is impossible to write an algorithm that can tell if a div that is `display:none` could ever by shown by user interaction and javascript. (See the halting problem.) The best that Google can do is a heuristic. Hackers that insert hidden links into sites are doing "churn and burn" SEO. Their rankings may increase for a while until Google discovers their spam. Then Google penalizes their site. The hackers throw that site away and start a new site.
stackexchange-webmasters
{ "answer_score": 10, "question_score": 6, "tags": "seo, links, hacking, blackhat" }
Кликабельный текст в Toolbar Подскажите пожалуйста следующее, есть много фрагментов и по клику текста (имя проекта) в `toolbar`'е должен показывать главный фрагмент. Как сделать этот текст кликабельным или куда копать хотя бы?
**XML:** <android.support.v7.widget.Toolbar android:id="@+id/toolbar" ...> <TextView android:id="@+id/toolbar_title" ... /> </android.support.v7.widget.Toolbar> **В классе:** toolbar.findViewById(R.id.toolbar_title).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG,"Clicked"); } }); _P.S. Убрать основное название и добавить его в_`TextView`.
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android, actionbar, android toolbar, android on click" }
$e+\pi$ and $e\cdot\pi$ Transcendental number or what? $e+\pi$ and $e\cdot\pi$ Transcendental number or what? I know what $e$ and $\pi$ transcrendental and $e\cdot\pi$ posible be rational and posible to be irrational, ($\sqrt2\cdot\sqrt2=rational$,$\sqrt2\cdot\sqrt3=irratinoal$) Anyway, We can use this function $f_n=\dfrac{x^n(1-x)^n}{n!}$ in proof of $\pi$,$e$ which these irrational, But in there, how we can prove these 2 equation ?
As of today, we don't know if $e+\pi$, $e\cdot\pi$ are irrational numbers. _This is an open problem_. From the expansion $$(x-\pi)(x-e) = x^2 - (e + \pi)x + e\pi$$ one sees that the above polynomial can't have rational coefficients. Thus at least one of $e + \pi$ and $e\pi$ is irrational. As @Henning Makholm pointed out, actually at least one of them is not just irrational but transcendental (since the roots of a polynomial with algebraic coefficients are algebraic). We are inclined to think both are transcendental numbers. A similar question.
stackexchange-math
{ "answer_score": 14, "question_score": 1, "tags": "real analysis, pi, transcendental numbers" }
How to wrap one div id around another one? How to wrap one div around another? I have following two `div` ids: #course { width: 325px; padding-right: 25px; border-right: 1px solid #999; border-top: 1px solid #999; } #home-page-sign-up { width: 275px; #padding-left: 25px; float: right; margin: auto; #position: relative; display: block; clear: both; } I want `#course` to be on left and `#home-page-sign-up` on right just next to it. I do get block on left and right as assigned but one is below another, I want them to be side by side. How can I achieve it?
You will want to float both of them left: #course{ float:left; width:325px; padding-right:25px; border-right:1px solid #999; border-top:1px solid #999; } #home-page-sign-up { width:275px; #padding-left:25px; float:left; margin: auto; #position:relative; display:block; } Just make sure #course falls first in the html
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "html, css" }
How to unlock admin in magento 1.9.3.3 using database? After entering the wrong password Magento has locked my admin account, How can I unlock this using database? If there is another way of unlocking admin account please tell me. My Magento version is 1.9.3.3
This is the SQL way of unlocking a Magento admin account: UPDATE admin_user SET failures_num=0, first_failure=NULL, lock_expires=NULL WHERE username='<username>'; Replace the `<username>` with the target account's username.
stackexchange-magento
{ "answer_score": 1, "question_score": 0, "tags": "magento 1.9.3.3" }
How does the OpenID 2.0 Deprication effect Google Users API? Will code that relies on the Users API to grab the email address of a Google Account be effect by this depreciation? will `user = users.get_current_user()` be enough to get back the email address?
> will `user = users.get_current_user()` be enough to get back the email address? It will be enough, but you need to upgrade asap because many other features would not work.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "google app engine, google api, google api python client" }
Div shifted to the right only in Firefox The breadcrumbs part of the page is shifted to the right (in Firefox) with no apparent reason. HTML: <div class="region region-header"> <section id="block-easy-breadcrumb-easy-breadcrumb" class="block block-easy-breadcrumb"> <section class="content"> <div id="breadcrumbs-one"> </section> </section> </div> CSS: #breadcrumbs-one { border-width: 1px; border-style: solid; border-color: #FFFFFF #FFFFFF #E7E7E7; box-shadow: 0 0 2px rgba(0, 0, 0, 0.2); overflow: hidden; width: 100%; } Here is the link to site: < It's not in english. Hope you can help.
I assume the issue is in `#main`. when you change your margin to `-7px auto 40px;` The things work. Also, if you do not want to make changes to `#main`, you need to change the padding of `#header, #footer` CSS with `10px 10px 8px;` values respectively. There are 1px issues that have a conflicting inheritance or structural differences that tend to change the layout styles of some elements if not calculated properly. Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "html, css, firefox, drupal, styling" }
Using multiple carets in single or multiple textareas and textboxes ### I think I may already know the answer to this one but... Is it possible to have two carets in a single textbox, or have two separate textboxes focused at the same time allowing the user to type into both symataniously? I know you can simulate this by adding a keydown listener and making their values match, but I want the visible caret in both fields. If not, does anyone have any ideas on how to simulate this?
Ace editor supports multiple cursors/carets like Sublime Text: < `Ctrl`+`Click` (or `Cmd(⌘)`+`Click` on OS X) in the live demo on that page to get multiple cursors and type away! You can also select a bunch of code and use `Tab` to indent a tab space, or `Shift`+`Tab` to outdent a tab space.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 9, "tags": "javascript, jquery, html, forms" }
Как сделать статистику из даты в бд Есть статистика вот в таком формате(на скрине показал скрин из бд) Как или какой запрос нужен что бы запросить колличество users_id за последний день,неделю,месяц и тд? ![.](
SELECT COUNT(u.user_id) FROM (SELECT user_id FROM some_table WHERE DATE_FORMAT(data, '%y%v') = date_format(DATE(NOW()), '%y%v') GROUP BY user_id) u; # Неделя в формате год (две последние цифры года), неделя (с ведущим нулем) SELECT user_id FROM some_table WHERE DATE_FORMAT(data, '%y%v') = 1908; # 8-я неделя 2019 года # За прошлую неделю в формате год (две последние цифры года), неделя (с ведущим нулем) SELECT user_id FROM some_table WHERE DATE_FORMAT(data, '%y%v') = DATE_FORMAT(DATE(NOW()), '%y%v') - 1; # Год в своем привычном формате SELECT user_id FROM some_table WHERE DATE_FORMAT(data, '%Y') = 2019; Ну и дальше в таком-же духе
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, mysql, sql, telebot" }
Return a part of regular expression with egrep on Ubuntu? I'm wondering if I can select only a part of a regular expression with egrep on Ubuntu. If I do this: wget -qO- | egrep -o -m 1 'Current version: <b>v(.*)</b>' It returned me this: Current version: <b>v0.10.28</b> But I only need the version number: 0.10.28 How can I perform this?
You can use `grep -P` (PCRE): wget -qO- | grep -oP -m 1 'Current version: <b>v\K(.*?)(?=</b>)'
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "linux, bash, grep" }
Replace values in a table I have a table (ascii format with space delimiter), as follow: 1 1 1900 111 1 2 1900 121 1 3 1900 145 1 4 1900 1.45e 07 1 5 1900 5.21e 25 1 6 1900 152 I would like, that if there is a fifth column (obviously enclosing the value of the exponent) the value is replaced by 0. Therefore, considering this example, the desired output should be as follow: 1 1 1900 111 1 2 1900 121 1 3 1900 145 1 4 1900 0 1 5 1900 0 1 6 1900 152 Does anyone have any guidance?
This should do the trick awk '{if (NF>4){print $1, $2, $3 , "0" } else {print $0}}' INPUTFILE.txt
stackexchange-unix
{ "answer_score": 2, "question_score": 1, "tags": "bash, replace, table" }
Serve Javascript as text from Firebase Function I'm trying to serve some text as javascript from a firebase function. My function looks like: module.exports.js = functions.https.onRequest(async (req, res) => { let source = "...."; res.status(200).send(source); }); That I want to be able to load it in a `<script/>` tag: <script type="module" src=" But when I do, I get an error in the browser: > TypeError: 'text/html' is not a valid JavaScript MIME type. I've tried adding a `type("application/javascript")` to the response, with no affect. How do I set the correct response headers / MIME type so that my response can be loaded by the browser as Javascript?
Nevermind. Problem was in the ...'s. Setting response headers does do the trick: res.set({ 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/javascript' });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, firebase, google cloud functions" }
How to find a group with generators and relations fulfilling several properties? I would like to ask the following question: Let $G:= \langle x,y \mid \text{some relations} \rangle$. > Is it possible to find a group $G$ as above fulfilling the following criteria simultaneously? * The order $o(x)$ of the element $x$ is finite: $o(x) < \infty$ * $o(y) < \infty$ * $ N:= \langle x^2 \rangle \unlhd G$ * $ |G|=\infty$ * $ |G/N| < \infty$ When I tried to find such a group $G$, I always ended up with a finite group $G$, but I would like to have $|G|=\infty$. Thank you very much for the help.
Since $\lvert x\rvert$ is finite and $N=\langle g= x^2\rangle\unlhd G$ is cyclic, we have $$g^{\frac{\lvert x\rvert}{2}}=(x^2)^{\frac{\lvert x\rvert}{2}}=x^{\lvert x\rvert}=e,$$ so that $\lvert N\rvert$ is finite. But now $$\begin{align} \lvert G\rvert&=[G:N]\lvert N\rvert\\\ &=\lvert G/N\rvert\lvert N\rvert\\\ &<\infty, \end{align}$$ a contradiction.
stackexchange-math
{ "answer_score": 2, "question_score": -1, "tags": "group theory, group presentation, infinite groups, combinatorial group theory" }
How to show a vector space is closed under an Operation? Consider an operator $A$ acting on a vector in some $n$-dimensional vector space $V = \operatorname{span}(v_1, v_2,..., v_n)$. How does one show that the vector space is closed under the operator (i.e. $Av_j \rightarrow v_i$, where $v_j$ and $v_i$ are in $\operatorname{span}(v_1, v_2, ..., v_n)$ ). Is it simply testing the resultant vector to see if it satisfies the conditions for an element in our initial vector space or is there something more? Are there some general conditions for an operator that, if satisfied, imply such closure? Thanks
If $V = \operatorname{span}(v_1, v_2,..., v_n)$ and if you want to show that $A(V) \subseteq V$, then you have to show that $Av_j \in V$ for $j=1,...,n$.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "linear algebra, vector spaces, vectors" }
how to select specific columns from a data table in vb.net? I have a data table from which i am filtering data based on condition,but how to display specific columns only from the data table? Dim Dt As New DataTable Dim SQlDa As SqlDataAdapter = New SqlDataAdapter(SqlCmd) SQlDa.Fill(TrackingDt) Dim Rows() As DataRow = Dt.Select("State = " + "'" + State + "'") Dim TempDt As New DataTable If Rows.Length > -1 Then TempDt = Rows.CopyToDataTable() End If Return TempDt
Dim view As New DataView(MyDataTable) Dim distinctValues As DataTable = view.ToTable(True, "ColumnA")
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "asp.net, vb.net, datatable, datarow" }
Find Items in a comma separated database column I am working on searching algorithm for an ecommerce platform. The platform is able to create variations for different products and all the available variations for a products are included in a comma separated column. Here are all the fields. 1. `product_id` \- eg 1 2. `variation_combo` \- eg 54,35,49 (these are comma separated ids for different variations) 3. `product_name` \- eg "Nike branded Tshirt" Here is what i would like to achieve, something like * `SELECT product_id FROM table where variation_combo contains 35 AND 54 AND 49` * `SELECT product_id FROM table where variation_combo contains 35 AND 54` * `SELECT product_id FROM table where variation_combo contains 49`
Refer this: MySQL query finding values in a comma separated string select product_id from table where find_in_set('35',variation_combo) <> 0 and find_in_set('54',variation_combo) <> 0 and find_in_set('49',variation_combo) <> 0
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, mysql, sql, regex, database" }
How to reduce frequency resolution for high sampling rate and lot of samples? I'm kinda new in this field, and I have a following situation. There is a 1s long audio signal, with Fs = 96000Hz, and I have 96000 samples accordingly. If I do a single FFT on the entire signal, I get this 1Hz frequency and 48000 points, resulting in a very "fat" logarithmic spectrum, like in the picture below. How can I reduce resolution and thin out my plot without reducing sampling rate? Thanks in advance. ![enter image description here](
A simple way is to split the data into smaller N sample segments (pick N to suit your desired frequency resolution, then average the power or amplitude of all the FFT spectra: $$ \hat X = \frac{1}{N} \sum^{N-1}_{n=0} X_n X_n^* $$ Where $X_n, n \in \left\\{0:N-1\right\\}$ is your series of shorter FFT results and $\hat X$ is the averaged power spectra. If I remember correctly, for noise signals, the variance is reduced by $\frac{1}{N}$.
stackexchange-dsp
{ "answer_score": 3, "question_score": 0, "tags": "fft, frequency spectrum" }
Ordered products report exclude orders with status closed the default Magento2 report from ordered products excludes orders with status canceled. I also want to exclude status closed. /app/code/Magento/Reports/Model/ResourceModel/Product/Sold/Collection.php in line 60 shows $connection->quoteInto("{$orderTableAliasName}.state <> ?", \Magento\Sales\Model\Order::STATE_CANCELED), How can I add STATE_CLOSED here? I tried a bit but no success.
your condition should be in your case $connection->quoteInto( "{$orderTableAliasName}.state NOT IN (?)", [ \Magento\Sales\Model\Order::STATE_CANCELED, \Magento\Sales\Model\Order::STATE_CLOSED ] )
stackexchange-magento
{ "answer_score": 2, "question_score": 0, "tags": "magento2, reports" }
Web sockets to grab live data from my server I'm wanting to push real time data to my website via web sockets. The data is basically just text saying "Artist - Title", it is generated via my Windows server that is streaming live constantly. Can anybody point me in the right direction (i.e a manual/knowledge site) where I can read up on what will be required? Right now I have a PHP script that is pulling data from the MySQL database on my server, that then drops it onto my site as described above (Artist - Title) - obviously this doesn't accomplish what I want as it requires people to refresh the site every time they want to see what's currently being streamed, what I want is for it to just appear the second it starts playing on my server. I've tried researching into web sockets with no prevail to what I want to accomplish. If anybody has the knowledge as to what I'm missing to make this work I would be most appreciative of your answer.
Consider running a Node.js server with socket.io. See socket.io chat app tutorial and it should become clear. Basically you need JavaScript on your page to open the socket and respond to messages.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "php, mysql, websocket" }
JQuery Cookies: Trying to retrieve a cookie value I am using Jquery Cookie but am having difficulty setting and retrieving the info. What I have so far is: <script type="text/javascript" charset="utf-8" src="js/jquery.cookie.js"></script> <script type="text/javascript"> $(function() { var cookiedate = new Date(); cookiedate.setTime(cookiedate.getTime() + (60 * 60 * 1000)); $.cookie("mycookie", "checked", { expires: cookiedate, path: '/' }); console.log(cookiedate); alert( $.cookie("mycookie") ); }); </script> But it just isnt working. Can anyone help me out to find out what I am doing wrong? Thanks!
jquery.Cookie handles the dates for you. Just feed it the number of days you want the cookie to be valid for: $(function() { $.cookie("mycookie", "checked", { expires: 365, path: '/' }); //valid for a year alert( $.cookie("mycookie") ); }); P.S. Just in case you are using Chrome and are testing locally - Chrome doesnt support local cookies - Upload it to a server.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, cookies, set" }
Java base64 encode, decode yield different results I'm using this: `import com.sun.org.apache.xml.internal.security.utils.Base64;` to encode/decode Base64 strings and byte arrays to store into a db. I'm testing out encoding and decoding to see if I can get back the original string: SecureRandom srand = new SecureRandom(); byte[] randomSalt = new byte[64]; srand.nextBytes(randomSalt); System.out.println("rand salt bytes: " + randomSalt); // first line String salt = Base64.encode(randomSalt); try { System.out.println(Base64.decode(salt)); // second line }catch(Base64DecodingException e){ System.out.println(e); } However, this prints out: rand salt bytes: [B@68286c59 [B@44d01f20 Why are these not the same, so that I can get back the original byte array?
What you are doing is actually dealing with the java pointer instead of the actual bytes. This is the correct way to implement byte[] bytesEncoded = Base64.encodeBase64(str .getBytes()); System.out.println("ecncoded value is " + new String(bytesEncoded )); // Decode data on other side, by processing encoded data byte[] valueDecoded= Base64.decodeBase64(bytesEncoded ); System.out.println("Decoded value is " + new String(valueDecoded));
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "java, string, encoding, base64, decoding" }
Как правильно составить запрос с Any()? Доброго времени суток! Есть необходимость получить выборку постов из БД (использую Entity Framework). Подскажите, пожалуйста, как правильно написать запрос на линк. Суть: Есть таблица с подписками для пользователя, в ней может быть несколько строк значений. List<TRM_Subscribers> userSubscribers =sdb.TRM_Subscribers.Where(x => x.UserID == 1).ToList(); Также есть сами посты: (по двум параметрам из userSubscribers я хочу сделать выборку: IDCategory;idObj ;) postses = sdb.TRM_Posts.Where(x => x.IDCategory==1 || userSubscribers.Any(g => g.IDObj == x.idObj && g.IDCat == x.IDCategory)).ToList(); На меня компилятор ругается: _Unable to create a constant value of type 'Project.Models.TRM_Subscribers'. Only primitive types or enumeration types are supported in this context._
List<TRM_Subscribers> userSubscribers =sdb.TRM_Subscribers.Where(x => x.UserID == 1).ToList(); замените на var query=sdb.TRM_Subscribers.Where(x => x.UserID == 1); List<TRM_Subscribers> userSubscribers =query.ToList(); postses = sdb.TRM_Posts.Where(x => x.IDCategory==1 || query.Any(g => g.IDObj == x.idObj && g.IDCat == x.IDCategory)).ToList();
stackexchange-ru_stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c#, entity framework, linq" }