INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Remove previous chapter's title from current chapter's header Title of previous chapter appears in the header of the bibliography chapter in my report. How can I fix that? I should have " Biblographie" instead of " Liste des publications".![enter image description here](
It worked when I added \clearpage and \markboth{Bibliographie}{Bibliographie} right before calling bibliorgraphy.
stackexchange-tex
{ "answer_score": 0, "question_score": 0, "tags": "header footer, chapters, report" }
Reversing the bits in an integer x Bit Reversal I found this code for reversing the bits in an integer x (assume a 32bit value): unsigned int reverse(register unsigned int x) { x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1)); x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2)); x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4)); x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8)); return((x >> 16) | (x << 16)); } I am unable to understand the logic/algorithm behind this code. What is the purpose of all the magic numbers?
Let's look at how it's done for an 8 bit value: The first line in the function takes every second bit and moves it left or right: 12345678 --> 1-3-5-7- --> -1-3-5-7 --> 21436587 -2-4-6-8 2-4-6-8- The second line takes groups of two bits and moves left or right: 21436587 --> 21--65-- --> --21--65 --> 43218765 --43--87 43--87-- The third line takes groups of four bits and moves left or right: 43218765 --> 4321---- --> ----4321 --> 87654321 ----8765 8765---- Now the bits are reversed. For a 32 bit value you need two more steps that moves bits in groups of 8 and 16.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "bit" }
What is the differnce between Corporate/Company level and Listing level Market cap Upon searching on google, I will end up getting types of MarketCap (Large, Mid, Small etc). Please help.
Many companies have different classes of shares, but not all shares are listed on an exchange for trading (and some are not public at all too). e.g. Alphabet (parent company of Google) has Class A shares (symbol: GOOGL) and Class C shares (symbol: GOOG) listed. Class B shares are held by the founders and are not listed. Other companies, such as BHP Billiton, have shares listed on different exchanges, each with their own capital structure (eg. LSE: BHP, ASX: BHP) Corporate/Company level market cap includes these all these classes of shares across all exchanges and share classes. The listing level market only gives the portion of the company's market cap attributed to that particular symbol/listing.
stackexchange-money
{ "answer_score": 2, "question_score": 1, "tags": "stocks, stock markets, market capitalization" }
How to listen to angular 2 events MANUALLY on a dependency injected instance? If i have a component like @Component({selector: 'todo-cmp'}) class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); // this fires an event } } and in another component I get a copy of it through DI as in: ... class SomeOtherClass(){ constructor(todoCmp:TodoCmp){ // how do I listen to ... } ... How do I add an event listener manually inside "SomeOtherClass" and listen to any click events fired from the depenendcy injected instance of ToDoCmp.. something like todoCmp.addEventListener('complete',function(e){}); maybe? or something better in ng2? TX Sean.
First, `EventEmitter.next()` has been `EventEmitter.emit()` since alpha-45 or so. Second, the method you're looking for is `.subscribe()` class SomeOtherClass(){ constructor(todoCmp:TodoCmp){ todoCmp.complete.subscribe((result)=>{ //result == arg passed into emit() })) } Note that this information is readily available in the docs \- you should really check those out, as `EventEmitter` is much more capable than the event listeners you're used to.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 6, "tags": "typescript, angular" }
Creating a password regex Right now I need to duplicate a password expression validator for a website. The password is only required to be 8-25 characters (only alphabet characters) long. I thought this was weird and had been using this regex `(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,25})` but it has to be optional to have a capital letter, special characters and/or numbers throughout the password. I'm not particularly apt at building regex's where there are optional characters. Any help would be be appreciated. I am using asp.net's `RegularExpressionValidator`.
This pattern should work: ^[a-zA-Z]{8,25}$ It matches a string consisting of 8 to 25 Latin letters. If you want to allow numbers as well, this pattern should work: ^[a-zA-Z0-9]{8,25}$ It matches a string consisting of 8 to 25 Latin letters or decimal digits. If you want to allow special characters as well, this pattern should work: ^[a-zA-Z0-9$@!]{8,25}$ It matches a string consisting of 8 to 25 Latin letters, decimal digits, or symbols, `$`, `@` or `!` (of course you can add to this set fairly easily).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "asp.net, regex" }
get filesystem mount point in kernel module I want to get the filesystem mount point for a file system in my kernel module, which is a stackable filesystem. Eg. if /home/ab/abc is a file and /home is mounted on a different filesystem I want to have a dentry or path struct to /home. I want to do this in a module without modifying kernel code. e.g. there is a file in /home/user/ and now I want to know in which partition this file is. For example this file might be in the partition same as "/" or this file might be in another partition mounted on /home or /home/user.
You can get the list of file systems from `current->namespace`. By iterating `current->namespace->list` (items being `struct vfsmount`) you can get all mounted file systems. `vfsmount->mnt_mountpoint` is the directory entry you want. You can follow the code that `prints /proc/mounts` (e.g. `base.c/mountstats_open`, `namespace.c/m_start`) to get more details (e.g. some locking is needed). I don't know if you can do it in a kernel module, however.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 4, "tags": "linux, filesystems, linux kernel, kernel module" }
CMake could not find the VTKConfig.cmake I'm trying to compile a program in CMake but I'm getting this error. By not providing "FindVTK.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by "VTK", but CMake did not find one. Could not find a package configuration file provided by "VTK" (requested version 6.1) with any of the following names: VTKConfig.cmake vtk-config.cmake I can't find the relevant files (VTKConfig.cmake or vtk-config.cmake) on the machine but do have VTKConfig.cmake.in (which also doesn't work). Does anyone know where I can download the file from, or what I might be doing wrong.
It seems like you just have the VTK source code but haven't built it yet. VTKConfig.cmake.in is a template used by CMake to generate the VTKConfig.cmake file in the build and install directory. Look at < to see how to build VTK.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 11, "tags": "cmake, vtk" }
Can laser-induced graphene wires produce electromagnetic fields if a current is passed through them? For those who don't know, laser-induced graphene (LIG)) is a porous type of graphene that appears after exposing certain types of carbon-based materials with a laser. In this video, they made LIG on Kapton tape using a cheap 400 nanometer laser engraver module. He used the LIG to make supercapacitors, not to make conductive wires. At the end he used the LIG to make a low-voltage heater. If I took a Kapton wire, turned it into a LIG wire, used the wire to make a coil and passed an electrial current (a DC current), would it generate an electromagnetic field?
The current through the coil will produce a magnetic field. The voltage across the coil that pushes the current through the coil will produce an electric field.
stackexchange-electronics
{ "answer_score": 0, "question_score": 1, "tags": "electromagnetism, materials, electromagnet, lithography" }
Are there any alternate module for qq_import module (Quiz Questions Import Module)? Are there any alternate module for qq_import module (Quiz Questions Import Module) ? It seems it has no Drupal 7 version for it.
It turns our that there are some similar existing modules on D7 but not as close as qq_import module. Instead, I just created my own custom D7 quiz question importer. It only imports multiple choice type of questions though
stackexchange-drupal
{ "answer_score": 0, "question_score": 0, "tags": "7, importing exporting, quiz" }
Append var to div I made a Roulette game, but now I´m struggeling to use an int in the Append method. I want to use the var number as the paragraph of the appended div. Thanks in advance! if (Red == true) { Red = false; var randnum = Math.floor((Math.random() * 4) + 1); var number; switch (randnum) { case 1: number = 1; break; case 2: number = 3; break; case 3: number = 5; break; case 4: number = 7; break; } $("#WheelList").append("<li><div class='red'><center>'number'</center></div></li>");
Like this.In javascript `+` operator is used for concatenation. if (Red == true) { Red = false; var randnum = Math.floor((Math.random() * 4) + 1); var number; switch (randnum) { case 1: number = 1; break; case 2: number = 3; break; case 3: number = 5; break; case 4: number = 7; break; } $("#WheelList").append("<li><div class='red'><center>"+number+"</center></div></li>");
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript" }
Pinging to multiple servers via windows batch script I'm trying to check response from list of **n-thousand IPs** using ping command via **windows batch script** and save all results in a file ( **yes** if response and **no** if don't). Is this even possible via batch script? When I'm using script printed below ( _pingingN.bat_ ) I'm getting only first IP answer. @ECHO OFF SET ServerList="C:\MyPath\ip.txt" SET LogFile="C:\MyPath\PingResults.txt" IF EXISTS %LogFile% DEL %LogFile% FOR %%a IN (%ServerList%) DO ( ping -n 1 %%a | find "TTL=" > NUL IF %ERRORLEVEL% NEQ 0 ( echo no >> %LogFile% ) ELSE ( echo yes >> %LogFile% ) )
Based on my comment and using the `&&` and `||` conditionals, here's how I would do it: @Echo Off Set "ServerList=C:\MyPath\ip.txt" Set "LogFile=C:\MyPath\PingResults.txt" If Not Exist "%ServerList%" Exit /B >"%LogFile%" (For /F UseBackQ %%A In ("%ServerList%" ) Do Ping -n 1 %%A|Find "TTL=">Nul&&(Echo Yes [%%A])||Echo No [%%A]) _You'll note that I have also included the IP in the output, otherwise your log file will not show you which ones did or didn't pass/fail._
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "windows, shell, batch file, cmd, scripting" }
small confusion on $f'(x)=f'(-x)$ > I know it might be silly but I have a small confusion regarding this function $f'(x)=f'(-x)$ we know that $f'(x)=f'(-x)$ is an even function so f(x) must be an odd function but in my textbook question it is written that is $f(x)$ is an even function then $f(x)=0$ for all real numbers according to me it is correct in my textbook it is written that it is an incorrect statement. please explain me why is it incorrect
Since $f$ is odd we have $f(x)=-f(-x)$ for any $x$. But $f$ is also even, so from $f(-x)=f(x)$ the previous becomes $f(x)=-f(x)$. Now we see that $f(x)=0$. This is true for any $x$, so $f$ must be constantly $0$.
stackexchange-math
{ "answer_score": 4, "question_score": -2, "tags": "calculus, functions, derivatives" }
Transform this iteration function to recursive This is a function to display the sum of the input digits with iteration perspective: function sumOfDigits(number) { let strNumber = number.toString() let output = 0; for(i=0;i<strNumber.length;i++){ let tmp = parseInt(strNumber[i]) output = output + tmp } return output } // TEST CASES console.log(sumOfDigits(512)); // 8 console.log(sumOfDigits(1542)); // 12 console.log(sumOfDigits(5)); // 5 console.log(sumOfDigits(21)); // 3 console.log(sumOfDigits(11111)); // 5 I am wondering how we write this function in a recursive way?
Using the modulo operator, you can get the remainder (which in the case of a divison by 10, is the last number) and then add the next iteration. function sumOfDigits (n) { if (n === 0) return 0 return (n % 10 + sumOfDigits(Math.floor(n / 10))) } console.log(sumOfDigits(512)) If you want to see a more detailed explanation, check <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, recursion, iteration" }
Group Array with count I have an array of items that contains several properties. One of the properties is an array of tags. What is the best way of getting all the tags used in those items and ordered by the number of times that those tags are being used on those items? I've been trying to look to underscore js but not getting the expected results. return _.groupBy(items, 'tags'); Example of my data: item1 - itemName: item1 - tags(array): tag1, tag2 item2 - itemName: item2 - tags(array): tag1, tag3 so I'm trying to get something like `{tag1, 2}{tag2, 1}{tag3, 1}` Update: My tag contains a ID and a name. I'm trying to group by those IDs
You can do this simply using a reduce operation. For example var items = [{ itemName: 'item1', tags: [ {id: 'tag1', name: 'Tag 1'}, {id: 'tag2', name: 'Tag 2'} ] }, { itemName: 'item2', tags: [ {id: 'tag1', name: 'Tag 1'}, {id: 'tag3', name: 'Tag 3'} ] }]; var tags = items.reduce((tags, item) => { item.tags.forEach(tag => { tags[tag.id] = tags[tag.id] || 0; tags[tag.id]++; }); return tags; }, {}); document.write('<pre>' + JSON.stringify(tags, null, ' ') + '</pre>');
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "javascript, arrays, group by, underscore.js" }
Can players enchant items? I know that the DM can give you enchanted items, but can players spend gold and downtime to enchant their own?
The DMG has rules for this, at pp. 128-129, "Crafting Magic Items." You'll have to work with your GM to work out the details. In short, you can (with the GM's say-so) spend gold, spell slots, and time to create magic items; the rarer/more powerful the item, the harder to craft.
stackexchange-rpg
{ "answer_score": 14, "question_score": 7, "tags": "dnd 5e, magic items, crafting" }
To handle windows save dialog box in IE11 Can someone help me with the windows dialog box handling in selenium using auto IT. I want to press save. Have used `Send('!s')` in AutoIt script and called in my program using `Runtime.getRuntime().exec("C:\\Selenium\\FileDownload.exe")`. This saves the doc but after that program errors out. Have also used robot class but it did not work for me. Robot robot=new Robot(); robot.keyPress(KeyEvent.VK_ALT); robot.keyPress(KeyEvent.VK_S); robot.keyRelease(KeyEvent.VK_ALT); robot.keyRelease(KeyEvent.VK_S); Thanks
Use the following code to call your AutoIT script if the script runs perfectly fine when it is run independently. `String strModalDialogExeName = "C:\\Selenium\\FileUpload.exe"; Process p = Runtime.getRuntime().exec(strModalDialogExeName); p.waitFor(); int intExitCode = p.exitValue(); System.out.println(intExitCode); p.destroy();`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "selenium, autoit" }
Why "Your question could not be submitted." I am trying to submit a question. I have spent a lot of effort trying to be clear. > I like to make icons containing text. They are 240x240 pixels. > > However, when I put them on my desktop, the icons are way to large and I have to resize them. > > Is there a way to make them display their true size? But I keep getting > Your question could not be submitted. What could I do differently? ![enter image description here](
Scroll down on that page. The "issue" would hopefully be highlighted in red. My guess would be that you need to add at least one tag?
stackexchange-meta_askubuntu
{ "answer_score": 4, "question_score": 2, "tags": "support, asking questions" }
php pear db disconnect do i need manually call `disconnect()` ? for example <?php // Create a valid DB object named $db // at the beginning of your program... require_once 'DB.php'; $db =& DB::connect('pgsql://usr:pw@localhost/dbnam'); if (PEAR::isError($db)) { die($db->getMessage()); } // Proceed with a query... $res =& $db->query('SELECT * FROM clients'); // Always check that result is not an error if (PEAR::isError($res)) { $db->disconnect(); //?????????? die($res->getMessage()); } ................ working $db->disconnect();//?????????? return $value; ?>
No you don't need to disconnect from a database. It might be helpful for a long running script to use this operation, but your connection gets closed once the script has finished anyway.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, database, pear" }
Lib error while executing python file with WSL (ModuleNotFoundError: No module named 'PIL') First of all, sorry about my english, this isn't my native language. PS C:\Users\...... wsl ./Test.py Traceback (most recent call last): File "./Test.py", line 2, in <module> from PIL import Image ModuleNotFoundError: No module named 'PIL' I made this **Test.py** using pycharm. Its a wordcloud program and it works fine with pycharm. However, when I try to execute this file with _**wsl ./**_ it shows me the error above. Can someone help?
According to your comment you are checking if Pillow is installed in Windows, but you are running your Windows-hosted `Test.py` in WSL, i.e. using python interpreter and libraries that are installed in WSL. To illustrate, Powershell session in Windows, using python libpath from conda: (base) PS C:\> python -c "import os; print(os.__file__)" C:\Users\ml\Miniconda3\lib\os.py Powershell session in Windows, but executing code in WSL, python and libpath from Ubuntu: (base) PS C:\> wsl python3 -c "import os; print(os.__file__)" /usr/lib/python3.8/os.py You do need to check your Pillow installation, but in WSL.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, python imaging library, windows subsystem for linux" }
Experience Analytics page views and visits much lower than expected I have custom analytics which tracks page views and it seems to wildly differ from what Experience Analytics reports. For higher volume pages it seems to be 30% to 60% lower. For low volume pages (i.e. less than 500 visits per month) it can be off by orders of magnitude, with some days having 0 visits even though I know for a fact that is wrong. I have followed the xDB troubleshooting guide and the results have not improved. Is there some potential config issue or other explanation for this?
The main issue was because I had the **Sitecore.ExperienceAnalytics.Reduce.config** enabled. Disabling this and performing an reporting DB rebuild improved the discrepancy of high volume pages and fixed the issue with low volume pages. The rest of the discrepancy can be explained along the lines of this kb article, and due to the fact that it's not clear what the difference between a sitecore interaction (page visit) and a sitecore page view is. Pages can be viewed multiple times during a single interaction.
stackexchange-sitecore
{ "answer_score": 3, "question_score": 1, "tags": "experience analytics" }
How to read pdf stream in angularjs I got the following PDF stream from a server: !PDF STREAM How can this stream be read in AngularJS? I tried to open this as a PDF file in a new window by using the following code: .success(function(data) { window.open("data:application/pdf," + escape(data)); }); But I'm unable to see the content in opened window.
I achieved this by changing my controller code $http.get('/retrievePDFFiles', {responseType: 'arraybuffer'}) .success(function (data) { var file = new Blob([data], {type: 'application/pdf'}); var fileURL = URL.createObjectURL(file); window.open(fileURL); });
stackexchange-stackoverflow
{ "answer_score": 51, "question_score": 30, "tags": "java, angularjs, pdf, inputstream" }
SCALA: Type of object what is the type of this object? class Zad1A,B { override def toString: String = "(" + fst +","+snd+")" } object Zad1 { def main(args: Array[String]): Unit = { val v = new Zad1Int, String println(v) } } I tried to print the class name with : println(v.getClass) // would print: class $line8.$read$$iw$$iw$Zad1
The type of a singleton `object` is its singleton type, ergo, the type of `Zad1` is `Zad1.type`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -4, "tags": "scala" }
How to convert a QByteArray to a python string in PySide2 I have a `PySide2.QtCore.QByteArray` object called `roleName` which I got encoding a python string: propName = metaProp.name() // this is call of const char *QMetaProperty::name() // encode the object roleName = QByteArray(propName.encode()) print(roleName) // this gives b'myname' // now I would like to get just "myname" without the "b" roleString = str(roleName) print(roleString) // this gives the same output as above How can I get my decoded string back?
In Python3, you must specify an encoding when converting a bytes-like object to a text string. In PySide/PyQt, this applies to `QByteArray` in just the same way as it does with `bytes`. If you don't specify and encoding, `str()` works like `repr()`: >>> ba = Qt.QByteArray(b'foo') >>> str(ba) "b'foo'" >>> b = b'foo' >>> str(b) "b'foo'" There are several different ways to convert to a text string: >>> str(ba, 'utf-8') # explicit encoding 'foo' >>> bytes(ba).decode() # default utf-8 encoding 'foo' >>> ba.data().decode() # default utf-8 encoding 'foo' The last example is specific to `QByteArray`, but the first two should work with any bytes-like object.
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 10, "tags": "python, python 3.x, string, pyside2, qbytearray" }
How to get column name with max value across multiple columns I have the following data, I am using proc sql in SAS. ID Col_1 Col_2 Col_3 1 100 110 120 I want to get ID Max_Col 1 Col_3
This isn't a SQL solution, since the problem lends itself better to a SAS data step. `VNAME()` also doesn't work in SAS SQL. Assuming you're using SAS then you can use a combination of the `VNAME`, `MAX` ,and `WHICHN` functions. What would you want to happen if you had duplicates for the maximum value? data want; set have; array col(3) col_1-col_3; index_of_max=whichn(max(of col(*)), of col(*)); variable_name=vname(col(index_of_max)); run;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -2, "tags": "sql, sas" }
Can we interrupt our service if we use CI/CD I am a consultant for a large organization. I work with CI/CD. Now sometimes the organization actually interrupts its services for upgrading the systems - I never do that with my own apps (where I use travis-ci and google appengine). I have ten years uninterrupted service with my own app. Is it alright to name our function "continuous" when we actually interrupt our services?
Yes. The 'Continuous' refers to the automation of the processes rather than zero downtime. Having said that. I would assume that: * If there is significant downtime they wont _want_ to continuously deploy. (it would cause lots of outages) * There is still a manual step somewhere (a fully automated process is usually fast You can imagine a working CD setup with downtime if the downtime is very short and doesn't affect the gross functionality of the overall product
stackexchange-softwareengineering
{ "answer_score": 6, "question_score": 2, "tags": "continuous integration, continuous delivery" }
SSRS Collected Pie Chart - showing orginal percentage I have created a collected pie chart in SSRS 2012. How do I get the child pie to show the original percentage value? In this example, the Child Pie is worth 7% of the original. I want the child pie values to be the original value (such as 2%) and not 33%. ![enter image description here](
Instead of using the value directly in the Values area, convert them to a % first. For example instead of the value set to Sum(Fields!Column.Value) Set it to this Sum(Fields!Column.Value) / Sum(Fields!Column.Value, "DataSet1") (replace "DataSet1" with whatever the parent container's name is) Then in the series label properties, remove the Label data setting and use the Number format to make it a %. Here is a quick example ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "reporting services, charts, pie chart, ssrs 2012" }
How to redirect srv dns to other domain I got a domain and want people to people able to join a server for a game I'm currently running. The server is running by a third party host. For now, I got a direct IP address and port I can connect through, but now I want others to be able to connect to a direct IP address. Now I have read about SRV records but I have only found examples where people want to connect to a server on their own host. Is it possible to make a DNS record so people could connect by only entering `mc.scriptware.org` How would I go and do this? The domain is on Cloudflare and I have tried this: Picture
You can point your hostname to any IP you want. Just create **A** record with your game server IP. You DNS configuration should contain following entry: mc.scriptware.org. A 0.0.0.0 where _0.0.0.0_ is your game server's real IP address. * * * **EDIT:** After some more research I found that minecraft client supports _SRV_ records. You just have to create following DNS record: _minecraft._tcp.mc SRV 0 1 PORT mc.scriptware.org. Where _PORT_ is your server's port number. * * * It also may be good idea to set different name for subdomain that points to server (A record subdomain) eg. _mcsrv.scriptware.org_ instead of _mc.scriptware.org_. Without this game client probably will skip searching for _SRV_ record, because _mc_ subdomain exists and points to an IP address.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "dns, minecraft, srv" }
Planning to use real time streaming video. Alternatives Having a site written under `ASP.NET MVC` framework which alternatvies are there to integrate it with `real-time video streaming`? I've heard about `IIS Smooth Streaming`. Also I've heard that it isn't a good way to use `ASP.NET MVC` here? How this gets resolved in a real world applications? Thanks! **Environment (supposed..)** Windows Server 2008 R2; IIS 7; But maybe it is possible to use some service on crossdomain, I mean on other platform which supports the kind of services..
Why not using simply Vimeo hosting for your videos? < It is not free for commercial purposes, but it is cheap enough and it allows high resolution video. Probably it is cheaper that handling streaming on your IIS if you have not a big big traffic ad sveral several videos.
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": ".net, asp.net mvc, iis, streaming" }
How to get just one of the same record in foreach I have this query to return the categories a user posted in $this['items'] = Advert::with('cats')->where('user_id', $slug)->get(); and in twig i have {% for item in items %} {{ item.cats.cat_title }}<br> {% endfor %} It is returned this way > Agro-Products and Commodity Agro-Products and Commodity Auto Parts and Accessories Agro-Products and Commodity Agro-Products and Commodity Agro-Products and Commodity Agro-Products and Commodity Agro-Products and Commodity Agro-Products and Commodity Men's Clothing Men's Clothing Is there a way to get just one of the same record returned? `first()` does not do it
Try this: $this['items'] = Advert::select('cat_id') ->with('cats') ->groupby('cat_id') ->where('user_id', $slug) ->get(); // replace `cat_id` with the category id column
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, laravel" }
Why am I getting Subquery returns more than 1 row I would like to have the rows that are not being displayed but get an error subquery returns more than 1 row This works fine; SELECT CONCAT( P.LastName, ', ', P.FirstName ) AS Name, ( SELECT MP.MembershipID FROM membershipperson MP WHERE MP.PersonID = P.PersonID ) AS MembershipID, PersonID FROM `person` P This fails when I add the ORDER BY 'MembershipID' it works if I ORDER BY 'PersonID'; SELECT CONCAT( P.LastName, ', ', P.FirstName ) AS Name, ( SELECT MP.MembershipID FROM membershipperson MP WHERE MP.PersonID = P.PersonID ) AS MembershipID, PersonID FROM `person` P ORDER BY `MembershipID` ASC How do I get the list with all the MembershipID rows?
Is it important to use a subquery? You might write it using `INNER JOIN`: SELECT CONCAT( P.LastName, ', ', P.FirstName ) AS Name, MP.MembershipID, P.PersonID FROM `person` P INNER JOIN `membershipperson` MP ON MP.PersonID = P.PersonID ORDER BY MP.MembershipID ASC
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql" }
Replace double/nested for loop over function that returns dataframe with apply in R Consider a function that takes in two input arguments and returns a dataframe: myFun <- function(a, b){ data.frame(aSQ = a^2, bSQ = b^2, SQPROD = a^2*b^2) } myFun(1, 1) A double loop can be constructed over each of the arguments of this function: results <- as.data.frame(matrix(0, nrow = 9, ncol = 3, dimnames = list(c(), c('aSQ', 'bSQ', 'SQPROD')))) for (a in 1:3) for (b in 1:3) results[(a-1)*3+b, ] <- myFun(a, b) How to replace this double loop with an apply construct?
resList <- mapply( myFun, a = rep(1:3, times = 3), b = rep(1:3, each = 3), SIMPLIFY = FALSE ) dplyr::bind_rows(resList)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -5, "tags": "r, loops, for loop, apply, mapply" }
Convert a positive number to negative in C# You can convert a negative number to positive like this: int myInt = System.Math.Abs(-5); Is there an equivalent method to make a positive number negative?
How about myInt = myInt * -1
stackexchange-stackoverflow
{ "answer_score": 551, "question_score": 141, "tags": "c#" }
trigger jquery key event only outside form element Is it possible to trigger a key event only outside a form element? Background: I have a code that loads the next page when the right key is pressed. But I don't want to trigger that event if somebody is using that key in a form element. current code: $(document).keydown(function(e){ if (e.keyCode == 37) { var url = $('a#left').attr("href"); if (url != '') { // require a URL window.location = url; // redirect } return false; } if (e.keyCode == 39) { var url = $('a#right').attr("href"); if (url != '') { // require a URL window.location = url; // redirect } return false; } });
If you have other _fields_ outside your form this might be quite useful I hope `**LIVE DEMO**` document.onkeyup = function( ev ){ var key = ev.which || ev.keyCode , aID = { 37:"left", 39:"right" }; if( ! (/INPUT|TEXTAREA/i.test(ev.target)) && aID[key]) { var url = document.getElementById( aID[key] ).getAttribute('href'); window.location = url; } };
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "javascript, jquery" }
Using variables in SQL SELECT statements and its evaluation SELECT (@row:=@row+1) AS ROW, ID FROM table1 ,(SELECT @row := 0) r order by ID desc How does SQl evaluate this? Strangely, there seems to be little to no literature on this sort of this with variables in the SELECT statement. 1. How can SELECT select row = 0? I thought select had to select an entire column 2. what is the r here? 3. How does the SELECT @row:=@row+1 know how to iterate through the rows? 4. Its not clear to me how the ID is set here. The @row surely correspond somehow to the ROW, but ID seems to be just hanging on 5. Why does the FROM need to take from more than just the table 1?
There is very important "literature" on this: > It is also possible to assign a value to a user variable in statements other than SET. (This functionality is deprecated in MySQL 8.0 and subject to removal in a subsequent release.) In other words, this code is going to stop working at some point in MySQL. The correct way to do what you want is to use `row_number()`: SELECT ROW_NUMBER() OVER (ORDER BY ID DESC) AS ROW, ID FROM table1 ORDER BY ID DESC; The only reason to learn about variable assignment in MySQL `SELECT` statements is historical curiosity -- or if you are stuck maintaining a system that has not yet been migrated to MySQL 8+.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "mysql, sql, database" }
Hide address bar on the called VF page from custom detail page button in salesforce I have a custom button created and i am calling a VF page to open in new window. I have also the window properites set up. I have unchecked the field 'Show Address bar " in "Window properties". But the new page still shows the address bar. Does anyone have the same problem? Or am i doing something wrong? Below are the properties Width (in pixels) 265 Height (in pixels) 300 *Window Position No Preference Resizeable unchecked Show Address Bar unchecked Show Scrollbars unchecked Show Toolbars unchecked Show Menu Bar unchecked Show Status Bar checked
There's a trend for browsers to ignore the address bar setting. I don't think there's anything you can do about it. This Chrome bug has some more explanation.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "salesforce, visualforce" }
Getting handle of current window to GetWindowText? I want to display the Title of the Dialog box: HWND hWnd = ::GetActiveWindow(); char cc[101]; ::GetWindowText(hWnd,cc,100); MessageBox(cc); but the result yields a blank "". not sure what is wrong??
According to MSDN: > Retrieves the window handle to the active window attached to the calling thread's message queue. This means that if the thread which you are calling the function from doesn't own any window, the function will fail. You probably want `GetForegroundWindow` instead.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, visual c++" }
How can my userscript select this link based on the contained image src? I'd like to write a userscript automate a click on a certain image on a web page. The target URL is dynamic, but the image name is fixed. So far I have the following Userscript //--- Note that the contains() text is case-sensitive. var TargetLink = $("a:contains('Click link.jpg')") if (TargetLink && TargetLink.length) window.location.href = TargetLink[0].href Following is an extract of the web page, which I need a user script <a target="_blank" href=" border="0" src=" alt="view Rise of the Guardians" title="view Rise of the Guardians" width="742"></a> PS: alt and title of the image attributes are dynamic. Img SCR is fixed.
1. `:contains()` searches for text; it will not match against the image source. 2. The image source does not contain `Click link.jpg`. It contains `click_link.jpg`. The underscore and correct case are critical. Given that, this code will select the right link: var TargetLink = $("a:has(img[src*='click_link.jpg'])");
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, userscripts" }
Objective-C how to call to outlet? MainGameVC.h @property (strong, nonatomic) IBOutlet UITextView *questionBox; MainGame.VC.m: I am trying to make a function that will change the text of the question box and apply the possible answers to the answer boxes. When I try to declare my function it tells me quesitonBox does not exist unless when I'm in `ViewDidLoad` then I can access it with `_questionBox` but I can't declare a function inside `ViewDidLoad`. How can I declare this function and have the compiler recognize my questionBox outlet? I tried: NSString * question1() { questionBox.text = @"ABC"; } and NSString * question1() { _questionBox.text = @"ABC"; }
You can't access instance variables in a function. You need an instance method: - (void)question1 { self.questionBox.text = @"ABC"; } Also note the use of the property. Don't directly access the instance variable unless you have a good reason to. To call it, use: [self question1];
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, objective c, string, function" }
Managing large number of data in holoviews/hvplot curve and scatter plots Let's say I have a large DataFrame with lots of rows and I want to do a simple line plot of the data using hvplot/holoviews. Example: pd.DataFrame([i for i in range(1000000)]).hvplot() On my machine this plot is slow to be rendered and **very slow** to navigate in with pan, zoom and so on. Is there an option to make the plot lighter to handle, kind of what `datashade` option does for multidimensional plotting? At the moment, on my real data sampling is not an option, I want to keep all of my original data.
Datashader is not limited to multidimensional data, so just add `datashade=True` or `rasterize=True` (which is preferred in most cases, since it lets Bokeh provide colorbars and hover information). ![screenshot](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, plot, holoviews, hvplot" }
How to use CJK ruby for diacritics only Ruby for CJK is designed to put whole words above characters. But I want just the diacritics and not the pinyin spelling. This file \documentclass{article} \usepackage{CJK} \usepackage[overlap, CJK]{ruby} \renewcommand{\rubysize}{1} \begin{document} \Huge \begin{CJK}{UTF8}{gbsn}\ruby{}{\'{}}\ruby{}{\'{}}\ruby{}{\={}}\ruby{}{\'{}}\ruby{}{\u{}}\ruby{}{\'{}} \end{CJK} \end{document} gives pretty good output as shown below. But I would like to get rid of the blank vertical space that was left for the pinyin letters that I do not want shown. Is there a way to lower the tone marks? ![output of code](
You can adjust the size of `\rubysep` (which oddly is a macro and not a length): \documentclass{article} \usepackage{CJK} \usepackage[overlap, CJK]{ruby} \renewcommand{\rubysize}{1} \renewcommand{\rubysep}{-1.5ex} \begin{document} \Huge \begin{CJK}{UTF8}{gbsn}\ruby{}{\'{}}\ruby{}{\'{}}\ruby{}{\={}}\ruby{}{\'{}}\ruby{}{\u{}}\ruby{}{\'{}} \end{CJK} \end{document} ![output of code](
stackexchange-tex
{ "answer_score": 3, "question_score": 4, "tags": "cjk" }
Can I use a digital ring flash with a Nikon film camera? I have two Nikon film cameras (one is an FE2). Is it possible to fire a modern ring flash made for a DLSR with such equipment, or do I need a dedicated unit? I have hot shoe adapters and sync cables, so I have some flexibility with connectivity, but I am guessing they need to be Nikon-compatible. If this is possible, does anyone have any product advice?
A sync cable is a sync cable. If your camera has a PC port that your cable fits and your flash has a PC port that your cable fits then the camera should be able to fire the flash. Of course you will need to control the flash power manually when using a PC connection. If the flash in question doesn't allow for that it probably doesn't have a generic PC port. *PC in the context of flash photography has nothing to do with a personal computer. It is an abbreviation of _Prontor/Compur_. Prontor has its origins in the Italian word _pronto_ (quick) and was a brand of shutter produced by Alfred Gauthier in the 1950s. _Compur_ , derived from the word _compound_ , was the shutter brand of the Deckel Company. Both companies were based in Germany and both counted Zeiss as an influential stockholder when they introduced the standard 1/8"-inch coaxial connector for shutter/flash synchronization.
stackexchange-photo
{ "answer_score": 3, "question_score": 1, "tags": "flash, film, 35mm, ring flash" }
Camcorder pass-through or stand alone capture box for VHS source What would yield better quality: camcorder pass-through or buying a more recent dedicated capture box? I have a Canon Elura 65 that I've used in the past to capture video from VHS sources. It produces 480i AVI files. However, I lost the AV cable. So, should I get a new cable from EBay or buy a dedicated capture box?
This is really going to depend on the quality of your camera and the quality of your VCR. In general, the circuitry that is used to digitize an analog signal has grown by leaps and bounds in the past 10 to 15 years, but also VHS tapes and VCRs produce limited quality to begin with. For maximum quality you will certainly want something with an S-Video input and a VCR deck with an S-video output to maximize quality. As far as the line input goes, I'd probably favor the line input on a high quality camera from the end of the DV era over a cheap USB capture device, but a modern moderate or high quality capture device is going to do much better than even a high end in-camera analog to digital converter. Even cheap USB devices now are most likely better than cheap camcorders or early camcorders in the DV era, but millage will vary depending on the specific device.
stackexchange-avp
{ "answer_score": 2, "question_score": 3, "tags": "video quality, capturing" }
iPhone: Can I get an image picker to have the documents folder as its source It looks like I cant create an album for my picture producing app in the photo library... so what I was going to do is save the images to the documents folder for my app, which I think should be easy enough. The issue though is that the image picker seems to only allow you to pick saved images or photo library as the source, and I would like users to be able to view all images created by my app. Is there a way to make the picker work or will I have to roll my own?
the image picker that apple provides only gives you access to pictures saved in the camera roll. It also gives you the functionality to take a new picture if you are on an iphone. If you save pictures in your app's local storage directory, then you need to build your own mechanism for viewing these photos. You may want to take a look at Joe Hewitt's 320 project \- it has a lot of good controls that you may find useful.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "iphone, cocoa touch" }
Can I check for the existence of an HTTP only cookie with Javascript? Can I use Javascript to see if an HTTP-only cookie _exists_ , I don't want to see the value, just know whether or not it is there. I need this because I have an API using cookie based authentication with servicestack, with a client side SPA. I need to know, client side, whether or not I am authenticated. Is this possible?
No. HTTP-only cookies are not exposed to the JS in any way. That is the _point_ of the HTTP-only flag.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "javascript, authentication, cookies, servicestack, single page application" }
How do I add a custom select field in my pod? I am using Podsframework. I have created a pod called 'media'. Inside my pod I want to add a select field with multiple options(like 'online','offline','press'). So whenever someone is creating a new media he/she will have to select one of these options.I tried using helpers but didn't work.
Why wouldn't you use the relationship field, with the custom simple option? We saw that use case often so we built it into Pods 2.0
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "wordpress, podscms" }
Run a javascript only on the child of the element that triggered it I want to run a javascript only upon the child from the element that triggered it. I have tried to make a research but couldn't find a way to get an answer. I know this might be simple but I am new to java. Here is the fiddle of my problem FIDDLE. What I want is that when I hover on the upper element, only its corresponding rating shows up, not both of them. I have tried with find() without success $('.product-image').hover( function() { $('.product-image').find('.ratings').css('opacity', '1'); }, function() { $('.ratings').css('opacity', '0'); }); Thank you
You can use `event.target` in your method body, which will give the element that triggered the `hover` event. Wrap it in `$()` to have jQuery context available. $('.product-image').hover(function(event){ $(event.target).next('.ratings').css('opacity', '1'); }, function(event){ $(event.target).next('.ratings').css('opacity', '0'); }); Also updated your jsFiddle: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "javascript, jquery, children" }
Runtime of string concatenation checking algorithm I wrote an algorithm to check whether or not a string is a concatenation of any number of strings in an array (while being able to use a string multiple times). I'm having trouble figuring out exactly what the runtime of the algorithm is. I check the string in question against every word in the array and when I find a word that is a substring of the original string starting at index 0, I check the remaining substring against every word in the array as well. So I'm thinking this is an O(n^n), unless I'm missing something. def check_concat(str,substr,words) if substr == "" return false end words.each do |word| if word == substr && str != substr return true end if substr.index(word) == 0 if check_concat(str,substr[word.length..-1],words) return true end end end return false end
Let us assume your main string contains `m words` and there are `n words` in the array to be searched. In the worst case you need to check each word in the main string with each word in the array, which is `mn` time. Thus the time complexity of the function is `O(mn)`. For example the main string be `"Hello Hello Hello Hello Hello"`. The array to be checked contains the following words `'Hai', 'Fine', 'Hello'`. Then the function will require a total of 15 comparisons.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "performance, algorithm, runtime" }
Manuscript Revision: How to include the response to reviewer comments as an attached file? I have recently received a major revision from a journal. In the manuscript upload portal, I find only one place in the form of a text box where I could include the response to reviewer comments. But there is no place link to upload a document. I am thinking of choosing to include the response file as an attachment as it includes mathematical equations. So whether a separate file can be attached to include the response to reviewer comments?
This depends on the editorial management system used by the journal. If they let you attach multiple files, then upload the response to reviewers there (be sure it's clearly labelled as a response to reviewers), and write in the text box "see attached file". If they don't let you attach multiple files, then merge the response to reviewers with the manuscript's PDF, upload that, and write in the text box that you've added the response to reviewers to the manuscript because it contains mathematical equations.
stackexchange-academia
{ "answer_score": 3, "question_score": 1, "tags": "publications, journals, peer review" }
The variable declared but value is never used error I searched in SO and found some similar questions, but they did not solve my problem. I am using `ASP.Net` and here is my code : protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { int _new = 0; // other lines of codes which does not include _new for (int i = 0; i < _Array.Length; i++) { if (_Array[i] == "N" || _Array[i] == "NEW") { _new = 1; } } // other lines of codes which does not include _new } } I get the `The variable declared but value is never used error` warning on int _new = 0; why I am getting this error?
Because you have not done any process on the variable _new, you are only assigning the value to it
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net" }
mongoose model disable remove i want disable remove docs in some doc model. Inside doc pre hook I can do somthing like that: someSchema.pre('remove', function (next) { let err = new Error('Delete docs is not allowed!'); next(err); }); But remove still can be executed by someModel.remove() How I can avoid this?
answer was simple: just override remove fun like this: let model = mongoose.model('doc', someDocSchema); model.remove = function () { throw new Error('Delete docs is not allowed!'); };
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, mongoose" }
Is a Struts 2 Interceptor which puts and pops to Value Stack thread-safe? Consider an interceptor which puts an object in Value Stack, do some logic and then removes it: ActionContext.getContext().getValueStack().set("user", CurrentUser); doSomeLogic(); ActionContext.getContext().getValueStack().pop(); As mentioned in Are Interceptors in Struts2 Thread UNsafe? the interceptors are thread safe, but as we deal with Value Stack in above code, I wonder if this is ok or we should synchronize above code section. As secondary question, is there a better way to remove an element from the Value Stack ?
> As mentioned in Are Interceptors in Struts2 Thread UNsafe? the interceptors are thread safe **Interceptors are _NOT_ thread safe**; in JAVA, however, **the method is**. If you **don't use`static` variables nor instance variables**, everything instantiated inside a method is thread safe, that means that multiple threads accessing that method will access it sequentially, or will access it in a new instance of the containing class. The variables will never get mixed, **and you do not need to synchronize anything**. In addition, the `ValueStack` is stored in the `ActionContext`, that is `ThreadLocal`, and hence definitely Thread-safe. * * * BTW... why not using the Session for this ? :)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "java, multithreading, struts2, thread safety, struts2 interceptors" }
Border-radius: 50% vs. border-radius: 999em While exploring the awesome markup of Medium, found an interesting way to make beautiful pill-styled buttons by using border-radius:999em. However this raised a question: why border-radius:50% makes an oval instead of a pill? Here is a live example: < !Codepen to illustrate border-radius:50% vs. border-radius:999em
The border radius property does all it can to mantain same ratio between the overall radius, when you use `border-radius: 999em`, it keeps the same proportions of the smallest corner. But when you use `border-radius: 50%`, it makes the border set to the proportions of the entire object, assuming x-axis for 50% of the width and y-axis for the 50% of the height of the object, all corners combined make it appear as if the object is circular.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 8, "tags": "html, css" }
Unable to save file to s3 using scala akka-http Trying to save a file to s3. File is coming in as a `Source[ByteString, Any]` so having to convert it to an `InputStream` for the `PutObjectRequest`. Then calculating the `ObjectMetadata` content length and md5. Here's my code followed by the error message. Any input would be appreciated. Thanks. def uploadFile(source: Source[ByteString, _]) = { val stream: InputStream = source.runWith(StreamConverters.asInputStream(FiniteDuration(3, TimeUnit.SECONDS))) val metadata = new ObjectMetadata() metadata.setContentLength(IOUtils.toByteArray(stream).length) metadata.setContentMD5(Base64.encodeBase64(DigestUtils.md5(stream)).toString) s3.putObject(new PutObjectRequest("bucketName", "key", stream, metadata)) } Stack trace error message: `com.amazonaws.services.s3.model.AmazonS3Exception with message The Content-MD5 you specified was invalid.`
A non-blocking, more reactive alternative would be to use Alpakka S3 sink. It would solve all your encoding and S3 protocol issues for you, plus it will be fully backpressure-enabled for an enhanced scalability. Furthermore, it comes in the form of `Sink[ByteString,_]` so it doesn't need further data adaptation/conversion in your case.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "scala, amazon web services, amazon s3, akka, akka http" }
arch linux: sublime text text not alligned vertically so instead of my code being vertically aligned like usual and in any other code text editor it has weird vertical alignment like i am typing in Microsoft Word or something. anyone have an idea what this could be? ps its a fresh install not me messing up some unknown setting ![enter image description here]( **EDIT** : **solution** i forgot to install a default font library during my arch linux install, if you have this problem, do this and restart your X server
forgot to install a default font library during my arch linux install, if you have this problem, do this and restart your X server
stackexchange-superuser
{ "answer_score": 0, "question_score": -1, "tags": "arch linux, sublime text 2" }
Jquery Card Game first-child and clone something wrong Something i haven't been able to figure out. Code for creating 6 cards DOM elements: with two sides: <div class="cards"> <div class="card"> <div class="face front"></div> <div class="face back"></div> </div> Jquery: for(var i=0;i<5;i++){ $(".card:first-child").clone().appendTo("#cards"); } $("#cards").children().each(function(index) { $(this).find(".back").addClass(pattern); The code works fine , BUT It seems i **only** clone the **first child of "card"** ! How come it clones " face .back" element of all the other cards as well and let me aaproach it through jquery , it is not supposed to be cloned. Is it? thanks
You need to amend your selector so that it looks for the first child `.card` element within `.cards`, otherwise it will clone any `.card` element which is the first child of its container - which there will be multiple of after the first addition. Try this: for(var i = 0; i < 5; i++) { $(".cards .card:first-child").clone().appendTo("#cards"); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, html, css" }
How to tell Autotools Build System (Guile 1.8.8) Where Libtool is Installed? I am trying to build Guile 1.8.8 from source. I am stuck at the point where the build system is looking for `libtool`. I have installed it in a non-standard location. I have already built Guile 2.0.11. In 2.0.11 build system, there is an explicit flag to configure `--with-libltdl-prefix`, which I think tells the build system where libtool is installed. For Guile 1.8.8, I have Libtool installed in a non-standard location. How do I tell the build system where it is installed? I am specifically getting error messages like: libguile/Makefile.am:40: Libtool library used but `LIBTOOL' is undefined libguile/Makefile.am:40: The usual way to define `LIBTOOL' is to add `LT_INIT' I think in general this is a question regarding one or more of the autotools and how the build system finds programs / headers / libraries in non-standard locations.
This link is informative: How to point autoconf/automake to non-standard packages * * * 1. Find the directory where *.m4 exists, which corresponds to libtool, or package which is in non-standard location. 2. export ACLOCAL_PATH=/path/to/m4/file 3. cd /path/to/configure.[in,ac] 4. autoreconf -if 5. ./configure
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "gnu, autotools" }
Stuck in starting room in Stanley Parable I started a game of the Stanley Parable, I am in the starting office room. I walked out of the room, walked back into it and started clicking around. The door of the office closed on me and won't open no matter what I do. I have clicked on what seems like every object in the office and yet nothing is happening. What do I do? Is the game broken? Please limit spoilers as much as possible.
There is a bug where sometimes you can go back through a door while it is closing and locking. Try to avoid doing this, but if you get stuck as a result, simply hit Escape and begin the game from the start.
stackexchange-gaming
{ "answer_score": 9, "question_score": 7, "tags": "the stanley parable" }
How to create Laravel model from migration? I found many results how to create migration from a model, but is there any way to create a model from migrations? Basically I want to give a table name, and if there is multiple migration files (one to create and others to update the previous states) the model could be updated. Is there any solution for this?
I'm not sure that there's a good way to create a model directly from migrations, as it depends on what database you use as to the exact structure of your tables. There seems to be a package which support generating the models from your database, however: <
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "laravel, model, laravel 5.8, laravel migrations" }
Why .query() function not working on Django ORM query? As I already know that using `.query.__str__()` , we can get sql equivalent query from Django ORM query. e.g : `Employees.objects.filter(id = int(id)).query.__str__()` Above code working well & I am able to get sql equivalent query but when I am using same on below query I am getting error like below. Employees.objects.filter(id = int(id)).first().query.__str__() AttributeError: 'Employees' object has no attribute 'query' Why now I am getting error, any suggestions ?
[**`.first()`** [Django-doc]]( does _not_ return a `QuerySet`, it returns a model object. The query is evaluated eagerly. You can inspect the last query that Django made with: from django.db import connection print( **connection.queries[-1:]** ) That being said, in essence a `some_queryset.first()` is often the same query as `some_queryset`, except that it will limit the queryset. > **Note** : Please do _not_ use `.__str__`, you can use `str(my_queryset.query)`, or just `print(my_queryset.query)`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "python, django, database" }
If a and b are relatively prime, they must be the first row of an invertible 2x2 matrix Let _a, b_ be non-zero integers. Prove that $a$ and $b$ are relatively prime if and only if they are the first row of a matrix in $\mathrm{GL}_2(\mathbb Z)$: that is, there is a matrix $$A=\begin{bmatrix}a & b\\\c & d\end{bmatrix}$$ in $\mathrm{GL}_2(\mathbb Z)$. This is seems so simple, but I've been stuck on it for quite some time now. It seems to make sense when I look at, as the determinant will need to be 1, since the $\mathrm{gcd}(a, b)$ is obviously 1. And furthermore, since $\mathrm{gcd}(a, b) = 1$ we know there exists a pair of integers, $i, j$, such that $ai + bj = 1$. So $i$ must equal $d$ and $j$ must equal $-c$? I feel like I'm on the right track, I'm just not certain how to finish it off.
You have done (almost) everything already! The matrix you're after is $\begin{pmatrix}a&b\\\\-j&i\end{pmatrix}$, which, as you've shown, has determinant one. I guess the fact that you're missing is this: $$\mathrm{GL}_2(\mathbb Z)= \\{M \in \mathrm{GL}_2(\mathbb R)\cap M_2(\mathbb Z): \det(M)=\pm 1\\}.$$ The proof is simple: $M=\begin{pmatrix}a&b\\\c&d\end{pmatrix}$ has determinant $\pm1$ if and only if $$M^{-1} = \frac{1}{\det(M)}\begin{pmatrix}d&-b\\\\-c&a\end{pmatrix}$$has integer coefficients.
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "abstract algebra, matrices" }
Retaining data after uninstalling the app is there a way to retain some of my data after uninstalling the app and than again installing it on the device. I need to check if my app had been installed on one's device previously or not.
Yeah it's possible if you save App Data in External Storage of your device because that data is not deleted even if your app is uninstalled. Upon reinstalling the app, you can read the file data to determine was the app previously installed or it is a fresh install in case that file doesn't exists. **Note:-** Data in External Directory would be visible to user so it might be a case that user may delete the data from file manager.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "android, information retrieval, data retrieval, data recovery" }
How to use "continue" in groovy's each loop I am new to groovy (worked on java), trying to write some test cases using Spock framework. I need the following Java snippet converted into groovy snippet using "each loop" ## Java Snippet: List<String> myList = Arrays.asList("Hello", "World!", "How", "Are", "You"); for( String myObj : myList){ if(myObj==null) { continue; // need to convert this part in groovy using each loop } System.out.println("My Object is "+ myObj); } Groovy Snippet: def myObj = ["Hello", "World!", "How", "Are", "You"] myList.each{ myObj-> if(myObj==null){ //here I need to continue } println("My Object is " + myObj) }
Either use `return`, as the closure basically is a method that is called with each element as parameter like def myObj = ["Hello", "World!", "How", "Are", "You"] myList.each{ myObj-> if(myObj==null){ return } println("My Object is " + myObj) } Or switch your pattern to def myObj = ["Hello", "World!", "How", "Are", "You"] myList.each{ myObj-> if(myObj!=null){ println("My Object is " + myObj) } } Or use a `findAll` before to filter out `null` objects def myList = ["Hello", "World!", "How", "Are", null, "You"] myList.findAll { it != null }.each{ myObj-> println("My Object is " + myObj) }
stackexchange-stackoverflow
{ "answer_score": 77, "question_score": 47, "tags": "for loop, groovy, each, continue" }
How to convert UnsafePointer<CUnsignedChar> to String? I have tried this method: String.stringWithCString(cString: UnsafePointer<CChar>, encoding: NSStringEncoding) But unfortunately, it only work with `UnsafePointer<CChar>`. And I have no idea about how to convert `UnsafePointer<CUnsignedChar>` to `UnsafePointer<CChar>`.
`struct UnsafePointer<T>` has a constructor that takes an unsafe pointer of a different type as an argument: /// Convert from a UnsafePointer of a different type. /// /// This is a fundamentally unsafe conversion. init<U>(_ from: UnsafePointer<U>) Therefore you can create a string from `ptr : UnsafePointer<CUnsignedChar>` with let str = String.stringWithCString(UnsafePointer(ptr), encoding: someEncoding) or, in the case of UTF-8 encoding, more simply with let str = String.fromCString(UnsafePointer(ptr)) Note that the generic type `<CChar>` is automatically inferred from the context here, i.e. the last line is equivalent to let str = String.fromCString(UnsafePointer<CChar>(ptr))
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "string, swift" }
jQuery UI Modal Dialog Overlay When a jQuery UI modal dialog is displayed everything under the modal window is grayed out - I assume that a partially transparent div covering the entire area of the window is used for this purpose. In the app that I am creating the window has two main areas - the work area and a status bar at the bottom which I use, amongst other things,to show error messages. The problem I have run into is this - if I display error messages from server side interactions initiated by the modal dialog they appear "dull". Is there some way I could keep the semi transparent modal dialog overlay from covering the status bar at the bottom of the window so this does not happen? I'd much appreciate any help.
The modal dialog creates a `div.ui-widget-overlay` that is set with high z-index. You simply have to set the `z-index` of your status bar to more, depending on how you initially create the dialogs.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jquery ui, modal dialog" }
List comprehension using index values How do I turn the below for loop into a list comprehension? I have a list of lists. Each sublist has a number in index 4 position, and I would like to find a way to add them up. The for loop works, but I'd like a one-line solution with list comprehension. frequencies = [] for row in table: frequencies.append(int(row[4])) sum(frequencies) Here's my attempt: frequencies = [sum(i) for i, x in enumerate(table) if x == 4] However, the result is an empty object. In[52]: total Out[52]: []
Do it like this - frequencies = sum([int(row[4]) for row in table]) The approach you're using is a little different from what you want to achieve.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, list, list comprehension" }
If $z$ is any complex number satisfying $|z-2|=1,$ then show that $\sin(\arg z)=\frac{(z-1)(z-3)i}{2|z|(2-z)}$ If $z$ is any complex number satisfying $|z-2|=1,$ then show that $\sin(\arg z)=\frac{(z-1)(z-3)i}{2|z|(2-z)}$ I let $z-2=e^{i\theta}$ because $z-2$ is a unimodular complex number. $z=2+e^{i\theta}$ Argument of $z=\theta$ We need to prove that $\sin\theta=\frac{(z-1)(z-3)i}{2|z|(2-z)}=\frac{(e^{i\theta}-1)(e^{i\theta}+1)i}{-2e^{i\theta}|2+e^{i\theta}|}$ $=\frac{(e^{i\theta}-e^{-i\theta})}{2i|2+e^{i\theta}|}$ Put $e^{i\theta}=\cos\theta+i\sin\theta$ and $e^{-i\theta}=\cos\theta-i\sin\theta$ $=\frac{\sin\theta}{|2+\cos\theta+i\sin\theta|}$ $=\frac{\sin\theta}{\sqrt{(2+\cos\theta)^2+\sin^2\theta}}$ But the denominator does not simplify to $1$.I dont know where have i gone wrong?Can you help me?
$$z=\cos t+2+i\sin t$$ As $(z-1)(z-3)=(z-2)^2-1,$ $$\dfrac{(z-1)(z-3)}{|z|(2-z)}=\dfrac{(\cos t+i\sin t)^2-1}{-(\cos t+i\sin t)\sqrt{(\cos t+2)^2+\sin^2t}}=\dfrac{-2\sin t(\cos t+i\sin t)}{-(\cos t+i\sin t)\sqrt{(\cos t+2)^2+\sin^2t}}=\cdots$$ Can you take it from here?
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "complex numbers" }
gwt-oauth2: auth.login PopUp does not close and callback does no onSuccess I have changed Auth using xauth.setOAuthWindowUrl(" Calling auth.login(req, callback) After accepting the PopUp shows the " instead of being closed. The `Callback` \- `onSuccess` ist not triggered. all based on <
It works not changing Auth to a different redirect like: xauth.setOAuthWindowUrl(" just leave it to " and the window closes correctly and the callback is working as well.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "gwt, oauth 2.0" }
Negative voltage from positive output DC/DC my DC/DC ( < ) has 200 V output on pins +HV and GND. Can I get negative output by simply swithcing the meaning of output pins -> I will use +HV as GND, and GND as +HV. I want to use it only as negative source, so the positive output is unwanted. I used this idea with full wave rectifier -> when you switch the meaning of ouput pins you can get + or - waves, but only one of the option at once. Is this possible with DC/DC? If not, do you know about any DC/DC with negative output around -200 V/10 mA? Ideally ready to use system design. Input voltage around 19 V - 30 V. //edit -> input votlage info -> added info about used DC/DC
This is a typical POL converter without galvanic separation. As long as you prevent any further galvanic connections between your 200V circuit to the primary circuitry, you are fine. After all, polarity is basicly mathematics. But you probably will want connections between different parts of your circuitry. Then you will run into trouble with this POL-converter. You can look up, if there is a fully galvanically separated DC/DC converter with your spec, or a POL-converter with negative output.
stackexchange-electronics
{ "answer_score": 1, "question_score": 1, "tags": "dc dc converter, inverter, high voltage" }
Page.PreviousPage.FindControl is NULL I am accessing Test.aspx through two different pages. Something like this: **Page1.aspx -------> Test.aspx <\-------- Page2.aspx** I am testing this in IE7 where `Request.UrlReferrer.AbsoluteUri` is not working. In IE 8+ it works. Nothing I tried is working so far and its driving me **nuts**. I also tried putting a hidden textbox in Page1.aspx so that I can see if the control textbox is available, if it is then I know I am coming from Page1 or else Page2. This code is not working: var hidden = Page.PreviousPage.FindControl("tbhidden"); 'tbhidden' is this: `<asp:textbox ID="tbhidden" runat="server" visible = "false"/>` How would you crack this problem?
Normally the UrlReferrer will be blank for the first page bought up when a browser is started? You can only use the Page.PreviousPage object if you are doing a server side redirect using the Server.Transfer command **Breaking the problem down** If you are using anchors to get to the test page then add a parameter to it in page1 and 2 <a href="test.aspx?from=page1 ...> and pick it up in the test page using Request.QueryString["from"] If you are using a post then amend the form action in page1 and 2 <form action="test.aspx?from=page1 ...> This will double check that you are coming from the correct page. **Another** good tip is to download the tool called "Fiddler", it intercepts the website posts and gives a nicely formatted breakdown of all the referral values and page requests that occur.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, visual studio, visual studio 2010, c# 4.0" }
PostgreSQL: 2+ clients, unique constraint -> race condition I am interested, what is best practice to avoid that small problem :) Lets take 2 clients, both trying to insert rows in the table with unique constraint. Suppose, that it is "url" column. At one time there may appear the following situation: 1) Client A looks, is there url "a" in the table 2) Client A gets answer, that there is no that url 3) Client A is going to insert url "a" 4) Client B looks, is there url "a" in the table 5) Client B gets answer, that there is no that url 6) Client A inserted url "a" 7) Client B is going to insert url "a", but gets duplicate key error **Do I understand right, that the best way to avoid it - just make retries on application level?**
You can avoid the error with explicit locks taken out at the start of a transaction, but that can be bad for concurrency and throughput. < If you don't block concurrent attempts, you need to deal with retries one way or another. Rather than putting that logic in the application code, you can encapsulate it within a function. The logic would be similar to the merge_db() example: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "postgresql, unique, race condition" }
Loop program output I got curious and experimented a little on looping and I kind of confused myself here. Question 1: Why does this code output 012345678910 instead of 00000000000111111111112222222222233333333333444444444445555555555566666666666777 7777777788888888888999999999991010101010101010101010 ? for(a=0;a<=10;a++){ for(a=0;a<=10;a++){ printf("%d", a); } } Question 2: For the code shown below, does taking out the first statement mean that it would start on 0? If yes, then why does it output 12345678910 instead of 01234567891001234567891001234567891001234567891001234567891001234567891001234567 8910012345678910012345678910012345678910012345678910 ? for(a=0;a<=10;a++){ for(;b<=10;b++){ printf("%d", b); } }
1. Because when `a` reaches 10 in the inner loop, the outer loop also exits, so you only see 012345678910 2. Because after the 1st time the outer loop is executed, `b` is already 11 and the inner loop is no longer executed. For your desired output, you should reset `b` to zero every time the outer loop is executed for (...) { for (b = 0; ... ; ...) {...} // ^~~~~ This is what you should do }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -7, "tags": "c, loops" }
Cookie или localStorage? Что лучше использовать для сохранения статуса о админе, Cookie или LocalStorage? Мне нужно надежное хранилище и на регулируемый промежуток времени
прочтите тут думаю тут более упрощенный ответ на ваш вопрос. <
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "cookie, localstorage" }
Comparison of "location" object in javascript I want to know how "location"(window.location) object is compared in javascript i.e. which values are taken into consideration while comparing two "location" objects. Suppose i have top.location = "< and self.location = "< If i compare them as (top.location == self.location), it gives false. Whereas, if i compare them as (top.location.href == self.location.href), it will gives true. Can anyone explain why this happens? Thanks in advance.
`top.location` and `self.location` are Location objects. Objects in JavaScript can't be directly compared using `==` or `===`, which is why `top.location != self.location`. Since `top.location.href` and `self.location.href` are conventional strings, they can be compared as usual using `==` or, better, `===`.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, window.location" }
Как задать стиль объекту унаследованному от Button? Есть класс: public class GLine : Button { public int x, y; Game game; public GLine(int x, int y) { this.x = x; this.y = y; Grid.SetRow(this, y); Grid.SetColumn(this, x); DataContextChanged += GLine_DataContextChanged; } private void GLine_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { game = (Game)DataContext; Click += game.PlayerClick; } } Как задать объекту этого класса стиль, описанный в разметке UserControl'a, в который этот объект помещается? TargetType = "Button" - не работает.
Просто укажите наименование класса, ну и не забудьте про пространство имен XAML, например: <Style TargetType="local:GLine" ...
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, wpf" }
How to make whole table cell clickable but vertical align text inside it - CSS How to make whole table cell clickable but vertical align text inside it. Alright it is achievable by making link display:block and setting line height. But the problem is text may get 2 lines some times. So this way is not solution. Are there any other solution ? thank you.
You could do this by adding a class to the cell you want to click and hooking this up using jquery such as <td class="clickable">...</td> your jquery... $('.clickable').click(function() { alert('Table cell has been clicked'); });
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "html, css, vertical alignment" }
creating objects with new vs. {} in javascript There are two ways of creating an object in javascript: 1. use new on a "constructor function" 2. return a dictionary {} and set the proper key/value pairs The first is, for example FooType = function() { this.hello = function() { alert("hello"); }; }; foo = new FooType(); foo.hello(); the second is fooFactory = function() { return { hello : function() { alert("hello"); } }; }; foo = fooFactory(); foo.hello(); (Code written for the post. not guaranteed correct) Apart from risks of mistakes of having this bound to the global object, are these two method totally equivalent (also considering prototype inheritance etc...)?
They're not equivalent, especially when considering prototype inheritance. FooType = function() { this.hello = function() { alert("hello"); }; }; var foo = new FooType(); FooType.prototype.bye = function() { alert('bye!'); }; foo.bye(); // "bye!" The only way you could achieve that in the fooFactory way would be to add it to the `object` prototype which is a Very Bad Idea. The first method is much more meaningful in my opinion (since the object has a type you can check against) and can offer much better performance if the prototype is done properly. In your first example, every time you instantiate a new `FooType` object, it create a new "hello" function. If you have lots of these objects, that's a lot of wasted memory. Consider using this instead: function FooType() { } FooType.prototype.hello = function() { alert('Hello'); };
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "javascript" }
Can "alight" be used to mean "light"? Usually, the verb _(to) alight_ can be used to express: * Landing somewhere * Disembarking a vehicle But since you can also _set something alight_ , I've been wondering if someone would light my cigar if I told him, "please alight." In other words, does the `a-` prefix bear a constructive or destructive meaning?
The OED attests to several verb meanings of _alight_ that have fallen out of common usage (marked _rare_ ): > 1. _trans._ To shed light on; to illuminate, enlighten ( _lit._ and _fig._ ). > >> 1999 D. Tobin _Passage to Center_ 301: Such repose alights the face of The Tollund Man and Gunnar. > > 2. _trans._ To set light to; to light, ignite. Also _fig._ > >> 2009 S. Akhter _Faith & Philos. Islam_ vi. 89: The Holy Quran is an extraordinary pearl... Every fruit of good luck is found in it and every torch is alighted from it. > > I would not use them in modern communication except for deliberate literary effect. The etymology of this verb use of _alight_ is treated as uncertain, but it may be a reduction of the obsolete _onlight_ , which also means to shed light upon or to cause to shine. The OED further suggests that the adjective/adverb use of _alight_ derived from the verb and was later reinterpreted by analogy to _afire_ and _aflame_.
stackexchange-english
{ "answer_score": 3, "question_score": 1, "tags": "meaning, semantics, prefixes" }
How can I remove connections in Visual Studio "Copy Web Site" tool? Visual Studio 2008 has a Copy Web Site tool that remembers previous FTP locations that files have been copied to. There is a "Connections" drop down where they are listed. I'd like to remove some old listings from that, but I can't find where they're stored. I've looked at the solution file, and there's nothing there. John
Check <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "visual studio 2008" }
How to create a Raster from a pixel float array in Java? I'm trying to take a BufferedImage, apply a Fourier transform (using jtransforms), and write the data back to the BufferedImage. But I'm stuck creating a new Raster to set the results back, am I missing something here? BufferedImage bitmap; float [] bitfloat = null; bitmap = ImageIO.read(new File("filename")); FloatDCT_2D dct = new FloatDCT_2D(bitmap.getWidth(),bitmap.getHeight()); bitfloat = bitmap.getData().getPixels(0, 0, bitmap.getWidth(), bitmap.getHeight(), bitfloat); dct.forward(bitfloat, false); But I'm stumped trying to finish off this line, what should I give the createRaster function? The javadocs for createRaster make little sense to me: bitmap.setData(Raster.createRaster(`arg1`, `arg2`, `arg3`)); I'm starting to wonder if a float array is even necessary, but there aren't many examples of jtransforms out there.
Don't create a new `Raster`. Use [`WritableRaster.setPixels(int,int,int,int,float[])`]( to write the array back to the image. final int w = bitmap.getWidth(); final int h = bitmap.getHeight(); final WritableRaster wr = bitmap.getData(); bitfloat = wr.getPixels(0, 0, w, h, bitfloat); // do processing here wr.setPixels(0, 0, w, h, bitfloat); Note also that if you're planning to display this image, you should really copy it to a screen-compatible type; ImageIO seldom returns those.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "java, bufferedimage, raster" }
Module load/unload cycle when debugging Delphi application Sometimes when running application under Delphi 2009 debugger, as soon as I do anything with the application form (click, move..) Delphi starts to flood Event Log with following messages (similar): Module Load: UNKNOWN_MODULE_59954.No DebugInfo. Base Address: $02D90000. Process MyApp.exe (5584) Module Unload: UNKNOWN_MODULE_59954. Process MyApp.exe (5584) Number of UNKNOWN_MODULE increases for each cycle, so at example there have been almost 60000 module load/unloads. Application remains unresponsive during this flood. Sometimes I have to just terminate the application to be able to continue. Any idea how to start tracking the cause of this?
As "Arioch 'The" suggested - download and run Sysinternal's process explorer. * From the View menu choose "Lower pane -> DLLs (Ctrl+D)" * Mark your process in the process tree * Right click lower pane's header and choose "Add Columns". * From the DLL tab choose "Base Address". * Sort modules on that column * Find your dll's base address - you will get it's name :) If the module is unloading too fast - set "Options > Difference Highlight Duration" to 9 sec. In my case it was odbcint.dll: !procMon - find unknown module Also give your PC a virus scan - just in case :)
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "delphi, debugging" }
hide cells border using css I want to hide border of cell of a table . !enter image description here How to do it using css ? As it shows, I need to hide the marked borders (as in third and second rows).
<style> table { border: 1px solid black; width:100%; } table tr { border: 1px solid black; } table th { border: none; } </style> <table> <thead> <tr> <th class="col1">1</th> <th class="col2">2</th> <th class="col3">3</th> </tr> </thead> </thead> See here: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "css, border" }
why is my implementation so slow? (#26 of 99 haskell problems) when solving question 26 (" Generate the combinations of K distinct objects chosen from the N elements of a list" ) i came up with the following implementation: combi :: Int -> [a] -> [[a]] combi 0 _ = [[]] combi n ys@(x:xs) = [ y:xs' | y <- ys, xs' <- combi (n-1) xs ] one of the solutions suggested is : combinations :: Int -> [a] -> [[a]] combinations 0 _ = [ [] ] combinations n xs = [ y:ys | y:xs' <- tails xs , ys <- combinations (n-1) xs'] while somewhat similar, the solution provided runs significantly faster than mine. why?
1. Your solution is incorrect. E.g. `combi 2 [1,2]` is `[[1,2], [2,2]]` instead of `[[1,2]]`. 2. Your recursive case always calculates `combi (n-1) xs`, where `length xs == length ys - 1`. In the correct solution, length of `xs'` decreases with every step. This may seem like a small difference, but recursion compounds it.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "haskell, optimization, combinations" }
Removing characters using preg_replace function I use preg_replace function. I want the function not to remove apostrophe ( **'** ) character. So I want it to return the word as (o'clock) . How can I do that? $last_word = "o'clock."; $new_word= preg_replace('/[^a-zA-Z0-9 ]/','',$last_word); echo $new_word;
Try: $last_word = "o'clock."; $new_word= preg_replace('/[^a-zA-Z0-9\' ]/','',$last_word); echo $new_word; Demo here: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, preg replace" }
What is the problem name for Traveling salesman problem(TSP) without considering going back to starting point? I would like to know what is the problem name for TSP w/o considering the way of going back to starting point and what is the algorithm to solve this. I looked into Shortest path problem but that is not what I am looking for, the problem only find the shortest path from 2 assigned points. But what I am looking for is the problem which we give n points and inputting only 1 starting point. Then, find the shortest path traveling all points exactly once. (end point can be any point.) I also looked into Hamiltonian path problem but it seems not to solve my defined problem but rather find whether there is Hamiltonian path or not.
I've found the answer to my question in this book. It is the same with Computer wiring problem which occurs repeatedly in the design of computers and other digital systems. The purpose is to minimize the total wire length. So, it is indeed a minimum length Hamiltonian path. What the book suggests is to create a dummy point whose distances to every other points is 0. Therefore, the problem becomes an (n+1)-city symmetric TSP. After solving, just delete dummy point and then the minimum length Hamiltonian path is solved and we can get the TSP path without returning back the start point.
stackexchange-stackoverflow
{ "answer_score": 41, "question_score": 44, "tags": "algorithm, graph algorithm, traveling salesman, np hard" }
Arc parameter equation So, I have the function $y=-x^2+3$, and I'm to generate the parametric equation for the arc that is above $y=x$. I got from $-x^2+3>x$ to $\frac{1-\sqrt{13}}{-2}<x<\frac{1+\sqrt{13}}{-2}$, but I'm not sure how to proceed from here.
Now use the parametrization $(x, -x^2+3)$, and you are done.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "parametric" }
Iterate and call methods inside array-like objects I've got this object-structure and would like to iterate over all direct child objects of `obj` and call their `myMethod` method. While `for...in` iterates over them correctly I always get this error `o.myMethod is not a function` Here is a JSFiddle obj = { test1: { "name": "test1string", "myMethod": function(){ console.log("test 1 method called") } }, test2: { "name": "test2string", "myMethod": function(){ console.log("test 2 method called") } } }; for (var o in obj) { console.log(o.name()); o.myMethod(); } **How can I achieve the wanted behaviour?**
This happens because `o` in your `for` loop corresponds to keys and not to values. To get the value use square-bracket notation: `obj[o].myMethod();`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "javascript" }
Flutter - how to call multiple builder items in material app? class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( builder: BotToastInit(), //1. call BotToastInit navigatorObservers: [BotToastNavigatorObserver()], debugShowCheckedModeBanner: false, title: 'Pak Coins', theme: ThemeData( primarySwatch: Colors.blue, ), home: MySplashScreen(), ); } } this is my MyApp Class where want to call 2 builder 1. BotToastInit(), 2. EasyLoading.init() how i call both of this? builder: //here ,
The `builder` parameter must return one widget. If you like to do initialization or return two widgets, you've to nest them yourself inside the `builder`: builder: (context, child) { // do your initialization here child = EasyLoading.init(); // assuming this is returning a widget child = botToastBuilder(context,child); return child; } if you look at the getting started guide of bot_toast package, they've an example at step 3. **Update:** Or utilize the builder methods provided by BotToast or EasyLoading such as: builder: EasyLoading.init(builder: BotToastInit()),
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 9, "tags": "flutter, material design, builder" }
How do I show that for linearly independent set in dual is a dual of a linearly independent set? Related: How do I prove that a bilinear map is symmetric in the given condition? Let $X$ be a Banach space over $\mathbb{R}$ and $X^*$ be the dual of $X$. Let $\lambda_1,....\lambda_n$ be linearly independent elements in $X^*$. Then, how do I prove that there are linearly independent elements $x_1,...,x_n$ in $X$ such that $\lambda_i(x_j)=\delta_{ij}$?
Linear independence of such elements $x_j$ is automatic, since if $\sum c_jx_j=0$ then for all $i$ $0=\lambda_i(\sum c_jx_j)=c_i$. For existence, consider the map $\Lambda:X\to\mathbb{R}^n$ given by $\Lambda(x)=(\lambda_1(x),\dots,\lambda_n(x))$. If $\Lambda$ were not surjective, there would be a nonzero functional $f:\mathbb{R}^n\to\mathbb{R}$ which vanishes on the image of $\Lambda$. Such an $f$ would have the form $(a_1,\dots,a_n)\mapsto \sum c_ja_j$ for some $c_j\in\mathbb{R}$, and the fact that $f$ vanishes on the image of $\Lambda$ says exactly that $\sum c_j\lambda_j=0$. Since the $\lambda_j$ are linearly independent, this can't happen unless $c_j=0$ for all $j$, i.e. $f=0$. Thus $\Lambda$ is surjective. In particular, there exist $x_j\in X$ whose images under $\Lambda$ are the standard basis vectors of $\mathbb{R}^n$. This means exactly that $\lambda_i(x_j)=\delta_{ij}$.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "functional analysis, banach spaces" }
Why are finite unions of algebraic sets algebraic? Suppose $F,G$ are polynomials in $k[x_1,\cdots, x_n]$ (k is a field). Let $$V(F) = \\{ (a_1,\cdots,a_n)\in k^n : F(a_1,\cdots,a_n)=0 \\}.$$ Then $V(F)\cup V(G) = V(FG),$ essentially because integral domains don't have zero divisors. What I'm having trouble seeing is $$ V(I)\cup V(J) =\\{ (a_1,\cdots, a_n)\in k^n: F(a_1,\cdots,a_n)G(a_1,\cdots,a_n)=0 \ \ \ \forall F\in I, \ \ G\in J\\}.$$ The same argument as in the simpler case doesn't seem to apply since if $x$ is a point in the RHS, then it could make $FG$ always vanish by sometimes making $F$ vanish but not $G$ for some $F,G$, and other times making $G$ vanish but not $F$ for some other $F,G.$ Can someone help me see why the equation is true? EDIT: More specifically, I can see why the LHS is a subset of the RHS, but not the reverse.
Suppose that $x\in V(I)\cup V(J)$. Then it is either in $V(I)$ or $V(J)$; let's say it is in $V(I)$. Thus, $F(x)=0$ for all $F\in I$, and hence, for all $F\in I$ and $G\in J$, we have that $F(x)G(x)=0$. The same reasoning applies if we assumed $x$ was in $V(J)$. Thus, $$V(I)\cup V(J)\subseteq\\{x\in k^n\mid F(x)G(x)=0\text{ for all }F\in I,G\in J\\}.$$ Conversely, let's suppose that the point $x$ satisfies $F(x)G(x)=0$ for all $F\in I$ and $G\in J$. If it is the case that $F(x)=0$ for all $F\in I$, then by definition, we have $x\in V(I)$, and hence $x\in V(I)\cup V(J)$. So, now let's suppose that there were some $F_0\in I$ such that $F_0(x)\neq 0$. Then for any $G\in J$, since we assumed that $F_0(x)G(x)=0$ and we are working over a field, we must have $G(x)=0$. Thus, $x\in V(J)$, and hence $x\in V(I)\cup V(J)$.
stackexchange-math
{ "answer_score": 12, "question_score": 9, "tags": "algebraic geometry, algebraic curves" }
how to reset wamp server password I've put the password in the main phpmyadmin and not one of the databases. How can I even access it if can't even have the chance to input the password.
Take a look at reseting the MySQL root password here. UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root'; FLUSH PRIVILEGES;
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "wampserver" }
adding datetime into excel sheets using xls I was using the library datetime and xlwt i wanted to create a sheet name and i want to add the date and time is has been created so i used the following lines. sheet1 = wb.add_sheet('applied job list'+datetime.now()) it throwed an error saying File "d:/PROJECTS/job_apply_bot/aasda.py", line 5, in <module> sheet1 = wb.add_sheet('applied job list'+datetime.now()) TypeError: can only concatenate str (not "datetime.datetime") to str idk what i am missing can someone help
Looks like your returning an object with datetime.now() try converting it to a string first like this, `sheet1 = wb.add_sheet('applied job list' + str(datetime.now()))`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, datetime, xlwt" }
Is feather edge bad? ![enter image description here]( Currently learning about aircraft piston engine. Feather edge can be found at the engine valves as according to the picture. Can someone explain briefly about what is feather edge? Why it is bad? Which part of the engine that has the feather edge?
As noted here > A thin edge is called a feather edge and can lead to preignition; the valve edge would burn away in a short period of time, and the cylinder would have to be overhauled again. Basically during a rebuild over-grinding the valves can lead to a feathered edge which in turn can lead to higher/faster engine wear. Essentially by grinding the edge to thin you cause the limited remaining metal to wear out much faster. This can also lead to valve seating issues and out right leaks.
stackexchange-aviation
{ "answer_score": 4, "question_score": 5, "tags": "engine, piston engine" }
How to start an activity I have created two classes: `Example1` and `Example2`, which extends activity. `Example1` contains a UI of buttons, while Example2 contains UI of TextEdit. I want to call Example2 when a button is clicked, so this code is in an `onclick` method Intent i = new Intent(); i.setClassName("com.a.ui", "com.a.ui.Example2"); startActivity(i); So I am able to get the UI of Example2 successfully. What's an alternate way of calling intent? Is there any alternate way to start an activity?
you can call like this: startActivity(new Intent(com.a.ui.this, com.a.ui.Example2.class));
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android, android intent" }
Can't use liveData or viewModelScope.launch I'm trying to use these two builders for coroutines in my app, but in my ViewModel I can't import them or they do not pop up. These are my dependencies: implementation "androidx.lifecycle:lifecycle-extensions:2.2.0-rc02" implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2' and in my ViewModel class MainViewModel(): ViewModel() { init{ viewModelScope ----> does not work , marked in red val data = liveData {} ----> does not work, marked in red } } I rebuilt, cleaned, and restarted with invalidating cache, but I can't use them
Add the ViewModel ktx lib: implementation "androidx.lifecycle:lifecycle-viewmodel-ktx$lifecycle_version" Available after AndroidX lifecycle v2.1.0
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 8, "tags": "android, kotlin, mvvm, kotlin coroutines" }
android layout form activity i am having an xml main.xml,which has few layouts <LinearLayout xmlns:android=" android:id="@+id/mainl" android:tag="aa" android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="fill_parent"> </LinearLayout> Is it possible to add one more layout inside the `LinearLayout` from the Activity at Run time. I am able to create Layout in Activity(without using xml) ,but problem in adding this layout to xml at run time ,anyone has a solution
You won't add it to the XML at run-time, but you can add it to the layout, which I think is what you want to do. parent.addView(child);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android" }
Javascript - Remove values from array - Constructing an array of times I am having an issue figuring this out. The idea is that I have an array of values that I'm considering times, and I need to remove all values that overlap with a specific time: `var availableTimes = ['0 - 0.5', '0.5 - 1', '1 - 1.5', '1.5 -2', '2 - 2.5', '2.5 -3']` `var timeToRemove = '0.5 - 2'` I have full control over what the array looks like, but that's the idea. I can't figure out how to construct my array of available times and my `timeToRemove` so that I can accomplish this. I am using a 24:00 hour clock, so `1 - 1.5` is 1:00 AM to 1:30 AM. Any thoughts on the best way to construct this?
I would prefer a OO way to do it: (1) Construct an array with objects with following structure: { StartTime:[fload], EndTime:[fload] } So your time array looks like this var availableTimes= [ {StartTime:0,EndTime:0.5}, {...} ]; (2) The time to be removed has the same structure: var timeToRemove = '0.5 - 2'; => var timeToRemove={StartTime:0.5,EndTime:2}; (3) Delete algorithm looks like this: for (var i=0;i<availableTimes.length;i++) { if(availableTimes[i].StartTime > timeToRemove.StartTime && availableTimes[i].EndTime < timeToRemove.EndTime) availableTimes[i]=null; //perform deletion }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "javascript, arrays" }
Criteria Morphia MongoDB I have a collection like this: { "_id": { "$oid": "53f34ef8ec10d6fa97dcc34b" }, "editions": [ { "number": 1, ... }, { "number": 2, ... }, ... ] } I want filter results of my query by some number. I tried criterias.add(query.criteria("editions.number").equal(paramNumber)); And query.filter("editions.number =", paramNumber) However I just received all collection, when I pass paramNumber equals 2. What I want is receive the following result: { "_id": { "$oid": "53f34ef8ec10d6fa97dcc34b" }, "editions": [ { "number": 2, ... } ] } What am I doing wrong?
You can't receive partial arrays like that. You'll get back with the full document/object or just the fields you've specified in a projection.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mongodb, mongodb query, morphia" }
Shell complains 'cannot execute binary file' I've playing around with linux and noticed that for some mysterious reason commands like '/bin/sh ' just will not work. Each time I'm trying to start a process it yields 'cannot execute binary file' error message. m@sanctuary:~$ sh sed /bin/sed: /bin/sed: cannot execute binary file When I first launch sh and try to execute sed, it succeeds. I'm starting to lose my wits. It would be just great, if somebody could help me. Thank you.
"sed" isn't a shell script, so you don't execute it with sh. Just type `sed ...args...` not `sh sed ...args...`
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "linux, shell" }
C++ STL std::random_shuffle cannot pass custom random number generator I want to random_shuffle a vector (I know that random_shuffle is depreciated), but I get a compile error when I pass my custom random function which I copied from another thread on here. Can someone show me how to call random_shuffle using the random number generator posted below? random_shuffle(defects.begin(), defects.end(), xorshf96); static unsigned int x=123456789, y=362436069, z=521288629; unsigned int xorshf96(void) { //period 2^96-1 unsigned int t; x ^= x << 16; x ^= x >> 5; x ^= x << 1; t = x; x = y; y = z; z = t ^ x ^ y; return z; }
`xorshf96` does not meet the requirements of the `RandomFunc` argument to `std::random_shuffle`: > `r` \- function object returning a randomly chosen value of type convertible to `std::iterator_traits<RandomIt>::difference_type` in the interval `0,n)` if invoked as `r(n)` It must take an argument and return a random number less than it. The function is in implementation of the [Knuth Shuffle and that is how that algorithm works. As a sample fix, you could provide: unsigned int xorshf96_fixed(int n) { return xorshf96() % n; } random_shuffle(defects.begin(), defects.end(), xorshf96_fixed);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c++, random, stl" }
Difference between formula and algorithm What is the difference between the terms formula and algorithm in mathematics? I haven't seen the definition of formula anywhere. I know that algorithm means that Turing machine halts for every input. Is for example $$x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}$$ formula or algorithm as $\pm$ means you can choose which sign you use? Are there any formulas that are not algorithms or algorithms that are not formulas?
An algorithm is in its most general definition: a way of achieving a desired goal. Formula are merely recipes or components. Example: The actual method of baking bread with steps is an algorithm: 1. get ingredients 2. mix ingredients 3. put in oven 4. cook until certain time at certain temperature 5. take out and wait till cools in here would be formula such as the formula for the bread, what ingredients etc... The quadratic formula is just that: a formula for solving quadratic equations An example of an algorithm for solving quadratics would be: 1. get quadratic: call a the coefficient in front of x^2, b the coefficient in front of x and c the constant coefficient. 2. evaluate quadratic formula (both + and - versions) on given a, b and c 3. simplify This algorithm solves the actual problem... whereas the formula is a tool used in the process.
stackexchange-math
{ "answer_score": 12, "question_score": 15, "tags": "algorithms, notation, terminology" }