text
stringlengths
64
89.7k
meta
dict
Q: Why am I getting ZERO as the output in Android Calculator Application? I am making a calculator app in the android studio but I am always getting the result as zero when I am clicking = operator. Kindly help me resolve the error. The code is as follows: public class MainActivity extends AppCompatActivity { Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnAdd, btnSub, btnMul, btnDivide, btnEquals, btnPercentage, btnClear, btnErase, btnPoint; EditText etDisplay; int num = 0, result = 0; int operator; public static final int ADD = 0; public static final int SUBTRACT = 1; public static final int MULIPLY = 2; public static final int DIVIDE = 3; public static final int PERCENTAGE = 4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etDisplay = (EditText) findViewById(R.id.etDisplay); btn0 = (Button) findViewById(R.id.btn0); btn1 = (Button) findViewById(R.id.btn1); btn2 = (Button) findViewById(R.id.btn2); btn3 = (Button) findViewById(R.id.btn3); btn4 = (Button) findViewById(R.id.btn4); btn5 = (Button) findViewById(R.id.btn5); btn6 = (Button) findViewById(R.id.btn6); btn7 = (Button) findViewById(R.id.btn7); btn8 = (Button) findViewById(R.id.btn8); btn9 = (Button) findViewById(R.id.btn9); btnAdd = (Button) findViewById(R.id.btnAdd); btnSub = (Button) findViewById(R.id.btnSub); btnMul = (Button) findViewById(R.id.btnMul); btnDivide = (Button) findViewById(R.id.btnDivide); btnEquals = (Button) findViewById(R.id.btnEquals); btnPercentage = (Button) findViewById(R.id.btnPercentage); btnClear = (Button) findViewById(R.id.btnClear); btnClear.setOnClickListener(new View.OnClickListener() { /****btnClear is used to clear the contents of EditText****/ @Override public void onClick(View v) { etDisplay.setText(""); num = 0; result = 0; } }); btn0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { num = num * 10; etDisplay.setText(""); etDisplay.setText(String.valueOf(num)); } }); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { num = (num * 10) + 1; etDisplay.setText(""); etDisplay.setText(String.valueOf(num)); } }); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { num = (num * 10) + 2; etDisplay.setText(""); etDisplay.setText(String.valueOf(num)); } }); btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { num = (num * 10) + 3; etDisplay.setText(""); etDisplay.setText(String.valueOf(num)); } }); /SIMILARLY FOR OTHER BUTTONS/ btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*...*/ } }); btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*...*/ } }); btn6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*...*/ } }); btn7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*...*/ } }); btn8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*...*/ } }); btn9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*...*/ } }); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { operator = ADD; result = num; num = 0; } }); /SIMILARLY FOR btnSub, btnMul, btnDivide, btnPercentage/ btnSub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*...*/ } }); btnMul.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*...*/ } }); btnDivide.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*...*/ } }); btnPercentage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*...*/ } }); btnEquals.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (operator){ case ADD : result = result + num; case SUBTRACT : result = result - num; case MULIPLY : result = result * num; case DIVIDE : result = result / num; case PERCENTAGE : result = result / 100; } try { etDisplay.setText(String.valueOf(result)); } catch (ArithmeticException e){ etDisplay.setText(""); } finally { num = 0; result = 0; } } }); } } A: you need to add break in your switch otherwise all cases will be executed case ADD : result = result + num; break; case SUBTRACT : result = result - num; break; case MULIPLY : result = result * num; break; case DIVIDE : result = result / num; break; case PERCENTAGE : result = result / 100; Seems like you are trying with small numbers where / 100 is giving you value less than 1 and the integer division will give you 0 , truncate the rest of the value
{ "pile_set_name": "StackExchange" }
Q: Displaying an image in PHP from MYSQL? I am trying to display an image using php. The image is stored in MYSQL table. I am able to retrieve the information from mysql in my php code, but i am having trouble displaying the image. $db_link = mysql_connect($host_name, $user_name, $password) or die("Could not connect to $host_name"); mysql_select_db("gameportal") or die("Could not select database $db_name"); $query = "select * from gamesinfo;"; $result = mysql_query($query, $db_link) or die("Could not select"); $Row = mysql_fetch_row($result); echo "$Row[0]<br>"; echo "$Row[1]<br>"; echo "<img src="$Row[7]" class="body" alt="" /> <br>";//image echo "$Row[5]<br>"; Row 7 contains the location of the image (in this case a weblink). When i try to display the webpage, the page is blank, nothing shows, but when i remove that line with the pic, the webpage shows with the remaining info. What am i doing wrong? A: This is the culprit: echo "<img src="$Row[7]" class="body" alt="" /> <br>"; You use unquoted double quotes inside double quotes ;-). Try echo "<img src='$Row[7]' class='body' alt='' /> <br>"; EDIT The point is not the double quotes inside double quotes, but unquoted double quotes inside double quotes - this should work as well: echo "<img src=\"$Row[7]\" class=\"body\" alt=\"\" /> <br>";
{ "pile_set_name": "StackExchange" }
Q: DocuSign SDK Assembly Dependency Versions I am integrating the DocuSign SDK into my application (from the github page here: https://github.com/docusign/docusign-csharp-client) and can see it has two dependencies: - Netwtonsoft.JSON - RestSharp However, it seems the included dependency assemblies are not the same versions that were used to create the DocuSign SDK assembly. The included NewtonSoft.JSON assembly is v8, but the SDK uses v7. The included RestSharp assembly is 105.2.3, but the SDK uses v105.1.0.0 Is it possible to get an updated SDK with the correct dependencies? A: Dependencies For the DocuSign Nuget package 2.1.4 Newtonsoft.Json (>= 8.0.3) RestSharpSigned (>= 105.2.2) Source code is also referring to the same versions. See here
{ "pile_set_name": "StackExchange" }
Q: How to sync repo in bitbucket to Visual studio team service? I am very new to VSTS platform. In one of my project, I am trying to integrate the bitbucket source control to VSTS. By this way I should be able to see the updates made on bitbucket onto the VSTS account. I have tried creating build on VSTS, but that only shows the commits history of the selected repository of bitbucket. Is there a way to manage all the bitbucket changes on VSTS as source control? A: To sync changes from bitbucket repo to VSTS git repo automatically, you can achieve it by using a VSTS build definition. Detail steps as below: 1. Create a build definition with Bitbucket repo When creating a VSTS build definition -> Select the Bitbucket repo you want to sync -> create. 2. Enable continuous integration In the build definition -> Triggers Tab -> Enable continuous integration -> Include all branches with *. 3. Add PowerShell task with the script to sync bitbucket repo with VSTS git repo Add a PowerShell task with below script: if ( $(git remote) -contains 'vsts' ) {git remote rm vsts echo 'remove remote vsts' } $branch="$(Build.SourceBranch)".replace("refs/heads/","") git remote add vsts https://Personal%20Access%20Token:[email protected]/project/_git/repo git checkout $branch git push vsts $branch -f For the detail steps to add and config the PowerShell task as below: Edit your build definition -> Click + to add a task for your agent phase -> Search powershell task -> click Add -> click the PowerShell task you added -> select Inline type -> then add your powershell script in the Script option -> Save build definition. Now no matter which branch is updated in your bitbucket repo, VSTS git repo will be synced automatically. Yo sync changes from VSTS git repo to bitbucket repo, you can create another CI build to achieve it. Detail steps as below: 1. Create a CI build with VSTS git repo 2. Enable continuous integration 3. Add a PowerShell task with below aspects if ( $(git remote) -contains 'bitbucket' ) {git remote rm bitbucket echo 'remove remote bitbucket' } git remote add bitbucket https://username:[email protected]/username/repo.git $branch="$(Build.SourceBranch)".replace("refs/heads/","") git checkout $branch git push bitbucket $branch -f
{ "pile_set_name": "StackExchange" }
Q: How to resolve pathspec not matching any file known to git when checking out a single, deleted file? I have a branch feature that has come off of develop and is ahead of it. A combination of stash pops and merge develops have resulted in a commit that includes a rm for particular file. I'm trying to undo this delete by checking out the file from the commit before this delete with: name@machine ~/path/inside/the/repo/to/the/parent/dir $ git checkout megalongshaofthecommitthatdeletedthefile^ -- filename.ext but get error: pathspec 'filename.ext' did not match any file(s) know to git. I've tried checking out files that haven't been deleted, but git is still refusing to check out the undeleted file. How can I tell git where to get this file? A: How can I tell git where to get this file? What can be done? use git reflog and checkout the previous commit before the changes if you need to. reflog is the full history of your repository which allow you to go back to any desired point in time git log --follow <file> will display the commits where the file was modified (last change will be the first one) This command will display all the log entries for the given file so you can grab the required commit and take the file form there using git checkout SHA-1 file_path git bisect to search in which commit the file was removed. Bisect is the way to search for "bugs" and or changes made to the repository use it to track when the file was deleted. you can write script that search if the file exists and run it with the git bisect --run... flag Once you have the desired SHA-1 use git revert SHA-1 to "undo" the changes made in the given commit. I assume you want to do it in a new branch to be safe. If you need only the file and not the rest of the changes: git checkout SHA-1 -- file_path A: The solution to the pathspec issue is specifiying the parent directory, relative to the directory bash is looking at, rather than just the filename, because git is not necessarily running in the same directory that bash is "on". Assuming git is running at C:/Program Files (x86)/Git/ name@machine ~/path/inside/the/repo/to/the/parent/dir $ git checkout megalongshaofthecommitthatdeletedthefile^ -- filename.ext will look for C:/Program Files (x86)/Git/filename.ext. Instead, run: name@machine ~/path/inside/the/repo/to/the/parent/dir $ git checkout megalongshaofthecommitthatdeletedthefile^ -- ../dir/filename.ext which will look for C:/repodir/path/inside/the/repo/to/the/parent/dir/filename.ext
{ "pile_set_name": "StackExchange" }
Q: Get position in class hierarchy Is the a way to get the number of ancestors for an instance of class? E.g. a class of type UITouch would be of level 2 as it inherits from NSObject. A: int level = 1; Class cls = [UITouch class]; while (cls = [cls superclass]) ++ level; return level;
{ "pile_set_name": "StackExchange" }
Q: Email delegation Google Apps for Business With email delegation in Google Apps for Business, is it possible to use an external email client like Outlook, Mac Mail etc. to access the emails? I.e. an assistant using Mac Mail would be able to access the boss’s emails? A: Since Gmail delegation is thought for Google Apps it makes sense to use it with Google Apps' Gmail. Once the delegate is signed into their own own Gmail account, they can then access the other person's account from the account selection menu at the top of Gmail. Also the mentioned restrictions on the delegations prohibits setting up an email client: You won't be able to give anyone permission to change your account password or account settings, or chat on your behalf. But an alternative to using just any client might be possible using the Google Apps Sync for Microsoft Outlook®:
{ "pile_set_name": "StackExchange" }
Q: NullReferenceException at PropertyChanged Event (Prism 6.3) I'm using Prism 6.3 to build a simple cloud client with seafile. After the user logs in, I navigate to a sidebar in a side region (SidebarRegion). OnNavigatedTo are the libraries loaded in a collection and displayed. When the selected library changes, I navigate to a new ItemsView instance (ContentRegion) and load the items (from the library) so they can also be displayed. If now clicked on an item, I navigate to another side region to display detailed information about the item. public SeafDirEntry SelectedItem { get { return _selectedItem; } set { if (!SetProperty(ref _selectedItem, value) || value == null) return; var parameter = new NavigationParameters {{ "item", _selectedItem }}; _regionManager.RequestNavigate(_regionNames.InfoBarRegion, new Uri("ItemInfoView", UriKind.Relative), parameter); } } There's also a delete button, which is hooked to a command which deletes the item Now, after the item/file is deleted from the server, I hooked up the PubSubEvent to reload the items from the library with the RefreshItemsAsync() method. After the items collection is overwritten, the PropertyChangedevent throws a NullReferenceException, even if I try this: public ObservableCollection<SeafDirEntry> Items { get { return _items; } set { if (value == _items) return; _items = value; RaisePropertyChanged(); // <- throws here // SetProperty(ref _items, value); <- same result } } I tried also to remove the item from the collection with the item as payload of the PubSubEvent, but it also throws an NullReferenceException at _items.Remove(itemFromPayload). Even if I refresh the collection manually by a button, same result. The ItemsViewModel gets only created once per library and resists even after switching between them, so the reference should exists. What did I miss out here? A: AFAICT _items is not initialised unless you navigate to it with "valid" data, which is loaded asynchronously. So _items could be "null" well after the page has been displayed (at which point the XAML would presumably try to use a collection which is null). Consider instead the approach of always initialising it to an empty collection, and then populating that collection (on the correct thread) with the data you want displayed. That's how ObservableCollections are meant to work.
{ "pile_set_name": "StackExchange" }
Q: How to wait until an element exists for dojo? In dojo, is there a way to get notified when an element of certain class (or contain certain text) has been created? There is an almost exactly the same question asked in here for jQuery. But I'd like to know if there is a similar solution for dojo. Thank you! A: For dojo 1.7, based on the JQuery answer, I would do : require(["dojo/on", "dojo/_base/array"], function(on, array){ on(dojo.doc, "DOMNodeInserted", function(evt){ var classes = dojo.attr(evt.target, "class").split(" "); if (array.indexOf(classes, "myclass") > -1) { console.debug("Inserted node with class myclass", evt.target); } }); });
{ "pile_set_name": "StackExchange" }
Q: Перевод уведомления «непонятна суть вопроса» Привет! Я модератор дружественного сайта «Русский язык», пришедший на эту замечательную Мету с мирным предложением: программисты — особая каста, с собственными понятиями, со своим жаргоном и т. д., и т. п. Так случилось, что нашим сайтам приходится пользоваться одним и тем же переводом. Из-за этого некоторые выражения, уместные в среде программистов, выглядят вычурно для простых людей-непрограммистов. Один из показательных примеров — текст уведомления, прикрепляемого к вопросу при закрытии по причине «непонятна суть вопроса». В нем содержатся: словосочетание «воспроизводить проблему» («как её воспроизвести»), носящее специальный характер, и неуместные для вопросов по русскому языку «что вы хотите получить в результате» и «приведите пример кода». Поскольку здесь куда больше переводчиков, чем на Мете РЯ, предлагаю найти компромисс. Полные тексты: Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. Постарайтесь писать более развернутые вопросы. Для получения ответа поясните, в чём именно вы видите проблему, как её воспроизвести, что вы хотите получить в результате и т. д. Приведите пример кода. A: Мне кажется, что правильное решение проблемы — это завести разные переводы для разных сайтов. Разумеется, «воспроизводить проблему» нужно программистам, т. к. наш подсайт и создан для вопросов в формате «проблема — решение». Я не знаю, как именно решают вопрос другие сайты, ведь у нас много разных сайтов и на английском языке. Возможно, имеет смысл позаимствовать решение оттуда. Возможно, предложенное решение — долгосрочное, и в короткие сроки не реализуемо. Тем не менее, имеет смысл иметь разные переводы и, возможно, разные наборы причин закрытия. Пример: «Проблема вызвана опечаткой в исходном коде автора вопроса» — причина закрытия, очевидно, релевантная только для программистов. Обновление: Николас сообщил в чате, что англоязычные сайты используют одну и ту же формулировку. Так что к сожалению это решение не будет реализовано в ближайшем будущем. Так что всё же нужно придумывать формулировку, подходящую всем сайтам. A: Думаю, что нам не нужно держаться за формулировки «приведите пример кода» и «воспроизведение проблемы». Как недавно обсуждалось, не в каждом вопросе должен быть пример кода. Много отличных вопросов можно задать без единой строчки кода. Если вопросу не хватает именно кода для воспроизведения проблемы, то нужно использовать другую причину закрытия: MCVE (минимальный достаточный пример, воспроизводящий проблему). Если вопросу не хватает смысла или формулировки желаемого результата, то нужно использовать причину «непонятна суть вопроса». Но тогда в ней не должно быть требования кода! Выводы: Отсутствие возможности написать уникальный для каждого сайта текст в данной причине не является проблемой. Проблема в том, что вместо MVCE мы пытаемся использовать другую причину, для этого не предназначенную. Решение: давайте использовать обе причины: «непонятно, что вы спрашиваете» и MCVE — по назначению.
{ "pile_set_name": "StackExchange" }
Q: Customs and baggage when transferring in Schengen and going outside I am flying from Prague through Frankfurt to Toronto. Do I need to go through customs in Frankfurt and will my baggage go directly onto the next plane? A: (I didn't manage to find the duplicate, so I'll try to make a summary answer.) It all depends on two big aspects: Do you have one ticket (with transfer) or two separate tickets? To which country do you fly? If you have one ticket with transfer, then you should get checked in for both flights in Prague. I recommend to arrive the advised 2 hours before departure so that you manage to sort out things nicely. If you get checked in for both flights, then your luggage will make it on its own, and you just move yourself to the correct terminal/gate in Frankfurt. (Check your luggage receipt to ensure it did though! It has to show the code YYZ for Toronto rather than FRA for Frankfurt.) You will pass the passport control (Schengen exit) in Frankfurt (in Prague T2, it's just a brief control and you can even use your ID for that one). It can happen that they don't issue the boarding pass for Frankfurt. Ask the clerk then if the luggage gets checked-in to Toronto or not, and read the next section carefully. If you have two separate tickets you can still try to get checked in for the flight Frankfurt--Toronto in Prague, but the chances of success are low. (May work if both airlines are in the same alliance, and none of them are low cost carriers, but you'll need to ask nicely at check-in.) Then, you'll have to get your luggage in Frankfurt like if you were terminating there, move (with your luggage) and go the departure terminal at the airport and check-in yourself and your luggage like someone who starts there. Remember that this may take quite some time. This paragraph applies if your luggage wasn't checked in to Toronto in Prague, too. If your luggage was checked to Toronto in Prague, but your boarding pass wasn't issued (this can happen in very extra-ordinary cases), you just proceed to a transfer desk in Frankfurt, which will issue your boarding pass to Toronto. If you travel to a country which does a detailed check (USA knows to issue these sometimes, only to change their mind couple minds later, Israel is another such one, and there are surely more, but it all changes every couple months or so), then it can happen that they want to inspect your luggage before loading it on the overseas flight. I would recommend asking for the procedures on the airlines' hotline in advance, they ought to know the procedures. For the customs: If you have any goods to declare on leaving (like an apparatus worth €1M that you plan to take back home), you better do that in Prague. You should be able to do it in Frankfurt too (since most stuff can travel between CZ and DE without any problem), but it's better to solve this stuff as soon as possible. I better don't give more advice since it's impossible to answer that in general.
{ "pile_set_name": "StackExchange" }
Q: Filter records in bootstrap table with preset and selectable value I have a regular bootstrap table. For some reasons I need a filter just for one field with preset value, so when table is shown, records must be filtered. But also, this value must be selectable from some list (like regular html select). And records must be filtered just by picking value, not by clicking some submit button. I have already pursued this filter extension, but couldn't find out how to use it to satisfy all my requirements. I'd appreciate any help. Of course, the best way - show it with an example. A: Suppose you have a select dropdown with id "filter" and a html table with id "records", you can have this code show only the table rows that contain the selected value in the dropdown. $("#filter").change(function(){ $("#records > tr").hide(); $("#records > tr > td:contains('"+$(this).val()+"')").parent("tr").show(); });
{ "pile_set_name": "StackExchange" }
Q: Is there a way to recover crashed Choregraphe projects? I am working with Choregraphe and I recently connected two boxes causing my computer to crash. I had to hard restart the computer and now I am unable to access the project. Anytime I try to open it in choregraphe the application just crashes back to desktop. Other projects are unaffected. I am very very new to Choregraphe and I have not found many resources documenting this problem and how to recover from it. I figured there may be some brilliant minds here with suggestions for how to move forward. I have tried to open all of the various project files in regular vim to see if there was something I could hotfix on my own to no avail. I have tried to search through the troubleshooting documents for Choregraphe but have had no luck finding documentation relating to this type of issue. UPDATE: I have figured out that my Behavior.xar file had been overwritten during the crash. It is now an empty file, and this is why Choregraphe will not open the project. Does anyone know of a Way to recover this file? A: If you already upload it in your robot using the play button you can recover it in the .lastuploaded behavior folder in /home/nao/.local/apps/PackageManager...
{ "pile_set_name": "StackExchange" }
Q: What is this CJK app and why is it on my phone? I was going through my apps and discovered this: Um, what? Unfortunately, I'm not fluent in the language that the app is titled with (Chinese, I'm guessing?), so I have no idea what it is or where it came from. Any ideas? I tend to be careful with what I download (no third-party markets) so I would be surprised if it was malware, but that being said it still looks mighty suspicious to me. It's a Galaxy Nexus running Android 4.3 if that's relevant. A: It looks like it's Google's Pinyin IME. The icon has since changed to use squares instead of circles, but you can still see that it is generally the same, and you can find examples of the old round icon on the Internet still. It's still on the page for Google's Windows variant, in fact: Google must evidently ship this in their vanilla Android builds for Nexus devices, which would explain why it cannot be uninstalled. This seems to be verified by various sites around the web (one, two, three).
{ "pile_set_name": "StackExchange" }
Q: MySQL performing slower on 'ORDER BY id DESC LIMIT 100' compared to order with timestamp Let's take following scenario. We have SELECT id FROM table WHERE name='name' ORDER BY id DESC LIMIT 100 and the exact same query with LIMIT 5. The LIMIT 100 query takes about 0.2s and the LIMIT 5 takes 0.008s. (With even higher LIMIT of 1000 execution time rises to 2s!) Now we use timestamp instead of id. We have SELECT id FROM table WHERE name='name' ORDER BY timestamp DESC LIMIT 100 and again the exact same query with LIMIT 5. The LIMIT 100 query takes about 0.4s and the LIMIT 5 takes also 0.4s. (Higher LIMIT of 1000 doesn't affect execution time much. The table is build as following. The id is the primary key and auto_increment is active. The table has 500.000 rows. There are 100 different names which doesn't change. Every 10 min we insert into our table all the names with their recent updates (with timestamps). That means our table looks as following: +-----+-------+---------------------+--+--+ | id | name | timestamp | | | +-----+-------+---------------------+--+--+ | 1 | mark | 2019-03-31 09:00:02 | | | +-----+-------+---------------------+--+--+ | 2 | peter | 2019-03-31 09:00:02 | | | +-----+-------+---------------------+--+--+ | 3 | john | 2019-03-31 09:00:02 | | | +-----+-------+---------------------+--+--+ | ... | ... | ... | | | +-----+-------+---------------------+--+--+ | 101 | mark | 2019-03-31 09:10:02 | | | +-----+-------+---------------------+--+--+ | 102 | peter | 2019-03-31 09:10:02 | | | +-----+-------+---------------------+--+--+ | 103 | john | 2019-03-31 09:10:02 | | | +-----+-------+---------------------+--+--+ So after the query with name='mark' it should look like this: +-----+------+---------------------+--+--+ | id | name | timestamp | | | +-----+------+---------------------+--+--+ | 501 | mark | 2019-03-31 09:50:02 | | | +-----+------+---------------------+--+--+ | 401 | mark | 2019-03-31 09:40:02 | | | +-----+------+---------------------+--+--+ | 301 | mark | 2019-03-31 09:30:02 | | | +-----+------+---------------------+--+--+ | 201 | mark | 2019-03-31 09:20:02 | | | +-----+------+---------------------+--+--+ | 101 | mark | 2019-03-31 09:10:02 | | | +-----+------+---------------------+--+--+ | 1 | mark | 2019-03-31 09:00:02 | | | +-----+------+---------------------+--+--+ | ... | ... | ... | | | +-----+------+---------------------+--+--+ My question now is, why does order by id DESC performs so much slower with high LIMIT (Limit 1000 is over 2s), compared to the exact same query but ordered by timestamp DESC (Limit 1000 is around 0.4s). I tried to alter the table and add index to id, but that changed nothing. Does the problem lies in the gaps between id's? (501,401,301...). After three days of googling and trying different queries nothing changed, and my question on this strange behaviour is not answered yet. Explain query with id: +----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+ | 1 | SIMPLE | name | index | NULL | PRIMARY | 4 | NULL | 1000 | Using where | +----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+ And the explain query with timestamp: +----+-------------+-------+------+---------------+------+---------+------+--------+-----------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+------+---------+------+--------+-----------------------------+ | 1 | SIMPLE | name | ALL | NULL | NULL | NULL | NULL | 500000 | Using where; Using filesort | +----+-------------+-------+------+---------------+------+---------+------+--------+-----------------------------+ @niklaz the id type is int(10) @scaisEdge Table Schema: +-----------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | +-----------+------------------+------+-----+---------+----------------+ | name | varchar(10) | NO | | NULL | | +-----------+------------------+------+-----+---------+----------------+ | timestamp | timestamp | NO | | NULL | | +-----------+------------------+------+-----+---------+----------------+ A: the gap is not related to the content of the column ID .. You should try adding composite redundant index on your table create index idx1 on my_table(name, id) Could be the gap is related to cached value .. try perform the query in separated sessions.
{ "pile_set_name": "StackExchange" }
Q: How to know the user who created a specific item in Django? Is it possible to get the id of the user who created a specific item, no matter what it, in Django? I have a site where when the users are authenticated can access a form and submit a new item. Can I retrieve who created what without adding an extra 'submitted by' Event.objects.filter(owner=self.kwargs['pk']) (which gives me name 'self' is not defined )? A: You cannot access the information without adding a new field, but you can have a look at this library django-audit-log for easy tracking. It will add created_by and modified_by fields and maintain them.
{ "pile_set_name": "StackExchange" }
Q: Array Processing logic correction I have an array [1,2,4,5,1,7,8,9,2,3] and i would like it to generate all subset which sum of values are less than 10 current result [[1,2,4],[5,1],[7],[8],[9],[2,3]] expected result [[4,5,1],[9,1],[8,2],[3,7],[1,2]] that is what i did var a = [1,2,4,5,1,7,8,9,2,3], tempArr = []; tempSum = 0, result = []; for (var i = 0;i< a.length; i += 1 ) { tempSum+=a[i]; tempArr.push(a[i]); if((tempSum+a[i+1])>10) { result.push(tempArr); tempSum = 0; tempArr = []; } else if (i == a.length-1 && tempArr.length > 0) { // if array is [1,2,3] result.push(tempArr); } } but it gives me [[1,2,4],[5,1],[7],[8],[9],[2,3]] and it has 6 subset, but i expect to get [[4,5,1],[9,1],[8,2],[3,7],[1,2]] which has 5 subset. A: Below logic is in JavaScript :- var limit = 10; var arr = [1,2,4,5,1,7,8,9,2,3]; arr.sort(); var ans = new Array ( ); while(arr.length >0){ var ts = arr[arr.length-1]; arr.splice(arr.length-1 , 1); var ta= new Array ( ); ta.push(ts); var x = arr.length-1; while(x>=0){ if(ts + arr[x] <= limit){ ts = ts + arr[x]; ta.push(arr[x]); arr.splice(x , 1); } x= x-1; } ans.push(JSON.stringify(ta)); } alert(ans); It is Giving Output as required . [9,1],[8,2],[7,3],[5,4,1],[2]
{ "pile_set_name": "StackExchange" }
Q: Does dual-boot negatively affect performance? I only have one hard disk and Windows 7 is currently installed on it. I'm considering dual-boot but I was wondering: Will having Ubuntu and Windows at the same time with only one HDD affect my PC's performance? A: Setting up a dual boot does not affect the performance of a computer as only one operating system is running at a time. Thus, they get access to all of the computers resources. The only system spec which is affected is HDD space (not HDD speed) as the drive has been divided between the operating systems, thus, they only have access to the space allocated to them.
{ "pile_set_name": "StackExchange" }
Q: Parse Json array response in scala\Play There is a web service returning array of something {"apps": [{"name": "one"}, {"name": "two"}]} In my code I want to iterate every name val request = WS.url(s"http://localhost:9000/getData") val json = request.get.map { response => (response.json \ "apps" \\ "name") } json.foreach(println) However all my attempts return single record // Expect one two // Actual ListBuffer("one", "two") A: First of all, the neat solution here would be: val request = WS.url(s"http://localhost:9000/getData") request.get.map { response => val names = (response.json \ "apps" \\ "name") names.foreach(println) } Secondly, if you don't want to get confused about the types, you should change your naming standards. For a Future object, you may start with the prefix future, for an Option, it could start with maybe, etc. If you do so, the problem in your example will be more obvious: val request = WS.url(s"http://localhost:9000/getData") val futureJson = request.get.map { response => (response.json \ "apps" \\ "name") } futureJson.foreach(println) // you call foreach for a Future, not for a List Thirdly, why would Future trait have a method called foreach? I think that's confusing for beginners and even mid-level developers. We know from other languages that, foreach means iterate over a list of objects. In Scala, it is considered part of "Monadic operations" which is still a gray area for me :), but the comment for Future.foreach in Scala source is this: /** Asynchronously processes the value in the future once the value becomes available. * * Will not be called if the future fails. */ def foreach[U]
{ "pile_set_name": "StackExchange" }
Q: Get artist name and song name by YouTube code On my website, people are able to drop their YouTube code link Like faXwJ9TfX9g How do I get the name of the artist and name of the song, with a simple Javascript. Input : faXwJ9TfX9g by User Output : Name of artist Output : Name of the Song Output : Length of the Song Best regards, Simon Buijs Zwaag Netherlands A: Youtube videos don't have tags for artist and song title (like mp3 files do, for example). So, AFAIK the best you can do is get the video title. You could go further and parse it to get the artist and song name, but I don't think this is something you'd want to do. Using the Data API here's what you can do: <html> <head> <script type="text/javascript"> function processData(data) { var title = data.entry.title.$t; var duration = data.entry.media$group.media$content[0].duration; } </script> </head> <body> <script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/faXwJ9TfX9g?alt=json-in-script&callback=processData"> </script> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Error npm install [email protected] Ubuntu 12.04.4 x64 When I try to deploy my meteor app with PORT=3000 MONGO_URL=mongodb://<user>:<password>@oceanic.mongohq.com:<port>/<db_name>node bundle/main.js I get the following error Error: Cannot find module 'fibers' When I try to install the fibers module with the commands stated on the meteor website cd bundle/programs/server/node_modules rm -r fibers npm install [email protected] I get the following errors rm: cannot remove `fibers': No such file or directory and then npm http GET https://registry.npmjs.org/fibers npm http 304 https://registry.npmjs.org/fibers > [email protected] install /root/mt_5/bundle/programs/server/node_modules/fibers > node ./build.js make: Entering directory `/root/mt_5/bundle/programs/server/node_modules/fibers/build' CXX(target) Release/obj.target/fibers/src/fibers.o ../src/fibers.cc:222:34: error: ‘Arguments’ does not name a type ../src/fibers.cc:222:45: error: ISO C++ forbids declaration of ‘args’ with no type [-fpermissive] ../src/fibers.cc:241:34: error: ‘Arguments’ does not name a type ../src/fibers.cc:241:45: error: ISO C++ forbids declaration of ‘args’ with no type [-fpermissive] ../src/fibers.cc:279:40: error: ‘Arguments’ does not name a type ../src/fibers.cc:279:51: error: ISO C++ forbids declaration of ‘args’ with no type [-fpermissive] ../src/fibers.cc:300:36: error: ‘Arguments’ does not name a type ../src/fibers.cc:300:47: error: ISO C++ forbids declaration of ‘args’ with no type [-fpermissive] ../src/fibers.cc:468:37: error: ‘Arguments’ does not name a type ../src/fibers.cc:468:48: error: ISO C++ forbids declaration of ‘args’ with no type [-fpermissive] ../src/fibers.cc:510:65: error: ‘AccessorInfo’ does not name a type ../src/fibers.cc:510:79: error: ISO C++ forbids declaration of ‘info’ with no type [-fpermissive] ../src/fibers.cc:518:65: error: ‘AccessorInfo’ does not name a type ../src/fibers.cc:518:79: error: ISO C++ forbids declaration of ‘info’ with no type [-fpermissive] ../src/fibers.cc:529:66: error: ‘AccessorInfo’ does not name a type ../src/fibers.cc:529:80: error: ISO C++ forbids declaration of ‘info’ with no type [-fpermissive] ../src/fibers.cc:533:77: error: ‘AccessorInfo’ does not name a type ../src/fibers.cc:533:91: error: ISO C++ forbids declaration of ‘info’ with no type [-fpermissive] ../src/fibers.cc:540:71: error: ‘AccessorInfo’ does not name a type ../src/fibers.cc:540:85: error: ISO C++ forbids declaration of ‘info’ with no type [-fpermissive] ../src/fibers.cc: In static member function ‘static void Fiber::DestroyOrphans()’: ../src/fibers.cc:202:41: error: no matching function for call to ‘v8::String::Utf8Value::Utf8Value(v8::Persistent<v8::Value, v8::NonCopyablePersistentTraits<v8::Value> >&)’ ../src/fibers.cc:202:41: note: candidates are: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:1861:5: note: v8::String::Utf8Value::Utf8Value(const v8::String::Utf8Value&) /root/.node-gyp/0.11.12/deps/v8/include/v8.h:1861:5: note: no known conversion for argument 1 from ‘v8::Persistent<v8::Value, v8::NonCopyablePersistentTraits<v8::Value> >’ to ‘const v8::String::Utf8Value&’ /root/.node-gyp/0.11.12/deps/v8/include/v8.h:1851:14: note: v8::String::Utf8Value::Utf8Value(v8::Handle<v8::Value>) /root/.node-gyp/0.11.12/deps/v8/include/v8.h:1851:14: note: no known conversion for argument 1 from ‘v8::Persistent<v8::Value, v8::NonCopyablePersistentTraits<v8::Value> >’ to ‘v8::Handle<v8::Value>’ ../src/fibers.cc: In static member function ‘static v8::Handle<v8::Value> Fiber::New(const int&)’: ../src/fibers.cc:223:13: error: request for member ‘Length’ in ‘args’, which is of non-class type ‘const int’ ../src/fibers.cc:225:22: error: invalid types ‘const int[int]’ for array subscript ../src/fibers.cc:227:21: error: request for member ‘IsConstructCall’ in ‘args’, which is of non-class type ‘const int’ ../src/fibers.cc:228:37: error: invalid types ‘const int[int]’ for array subscript ../src/fibers.cc:229:16: error: base operand of ‘->’ has non-pointer type ‘v8::Persistent<v8::FunctionTemplate, v8::NonCopyablePersistentTraits<v8::FunctionTemplate> >’ ../src/fibers.cc:232:55: error: invalid types ‘const int[int]’ for array subscript ../src/fibers.cc:233:19: error: request for member ‘This’ in ‘args’, which is of non-class type ‘const int’ ../src/fibers.cc:234:16: error: request for member ‘This’ in ‘args’, which is of non-class type ‘const int’ ../src/fibers.cc: In static member function ‘static v8::Handle<v8::Value> Fiber::Run(const int&)’: ../src/fibers.cc:242:30: error: request for member ‘Holder’ in ‘args’, which is of non-class type ‘const int’ ../src/fibers.cc:249:20: error: request for member ‘Length’ in ‘args’, which is of non-class type ‘const int’ ../src/fibers.cc:266:14: error: request for member ‘Length’ in ‘args’, which is of non-class type ‘const int’ ../src/fibers.cc:267:50: error: invalid types ‘const int[int]’ for array subscript ../src/fibers.cc: In static member function ‘static v8::Handle<v8::Value> Fiber::ThrowInto(const int&)’: ../src/fibers.cc:280:30: error: request for member ‘Holder’ in ‘args’, which is of non-class type ‘const int’ ../src/fibers.cc:284:20: error: request for member ‘Length’ in ‘args’, which is of non-class type ‘const int’ ../src/fibers.cc:286:20: error: request for member ‘Length’ in ‘args’, which is of non-class type ‘const int’ ../src/fibers.cc:287:49: error: invalid types ‘const int[int]’ for array subscript ../src/fibers.cc: In static member function ‘static v8::Handle<v8::Value> Fiber::Reset(const int&)’: ../src/fibers.cc:301:30: error: request for member ‘Holder’ in ‘args’, which is of non-class type ‘const int’ ../src/fibers.cc:307:20: error: request for member ‘Length’ in ‘args’, which is of non-class type ‘const int’ ../src/fibers.cc:316:29: error: conversion from ‘v8::Persistent<v8::Value, v8::NonCopyablePersistentTraits<v8::Value> >’ to non-scalar type ‘v8::Handle<v8::Value>’ requested ../src/fibers.cc: In member function ‘v8::Handle<v8::Value> Fiber::ReturnYielded()’: ../src/fibers.cc:383:24: error: conversion from ‘v8::Persistent<v8::Value, v8::NonCopyablePersistentTraits<v8::Value> >’ to non-scalar type ‘v8::Handle<v8::Value>’ requested ../src/fibers.cc: In static member function ‘static void Fiber::RunFiber(void**)’: ../src/fibers.cc:396:10: error: ‘Arguments’ does not name a type /root/.node-gyp/0.11.12/deps/v8/include/v8.h:768:13: error: ‘v8::HandleScope::HandleScope()’ is private ../src/fibers.cc:406:17: error: within this context ../src/fibers.cc:418:20: error: base operand of ‘->’ has non-pointer type ‘v8::Persistent<v8::Context>’ ../src/fibers.cc:425:9: error: ‘args’ was not declared in this scope ../src/fibers.cc:427:23: error: base operand of ‘->’ has non-pointer type ‘v8::Persistent<v8::Function, v8::NonCopyablePersistentTraits<v8::Function> >’ ../src/fibers.cc:427:45: error: base operand of ‘->’ has non-pointer type ‘v8::Persistent<v8::Context>’ ../src/fibers.cc:429:23: error: base operand of ‘->’ has non-pointer type ‘v8::Persistent<v8::Function, v8::NonCopyablePersistentTraits<v8::Function> >’ ../src/fibers.cc:429:45: error: base operand of ‘->’ has non-pointer type ‘v8::Persistent<v8::Context>’ ../src/fibers.cc:455:20: error: base operand of ‘->’ has non-pointer type ‘v8::Persistent<v8::Context>’ ../src/fibers.cc: In static member function ‘static v8::Handle<v8::Value> ../src/fibers.cc:587:60: error: invalid conversion from ‘v8::Handle<v8::Value> (*)(v8::Local<v8::String>, const int&)’ to ‘v8::AccessorGetterCallback {aka void (*)(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>&)}’ [-fpermissive] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:2098:8: error: initializing argument 2 of ‘bool v8::Object::SetAccessor(v8::Handle<v8::String>, v8::AccessorGetterCallback, v8::AccessorSetterCallback, v8::Handle<v8::Value>, v8::AccessControl, v8::PropertyAttribute)’ [-fpermissive] ../src/fibers.cc:588:75: error: invalid conversion from ‘v8::Handle<v8::Value> (*)(v8::Local<v8::String>, const int&)’ to ‘v8::AccessorGetterCallback {aka void (*)(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>&)}’ [-fpermissive] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:2098:8: error: initializing argument 2 of ‘bool v8::Object::SetAccessor(v8::Handle<v8::String>, v8::AccessorGetterCallback, v8::AccessorSetterCallback, v8::Handle<v8::Value>, v8::AccessControl, v8::PropertyAttribute)’ [-fpermissive] ../src/fibers.cc:588:75: error: invalid conversion from ‘void (*)(v8::Local<v8::String>, v8::Local<v8::Value>, const int&)’ to ‘v8::AccessorSetterCallback {aka void (*)(v8::Local<v8::String>, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<void>&)}’ [-fpermissive] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:2098:8: error: initializing argument 3 of ‘bool v8::Object::SetAccessor(v8::Handle<v8::String>, v8::AccessorGetterCallback, v8::AccessorSetterCallback, v8::Handle<v8::Value>, v8::AccessControl, v8::PropertyAttribute)’ [-fpermissive] ../src/fibers.cc:589:72: error: invalid conversion from ‘v8::Handle<v8::Value> (*)(v8::Local<v8::String>, const int&)’ to ‘v8::AccessorGetterCallback {aka void (*)(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>&)}’ [-fpermissive] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:2098:8: error: initializing argument 2 of ‘bool v8::Object::SetAccessor(v8::Handle<v8::String>, v8::AccessorGetterCallback, v8::AccessorSetterCallback, v8::Handle<v8::Value>, v8::AccessControl, v8::PropertyAttribute)’ [-fpermissive] /root/.node-gyp/0.11.12/deps/v8/include/v8.h: In function ‘void init(v8::Handle<v8::Object>)’: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:768:13: error: ‘v8::HandleScope::HandleScope()’ is private ../src/fibers.cc:614:14: error: within this context ../src/fibers.cc: In function ‘v8::Persistent<T> uni::New(v8::Isolate*, v8::Handle<T>) [with T = v8::Object]’: ../src/fibers.cc:123:35: instantiated from here ../src/fibers.cc:30:44: error: no matching function for call to ‘v8::Persistent<v8::Object, v8::NonCopyablePersistentTraits<v8::Object> >::New(v8::Isolate*&, v8::Handle<v8::Object>&)’ ../src/fibers.cc:30:44: note: candidate is: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5591:4: note: static T* v8::Persistent<T, M>::New(v8::Isolate*, T*) [with T = v8::Object, M = v8::NonCopyablePersistentTraits<v8::Object>] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5591:4: note: no known conversion for argument 2 from ‘v8::Handle<v8::Object>’ to ‘v8::Object*’ ../src/fibers.cc: In function ‘v8::Persistent<T> uni::New(v8::Isolate*, v8::Handle<T>) [with T = v8::Function]’: ../src/fibers.cc:124:27: instantiated from here ../src/fibers.cc:30:44: error: no matching function for call to ‘v8::Persistent<v8::Function, v8::NonCopyablePersistentTraits<v8::Function> >::New(v8::Isolate*&, v8::Handle<v8::Function>&)’ ../src/fibers.cc:30:44: note: candidate is: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5591:4: note: static T* v8::Persistent<T, M>::New(v8::Isolate*, T*) [with T = v8::Function, M = v8::NonCopyablePersistentTraits<v8::Function>] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5591:4: note: no known conversion for argument 2 from ‘v8::Handle<v8::Function>’ to ‘v8::Function*’ ../src/fibers.cc: In function ‘v8::Persistent<T> uni::New(v8::Isolate*, v8::Handle<T>) [with T = v8::Context]’: ../src/fibers.cc:125:43: instantiated from here ../src/fibers.cc:30:44: error: no matching function for call to ‘v8::Persistent<v8::Context>::New(v8::Isolate*&, v8::Handle<v8::Context>&)’ ../src/fibers.cc:30:44: note: candidate is: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5591:4: note: static T* v8::Persistent<T, M>::New(v8::Isolate*, T*) [with T = v8::Context, M = v8::NonCopyablePersistentTraits<v8::Context>] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5591:4: note: no known conversion for argument 2 from ‘v8::Handle<v8::Context>’ to ‘v8::Context*’ ../src/fibers.cc: In function ‘void uni::Dispose(v8::Isolate*, v8::Persistent<T>&) [with T = v8::Object]’: ../src/fibers.cc:136:32: instantiated from here ../src/fibers.cc:34:3: error: no matching function for call to ‘v8::Persistent<v8::Object, v8::NonCopyablePersistentTraits<v8::Object> >::Dispose(v8::Isolate*&)’ ../src/fibers.cc:34:3: note: candidate is: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:588:3: note: void v8::Persistent<T, M>::Dispose() [with T = v8::Object, M = v8::NonCopyablePersistentTraits<v8::Object>] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:588:3: note: candidate expects 0 arguments, 1 provided ../src/fibers.cc: In function ‘void uni::Dispose(v8::Isolate*, v8::Persistent<T>&) [with T = v8::Function]’: ../src/fibers.cc:137:28: instantiated from here ../src/fibers.cc:34:3: error: no matching function for call to ‘v8::Persistent<v8::Function, v8::NonCopyablePersistentTraits<v8::Function> >::Dispose(v8::Isolate*&)’ ../src/fibers.cc:34:3: note: candidate is: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:588:3: note: void v8::Persistent<T, M>::Dispose() [with T = v8::Function, M = v8::NonCopyablePersistentTraits<v8::Function>] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:588:3: note: candidate expects 0 arguments, 1 provided ../src/fibers.cc: In function ‘void uni::Dispose(v8::Isolate*, v8::Persistent<T>&) [with T = v8::Context]’: ../src/fibers.cc:138:36: instantiated from here ../src/fibers.cc:34:3: error: no matching function for call to ‘v8::Persistent<v8::Context>::Dispose(v8::Isolate*&)’ ../src/fibers.cc:34:3: note: candidate is: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:588:3: note: void v8::Persistent<T, M>::Dispose() [with T = v8::Context, M = v8::NonCopyablePersistentTraits<v8::Context>] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:588:3: note: candidate expects 0 arguments, 1 provided ../src/fibers.cc: In function ‘void uni::MakeWeak(v8::Isolate*, v8::Persistent<T>&, P*) [with void (* F)(v8::Isolate*, v8::Persistent<v8::Value, v8::NonCopyablePersistentTraits<v8::Value> >, void*) = Fiber::WeakCallback, T = v8::Object, P = Fiber]’: ../src/fibers.cc:146:53: instantiated from here ../src/fibers.cc:39:3: error: no matching function for call to ‘v8::Persistent<v8::Object, v8::NonCopyablePersistentTraits<v8::Object> >::MakeWeak(v8::Isolate*&, Fiber*&, void (*)(v8::Isolate*, v8::Persistent<v8::Value, v8::NonCopyablePersistentTraits<v8::Value> >, void*))’ ../src/fibers.cc:39:3: note: candidates are: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:646:3: note: template<class S, class P> void v8::Persistent::MakeWeak(P*, typename v8::WeakReferenceCallbacks<S, P>::Revivable) [with S = S, P = P, T = v8::Object, M = v8::NonCopyablePersistentTraits<v8::Object>, typename v8::WeakReferenceCallbacks<S, P>::Revivable = <type error>] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:653:3: note: template<class P> void v8::Persistent::MakeWeak(P*, typename v8::WeakReferenceCallbacks<T, P>::Revivable) [with P = P, T = v8::Object, M = v8::NonCopyablePersistentTraits<v8::Object>, typename v8::WeakReferenceCallbacks<T, P>::Revivable = <type error>] ../src/fibers.cc: In function ‘v8::Persistent<T> uni::New(v8::Isolate*, v8::Handle<T>) [with T = v8::Primitive]’: ../src/fibers.cc:269:55: instantiated from here ../src/fibers.cc:30:44: error: no matching function for call to ‘v8::Persistent<v8::Primitive, v8::NonCopyablePersistentTraits<v8::Primitive> >::New(v8::Isolate*&, v8::Handle<v8::Primitive>&)’ ../src/fibers.cc:30:44: note: candidate is: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5591:4: note: static T* v8::Persistent<T, M>::New(v8::Isolate*, T*) [with T = v8::Primitive, M = v8::NonCopyablePersistentTraits<v8::Primitive>] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5591:4: note: no known conversion for argument 2 from ‘v8::Handle<v8::Primitive>’ to ‘v8::Primitive*’ ../src/fibers.cc: In function ‘v8::Persistent<T> uni::New(v8::Isolate*, v8::Handle<T>) [with T = v8::Value]’: ../src/fibers.cc:339:63: instantiated from here ../src/fibers.cc:30:44: error: no matching function for call to ‘v8::Persistent<v8::Value, v8::NonCopyablePersistentTraits<v8::Value> >::New(v8::Isolate*&, v8::Handle<v8::Value>&)’ ../src/fibers.cc:30:44: note: candidate is: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5591:4: note: static T* v8::Persistent<T, M>::New(v8::Isolate*, T*) [with T = v8::Value, M = v8::NonCopyablePersistentTraits<v8::Value>] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5591:4: note: no known conversion for argument 2 from ‘v8::Handle<v8::Value>’ to ‘v8::Value*’ ../src/fibers.cc: In function ‘v8::Persistent<T> uni::New(v8::Isolate*, v8::Handle<T>) [with T = v8::FunctionTemplate]’: ../src/fibers.cc:561:55: instantiated from here ../src/fibers.cc:30:44: error: no matching function for call to ‘v8::Persistent<v8::FunctionTemplate, v8::NonCopyablePersistentTraits<v8::FunctionTemplate> >::New(v8::Isolate*&, v8::Handle<v8::FunctionTemplate>&)’ ../src/fibers.cc:30:44: note: candidate is: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5591:4: note: static T* v8::Persistent<T, M>::New(v8::Isolate*, T*) [with T = v8::FunctionTemplate, M = v8::NonCopyablePersistentTraits<v8::FunctionTemplate>] /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5591:4: note: no known conversion for argument 2 from ‘v8::Handle<v8::FunctionTemplate>’ to ‘v8::FunctionTemplate*’ In file included from /root/.node-gyp/0.11.12/src/node.h:61:0, from ../src/coroutine.h:1, from ../src/fibers.cc:1: /root/.node-gyp/0.11.12/deps/v8/include/v8.h: In static member function ‘static void v8::NonCopyablePersistentTraits<T>::Uncompilable() [with O = v8::Object, T = v8::Object]’: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:474:5: instantiated from ‘static void v8::NonCopyablePersistentTraits<T>::Copy(const v8::Persistent<S, M>&, v8::NonCopyablePersistentTraits<T>::NonCopyablePersistent*) [with S = v8::Object, M = v8::NonCopyablePersistentTraits<v8::Object>, T = v8::Object, v8::NonCopyablePersistentTraits<T>::NonCopyablePersistent = v8::Persistent<v8::Object, v8::NonCopyablePersistentTraits<v8::Object> >]’ /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5608:3: instantiated from ‘void v8::Persistent<T, M>::Copy(const v8::Persistent<S, M>&) [with S = v8::Object, M2 = v8::NonCopyablePersistentTraits<v8::Object>, T = v8::Object, M = v8::NonCopyablePersistentTraits<v8::Object>]’ /root/.node-gyp/0.11.12/deps/v8/include/v8.h:546:5: instantiated from ‘v8::Persistent<T, M>::Persistent(const v8::Persistent<T, M>&) [with T = v8::Object, M = v8::NonCopyablePersistentTraits<v8::Object>, v8::Persistent<T, M> = v8::Persistent<v8::Object, v8::NonCopyablePersistentTraits<v8::Object> >]’ ../src/fibers.cc:129:19: instantiated from here /root/.node-gyp/0.11.12/deps/v8/include/v8.h:478:5: error: cannot convert ‘v8::Primitive*’ to ‘v8::Object* volatile’ in assignment /root/.node-gyp/0.11.12/deps/v8/include/v8.h: In static member function ‘static void v8::NonCopyablePersistentTraits<T>::Uncompilable() [with O = v8::Object, T = v8::Function]’: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:474:5: instantiated from ‘static void v8::NonCopyablePersistentTraits<T>::Copy(const v8::Persistent<S, M>&, v8::NonCopyablePersistentTraits<T>::NonCopyablePersistent*) [with S = v8::Function, M = v8::NonCopyablePersistentTraits<v8::Function>, T = v8::Function, v8::NonCopyablePersistentTraits<T>::NonCopyablePersistent = v8::Persistent<v8::Function, v8::NonCopyablePersistentTraits<v8::Function> >]’ /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5608:3: instantiated from ‘void v8::Persistent<T, M>::Copy(const v8::Persistent<S, M>&) [with S = v8::Function, M2 = v8::NonCopyablePersistentTraits<v8::Function>, T = v8::Function, M = v8::NonCopyablePersistentTraits<v8::Function>]’ /root/.node-gyp/0.11.12/deps/v8/include/v8.h:546:5: instantiated from ‘v8::Persistent<T, M>::Persistent(const v8::Persistent<T, M>&) [with T = v8::Function, M = v8::NonCopyablePersistentTraits<v8::Function>, v8::Persistent<T, M> = v8::Persistent<v8::Function, v8::NonCopyablePersistentTraits<v8::Function> >]’ ../src/fibers.cc:129:19: instantiated from here /root/.node-gyp/0.11.12/deps/v8/include/v8.h:478:5: error: cannot convert ‘v8::Primitive*’ to ‘v8::Object* volatile’ in assignment /root/.node-gyp/0.11.12/deps/v8/include/v8.h: In static member function ‘static void v8::NonCopyablePersistentTraits<T>::Uncompilable() [with O = v8::Object, T = v8::Context]’: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:474:5: instantiated from ‘static void v8::NonCopyablePersistentTraits<T>::Copy(const v8::Persistent<S, M>&, v8::NonCopyablePersistentTraits<T>::NonCopyablePersistent*) [with S = v8::Context, M = v8::NonCopyablePersistentTraits<v8::Context>, T = v8::Context, v8::NonCopyablePersistentTraits<T>::NonCopyablePersistent = v8::Persistent<v8::Context>]’ /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5608:3: instantiated from ‘void v8::Persistent<T, M>::Copy(const v8::Persistent<S, M>&) [with S = v8::Context, M2 = v8::NonCopyablePersistentTraits<v8::Context>, T = v8::Context, M = v8::NonCopyablePersistentTraits<v8::Context>]’ /root/.node-gyp/0.11.12/deps/v8/include/v8.h:546:5: instantiated from ‘v8::Persistent<T, M>::Persistent(const v8::Persistent<T, M>&) [with T = v8::Context, M = v8::NonCopyablePersistentTraits<v8::Context>, v8::Persistent<T, M> = v8::Persistent<v8::Context>]’ ../src/fibers.cc:129:19: instantiated from here /root/.node-gyp/0.11.12/deps/v8/include/v8.h:478:5: error: cannot convert ‘v8::Primitive*’ to ‘v8::Object* volatile’ in assignment /root/.node-gyp/0.11.12/deps/v8/include/v8.h: In static member function ‘static void v8::NonCopyablePersistentTraits<T>::Uncompilable() [with O = v8::Object, T = v8::Value]’: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:474:5: instantiated from ‘static void v8::NonCopyablePersistentTraits<T>::Copy(const v8::Persistent<S, M>&, v8::NonCopyablePersistentTraits<T>::NonCopyablePersistent*) [with S = v8::Primitive, M = v8::NonCopyablePersistentTraits<v8::Primitive>, T = v8::Value, v8::NonCopyablePersistentTraits<T>::NonCopyablePersistent = v8::Persistent<v8::Value, v8::NonCopyablePersistentTraits<v8::Value> >]’ /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5608:3: instantiated from ‘void v8::Persistent<T, M>::Copy(const v8::Persistent<S, M>&) [with S = v8::Primitive, M2 = v8::NonCopyablePersistentTraits<v8::Primitive>, T = v8::Value, M = v8::NonCopyablePersistentTraits<v8::Value>]’ /root/.node-gyp/0.11.12/deps/v8/include/v8.h:558:5: instantiated from ‘v8::Persistent<T, M>& v8::Persistent<T, M>::operator=(const v8::Persistent<S, M>&) [with S = v8::Primitive, M2 = v8::NonCopyablePersistentTraits<v8::Primitive>, T = v8::Value, M = v8::NonCopyablePersistentTraits<v8::Value>, v8::Persistent<T, M> = v8::Persistent<v8::Value, v8::NonCopyablePersistentTraits<v8::Value> >]’ ../src/fibers.cc:269:55: instantiated from here /root/.node-gyp/0.11.12/deps/v8/include/v8.h:478:5: error: cannot convert ‘v8::Primitive*’ to ‘v8::Object* volatile’ in assignment /root/.node-gyp/0.11.12/deps/v8/include/v8.h: In static member function ‘static void v8::NonCopyablePersistentTraits<T>::Uncompilable() [with O = v8::Object, T = v8::FunctionTemplate]’: /root/.node-gyp/0.11.12/deps/v8/include/v8.h:474:5: instantiated from ‘static void v8::NonCopyablePersistentTraits<T>::Copy(const v8::Persistent<S, M>&, v8::NonCopyablePersistentTraits<T>::NonCopyablePersistent*) [with S = v8::FunctionTemplate, M = v8::NonCopyablePersistentTraits<v8::FunctionTemplate>, T = v8::FunctionTemplate, v8::NonCopyablePersistentTraits<T>::NonCopyablePersistent = v8::Persistent<v8::FunctionTemplate, v8::NonCopyablePersistentTraits<v8::FunctionTemplate> >]’ /root/.node-gyp/0.11.12/deps/v8/include/v8.h:5608:3: instantiated from ‘void v8::Persistent<T, M>::Copy(const v8::Persistent<S, M>&) [with S = v8::FunctionTemplate, M2 = v8::NonCopyablePersistentTraits<v8::FunctionTemplate>, T = v8::FunctionTemplate, M = v8::NonCopyablePersistentTraits<v8::FunctionTemplate>]’ /root/.node-gyp/0.11.12/deps/v8/include/v8.h:553:5: instantiated from ‘v8::Persistent<T, M>& v8::Persistent<T, M>::operator=(const v8::Persistent<T, M>&) [with T = v8::FunctionTemplate, M = v8::NonCopyablePersistentTraits<v8::FunctionTemplate>, v8::Persistent<T, M> = v8::Persistent<v8::FunctionTemplate, v8::NonCopyablePersistentTraits<v8::FunctionTemplate> >]’ ../src/fibers.cc:561:55: instantiated from here /root/.node-gyp/0.11.12/deps/v8/include/v8.h:478:5: error: cannot convert ‘v8::Primitive*’ to ‘v8::Object* volatile’ in assignment ../src/fibers.cc: In function ‘v8::Persistent<T> uni::New(v8::Isolate*, v8::Handle<T>) [with T = v8::FunctionTemplate]’: ../src/fibers.cc:31:2: warning: control reaches end of non-void function [-Wreturn-type] ../src/fibers.cc: In function ‘v8::Persistent<T> uni::New(v8::Isolate*, v8::Handle<T>) [with T = v8::Function]’: ../src/fibers.cc:31:2: warning: control reaches end of non-void function [-Wreturn-type] ../src/fibers.cc: In static member function ‘static v8::Handle<v8::Value> Fiber::GetCurrent(v8::Local<v8::String>, const int&)’: ../src/fibers.cc:524:3: warning: control reaches end of non-void function [-Wreturn-type] ../src/fibers.cc: In function ‘v8::Persistent<T> uni::New(v8::Isolate*, v8::Handle<T>) [with T = v8::Value]’: ../src/fibers.cc:31:2: warning: control reaches end of non-void function [-Wreturn-type] ../src/fibers.cc: In function ‘v8::Persistent<T> uni::New(v8::Isolate*, v8::Handle<T>) [with T = v8::Primitive]’: ../src/fibers.cc:31:2: warning: control reaches end of non-void function [-Wreturn-type] ../src/fibers.cc: In static member function ‘static v8::Handle<v8::Value> Fiber::New(const int&)’: ../src/fibers.cc:235:3: warning: control reaches end of non-void function [-Wreturn-type] make: *** [Release/obj.target/fibers/src/fibers.o] Error 1 make: Leaving directory `/root/mt_5/bundle/programs/server/node_modules/fibers/build' gyp ERR! build error gyp ERR! stack Error: `make` failed with exit code: 2 gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23) gyp ERR! stack at ChildProcess.EventEmitter.emit (events.js:107:17) gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:1045:12) gyp ERR! System Linux 3.8.0-29-generic gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" gyp ERR! cwd /root/mt_5/bundle/programs/server/node_modules/fibers gyp ERR! node -v v0.11.12 gyp ERR! node-gyp -v v0.13.0 gyp ERR! not ok Build failed npm ERR! [email protected] install: `node ./build.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] install script. npm ERR! This is most likely a problem with the fibers package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node ./build.js npm ERR! You can get their info via: npm ERR! npm owner ls fibers npm ERR! There is likely additional logging output above. npm ERR! System Linux 3.8.0-29-generic npm ERR! command "node" "/usr/local/bin/npm" "install" "[email protected]" npm ERR! cwd /root/mt_5/bundle/programs/server/node_modules npm ERR! node -v v0.11.12 npm ERR! npm -v 1.4.7 npm ERR! code ELIFECYCLE npm ERR! npm ERR! Additional logging details can be found in: npm ERR! /root/mt_5/bundle/programs/server/node_modules/npm-debug.log npm ERR! not ok code 0 What to do? Thanks! A: So after a bit of googeling i came to this. Node-fibers doesn't support intermediary releases, therefore you need to use 0.10.x branch or supported 11.x release!
{ "pile_set_name": "StackExchange" }
Q: I'm not able to perform validation for the input data in my mongoengine model class class TextBoxValues(DynamicDocument): entity_id = StringField(max_length=200, required=True) textbox_type = StringField(max_length=1000, required=True) regexp = re.compile('[A-Za-z]') entity_value = StringField(regex=regexp,max_length=None, required=True) I was using the regex parameter to perform validation which is not working for me,it still takes input in any format, why? A: The regex to provide to StringField(regex=) should in fact be a string but it also work if you give it a compiled regex. The problem is your regex actually. It should be regexp=r'^[A-Za-z]+$' as @wiktor-stribiżew suggested in the comment. The minimal example below demonstrates that the regex works as expected from mongoengine import * connect() # connect to 'test' database class TextBoxValues(Document): entity_value = StringField(regex=r'^[A-Za-z]+$') TextBoxValues(entity_value="AZaz").save() # passes validation TextBoxValues(entity_value="AZaz1").save() # raises ValidationError (String value did not match validation regex: ['entity_value'])
{ "pile_set_name": "StackExchange" }
Q: Unwanted outgoing phone calls Occasionally, when I flip the lid of my phone and put it on the table, the phone calls the primary number of the contact with which I communicated last (by phone or text message). I suspect that some button has this function under certain circumstances, but I am not able to reproduce this call back voluntarily. Does anyone know what happens to me? And maybe how to deactivate this hidden callback feature. I have a Samsung Galaxy S5 mini. Edit: According to the answer I received, I moved the icon of the phone app, so that it would be impossible to tap it three times by closing the lid. But this didn't change the problem. The annoying unwanted outgoing calls still persist. A: Finally, I found the problem. On the phone, when the contact is open, and I take the phone close to the ear, it calls, without touching it. Thus, when I leave the contact open, the phone can call out unvoluntarily. It suffices that it detects an object moving near. this can even happen when the phone was locked, and is unlocked later with the details of a contact open.
{ "pile_set_name": "StackExchange" }
Q: How to make a google spreadsheet into a list or a well spaced string? I'm trying to extract the data on a spreadsheet either into a nested 2-d list or copy and paste somehow as a string in which the spacing without format is not terrible. At first, I was thinking of just stripping the duplicate spaces away, but sometimes certain cells end up having not a single space between them and that's why I cannot do that. Anyway, I need to be able to extract long data which is why I need an easy way of accessing without having to go an fix the spacing for all the names and their corresponding information. A: Adapted from the Python Quickstart, you could use the following code: from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] # The ID and range of a sample spreadsheet. SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' RANGE_NAME = 'Class Data!A2:E' def main(): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('sheets', 'v4', credentials=creds) # Call the Sheets API sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute() values = result.get('values', []) if not values: print('No data found.') else: for row in values: print(', '.join(row)) if __name__ == '__main__': main() You will need to set the SPREADSHEET_ID to your Spreadsheet's Id and the RANGE_NAME to the range you are attempting to fetch. Afterwards, the data retrieved will be in the values variable, as a 2D Array. You can also use the pprint module for printing the data in a more human-readable way. You can read more about this solution in the Python Quickstart page.
{ "pile_set_name": "StackExchange" }
Q: Remove spaces in a Javascript variable I'm using AJAX to retrieve data from MYSQL database through PHP. However, if there is no result found, the variable still has two spaces. I found the problem using alert(data.length);. The result is 2, which means there are two spaces. How can I remove these spaces so that if there is no result, I could display a message using if(data == ''){}? Thank you! A: This is called string trimming. And here is one option for that in pure JavaScript: var len = data.replace(/\s/g, "").length; However, in modern browsers there is a string trim() function for that: var len = data.trim().length; A: I can't understand why you have those two empty spaces in the first place. If it's a suitable option for you, I would try to remove those spaces at the origin, so from the server response. If that's not possible you could use String.prototype.trim to remove leading/trailing white space. This would allow you to write your check as below if (data.trim().length === 0) { ... }
{ "pile_set_name": "StackExchange" }
Q: Cómo correr QT Designer en QT5 Windows He instalado PyQT5 sobre Windows mediante pip3 install PyQt5. Sin errores. De hecho desde Python se puede importar el módulo. Problema: ¿cómo puedo correr Qt Designer? No veo ningún designer.exe o similar. Gracias por adelantado. A: Qt Designer no viene con pyqt, sino que forma parte del paquete PyQt5-tools, debes instalarlo de forma independiente: py -3 -m pip install PyQt5-tools Una vez instalado correctamente te vas a donde tengas instalado Python en tu sistema y lo encontrarás en: Lib\site-packages\pyqt5-tools\designer.exe Si instalaste Python en el directorio por defecto (Windows 10) debes encontrarlo en: C:\Users\TU_USUARIO\AppData\Local\Programs\Python\Python36\Lib\site-packages\PyQt5\designer.exe ^ ^ | | Cambiar por tu usuario Cambiar por tu versión de Python Puedes crear un acceso directo para más comodidad.
{ "pile_set_name": "StackExchange" }
Q: DataTable: swich 2 Columns without header My Goal is to switch 2 Columns like this: datatable.Columns["column1"].SetOrdinal(1); datatable.Columns["column2"].SetOrdinal(0); Now what i'm trying to achieve, is that the column header(column1, column2) stay at their place not like the other values. A: You want to change the row-field order: foreach(DataRow row in datatable.Rows) { object oldCol2 = row["column2"]; row["column2"] = row["column1"]; row["column1"] = oldCol2; } But note that both columns should have the same type.
{ "pile_set_name": "StackExchange" }
Q: Revmob and Chartboost appear too late (lag?) I am making an iPhone/iPad application and I have the following problem: I want to pop up a revmob or a chartboost ad on my game over screen, which has a restart button. The ads do pop up, but by the time they appear, the player may press restart and go into gameplay again. And the ads end up on the gameplay screen (which I dont want) instead of ending up on the game over screen. Is there any way I can make sure that both chartboost and revmob ads pop up immediately after I make a call to their respective ad display functions? A: For Chartboost, I recommend you use the cacheInterstitial method before you call showInterstitial. By caching an ad, you are essentially taking an ad from the server and loading it temporarily onto the users device. After you have cached the ad, wait about 10 seconds or so and then call showInterstitial. This will speed up the process of showing ads. You can also utilize the delegate method shouldDisplayInterstitial. You can set it to NO if it is not an appropriate time to show an ad. Take a look at the following links for help http://help.chartboost.com/documentation/ios https://github.com/ChartBoost/client-examples Also, email [email protected] if you have any other questions.
{ "pile_set_name": "StackExchange" }
Q: libxml2 on iOS causing EXC_BAD_ACCESS errors when parsing HTML with HTMLParser I've been working on a project that uses libxml2 HTMLParser module to parse webpage HTML on iOS. I'm getting an EXC_BAD_ACCESS error from libxml2's htmlParseDocument whenever I try to parse a webpage that contains the line: <?xml version="1.0" encoding="UTF-8"?> If I strip this line out of the HTML, parsing works perfectly. Also note, I am using the DTHTMLParser class to bind the libxml2 SAX callbacks to Objective-C code. Since EXC_BAD_ACCESS in htmlParseDocument isn't much to go on, I've built a sample Xcode project that reproduces the error. I made it in Xcode 4.4 on Mountain Lion targeted for iOS 5.1. First it parses an HTML file that doesn't contain the offending line, then it attempts to parse the document with the offending line and crashes. You can download it here: http://michaelmanesh.com/code/libxml2-crash.zip A: The problem in DTHTMLParser was that apparently the method to prepare the c-callbacks in libxml did not set the function pointer for the function to call when a processing instruction is encountered to NULL. Because of this the processing instruction caused libxml2 to try to call a function at some random address causing the EXC_BAD_ACCESS. I fixed the problem in DTHTMLParser by implementing support for an optional delegate method to be called for when a processing instruction is encountered or NULL in the handler struct if this is not implemented in the delegate.
{ "pile_set_name": "StackExchange" }
Q: Want to make a software on VB.NET which decode Base64-encoded text strings and vice-versa I want to make a Software which decodes Base64-encoded text strings and vice versa. Any help provided on the topic with coding in Visual Basic will help me a lot. Thank you. Note:-c# language can also be implemented A: You need to call Convert.ToBase64String and Convert.FromBase64String. These methods convert byte arrays to and from Base64. If you want to encode a string in Base64, you'll need to convert it to a byte array by calling Encoding.Unicode.GetBytes(str) and Encoding.Unicode.GetString(bytes). (In the System.Text namespace) Note that Base64 should never be used for encryption, except to convert a byte array that was already encrypted into a string. If you want to encrypt data, use the RijndaelManaged class.
{ "pile_set_name": "StackExchange" }
Q: D3 force layou/ avoid overlapping node ( forcecollide, radius) I tried to create cluster bubble by using d3 force layout. After referring to several code, I could create the following chart. However the problem is that circles is overlapping each others. I referred to the several Q&A for this problem,Still I could not solve the porblem. I tried to make chart like the following site.(https://blockbuilder.org/ericsoco/d2d49d95d2f75552ac64f0125440b35e) I've already add forcecollide, however it seems not working.. Could anyone help this problem? The code for this chart is as follows. <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <div id="my_dataviz"></div> <script src="https://d3js.org/d3.v5.js"></script> <script> // set the dimensions and margins of the graph var width = 450 var height = 450 // append the svg object to the body of the page var svg = d3.select("#my_dataviz") .append("svg") .attr("width", 450) .attr("height", 450), color = d3.scaleOrdinal(d3.schemeAccent); // create dummy data -> just one element per circle var data = [{ "name": "A" , value:10}, { "name": "B", value:20 }, { "name": "C" , value:20 }, { "name": "D" , value:60 }, { "name": "E" , value:20 }, { "name": "F", value:20 }, { "name": "G", value:50 }, { "name": "H" , value:100 }] // Initialize the circle: all located at the center of the svg area var node = svg.append("g") .selectAll("circle") .data(data) .enter() .append("circle") .attr("r", d => d.value) .attr("cx", width / 2) .attr("cy", height / 2) .style("fill", d=>color(d.name)) .style("fill-opacity", 0.9) // .attr("stroke", "#b3a2c8") .style("stroke-width", 4) .call(d3.drag() // call specific function when circle is dragged .on("start", dragstarted) .on("drag", dragged) .on("end", dragended)); var transitionTime = 3000; var t = d3.timer(function (elapsed) { var dt = elapsed / transitionTime; simulation.force('collide').strength(Math.pow(dt, 2) * 0.7); if (dt >= 1.0) t.stop(); }); // Features of the forces applied to the nodes: var simulation = d3.forceSimulation() .force("center", d3.forceCenter().x(width / 2).y(height / 2)) // Attraction to the center of the svg area .force("collide", d3.forceCollide().strength(1).radius(30).iterations(1)) // Force that avoids circle overlapping .force('attract', d3.forceRadial(0, width / 2, height / 2).strength(0.07)) // Apply these forces to the nodes and update their positions. // Once the force algorithm is happy with positions ('alpha' value is low enough), simulations will stop. simulation .nodes(data) .on("tick", function(d){ node .attr("cx", function(d){ return d.x; }) .attr("cy", function(d){ return d.y; }) }); // What happens when a circle is dragged? function dragstarted(d) { if (!d3.event.active) simulation.alphaTarget(.03).restart(); d.fx = d.x; d.fy = d.y; } function dragged(d) { d.fx = d3.event.x; d.fy = d3.event.y; } function dragended(d) { if (!d3.event.active) simulation.alphaTarget(.03); d.fx = null; d.fy = null; } </script> </body> </html> A: In the collide force, you have a constant of 30 for the radius, if you pass a callback function to return the node value (your nodes radii) the problem should bbe solved. Here is how I did it: .force("collide", d3.forceCollide().strength(1).radius( (d) => d.value ).iterations(1))
{ "pile_set_name": "StackExchange" }
Q: FCM/GCM JSON payload - How to specify a large icon? I am sending a push notification using firebase endpoint. It is working successfully. I am using postman to send the request to FCM. My issue is I do not understand how to send a large icon with it. FCM has two types of payloads you can send. Data payloads and notification payloads. See here. I'm focusing on notification payloads. How do I specify a local large icon to show ? I know I can specify a default notification icon in the manifest this way using metadata: <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/mylogo" /> <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/mycolor" /> But this is for a small icon. How do I specify LARGE icon I'd like to use ? In the documentation I provided above for FCM, there is a example that looks like this: { "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "notification" : { "body" : "great match!", "title" : "Portugal vs. Denmark", "icon" : "myicon" } } but this is for small icon. how to do large icon? A large icon looks like this: A: FCM doesn't have an API to set a large-icon. If you want to achieve that you can send a data-message with custom payload, and create your own local notification inside onMessageReceived()
{ "pile_set_name": "StackExchange" }
Q: Haskell: Is it possible to use the abstract data type in pattern matching Say I have an ADT called foo data foo = N Integer | V Var | Div foo foo Is there a way to use the ADT in pattern matching so I don't have to write out every possible combination of data types? myfunc :: foo -> [Var] myfunc (N _) = [] myfunc (V a) = [a] myfunc (Div (foo) (foo)) = myfunc(foo) ++ myfunc(foo) Is there a way to make something like this work so I don't have to write myfunc (Div (N a) (N b)) = myfunc(N a) ++ myfunc(N b) myfunc (Div (V a) (N b)) = myfunc(V a) ++ myfunc(N b) myfunc (Div (N a) (V b)) = myfunc(N a) ++ myfunc(V b) ... etc A: Well, if you name things correctly, what you have works: -- types have to begin with a capital letter, just like constructors data Foo = N Integer | V Var | Div Foo Foo myfunc :: Foo -> [Var] myfunc (N _) = [] myfunc (V a) = [a] myfunc (Div left right) = myfunc left ++ myfunc right To test: type Var = String -- Don't know what Var is, but it's a String for this example > myfunc (Div (Div (V "A") (V "B")) (Div (V "C") (N 1))) ["A", "B", "C"]
{ "pile_set_name": "StackExchange" }
Q: Activity recreation and unresumable operation I wonder what is correct way for handling an unresumable running process when an activity recreates. For example I have a JNI module for authenticating to a server. I have created a new instance of this object in OnCreateView() of my activity, setting up some callback routines for it. Now by pressing a button, I start my authentication process asynchronously. Authentication is just 1 sec, but if my activity recreate during authentication process(for example I switch from portrait to landscape), my JNI object will be recreated and mess authentication process up. I cannot save state of authentication process. Now what do you suggest for such situations? An idea is running authentication process in a service, completely separated from activity recreation. I wonder if there is any other simpler approach or not. A: Add configChanges to your activity in Manifest. <activity android:name="com.yourActivity" android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:label="@string/app_name" android:theme="@android:style/Theme.Translucent.NoTitleBar" />
{ "pile_set_name": "StackExchange" }
Q: Run a VBA Macro against an Excel sheet with C# Is it possible to write a WPF C# application that can load and read a VBA Macro from a separate text file, open an existing Excel workbook, and process the VBA macro against it? I am NOT trying to convert VBA to C# or generate VBA from C#. The application, VBA Macro text file (the VBA is extracted and saved separately on a text file), and Excel are all written / generated separately by different people. The application load and read a text file that contains VBA, and open an existing excel file and run the Macro against it either by injecting the macro to excel or even better, leave the workbook without a macro in it. I have no idea how or where to start, or if that is even possible. The closet I found on SO is Injecting vba macro code into excel using .net but doesn't seem to help. I'm looking for any suggestion to get me start and I'll share and update my progress here. A: Here is the way to add some VBA from file in VBA (shouldn't be so hard to adapt it to C# but I am not familiar enough to C# syntax): Function Insert_VBACode(ByRef oWB As Workbook) Dim oVBP As VBProject ' VB Project Object Dim oVBC As VBComponent ' VB Component Object On Error GoTo Err_VBP Set oVBP = oWB.VBProject Set oVBC = oVBP.VBComponents.Add(vbext_ct_StdModule) oVBC.CodeModule.AddFromFile "c:\VBADUD\Templates\MSample.bas" oWB.Application.Run "'" & oWB.name & "'!SayHello" oWB.Save End Function [Source] (have a look there if you want to add any error handling I've removed here for more readability). You can also open the workbook instead of taking it as an argument of the function. And then, you can call your imported macro from C# thanks to this walkthrough from MSDN.
{ "pile_set_name": "StackExchange" }
Q: Replace all zeros in array with previous nonzero value with Scala I would like to know if there is a neat way of replacing all zeros in an array with the previous nonzero value in Scala. Similar to this question: pandas replace zeros with previous non zero value I can achieve this for the case where there are no consecutive zeros with sliding: scala> Array(1,2,3,0,5,6,7).sliding(2).map {case Array(v1, v2) => if (v2==0) v1 else v2}.toArray res293: Array[Int] = Array(2, 3, 3, 5, 6, 7) although I then have to append the first value (which I would do before converting to array). The above code does not work if there are two consecutive zeros: scala> Array(1,2,3,0,0,6,7).sliding(2).map {case Array(v1, v2) => if (v2==0) v1 else v2}.toArray res294: Array[Int] = Array(2, 3, 3, 0, 6, 7) The desired result is Array(2,3,3,3,6,7). This would be easy to do with a for loop; is it possible with a functional approach? A: Use scanLeft: Array(1,2,3,0,5,6,7).scanLeft(0)({(left, right) => if (right == 0) then left else right}).tail A: There are probably lots of ways. You can do this with foldLeft for example: Array(1,2,3,0,0,6,7) .foldLeft(List.empty[Int]){ (acc, v) => if (v != 0) v :: acc else acc.head :: acc }.reverse.toArray
{ "pile_set_name": "StackExchange" }
Q: How can i export my event logs to a folder (csv or txt) on every start up automatically? I was looking for either a batch file, powerscript (not really good with yet)or any way to have my event logs exported to txt or csv on every start up? Im using windows 7 pro if that helps A: This will output last 20 system event logs in eventlog.txt.Not sure what exactly you need from eventlog - it's a big place... WEVTUtil query-events System /count:20 /rd:true /format:text > eventlog.txt You can change System to Application,Security or Setup - not sure what exactly you need. more info: http://ss64.com/nt/wevtutil.html check also this: http://ss64.com/nt/psloglist.html You can save this (or similar) command to bat file and schedule it on start-up
{ "pile_set_name": "StackExchange" }
Q: Input não recebe valor ao clicar no Button Estou com dificuldade em utilizar o getElementById. Quando executo meu código e clico no botão, aparentemente o valor inserido no input não é recebido. Alguém pode me ajudar? var teste1 = document.getElementById("teste").value; var button = document.querySelector("button"); button.onclick = document.write(teste1); <input id="teste"/> <button>Testar</button> A: Seu problema é que precisa ler o valor do campo ao clicar no botão e não antes, veja o exemplo abaixo: var button = document.querySelector("button"); button.onclick = function(e){ // deve ler o valor ao clicar e nao antes var teste1 = document.getElementById("teste").value; document.write(teste1); } <input id="teste"/> <button>Testar</button>
{ "pile_set_name": "StackExchange" }
Q: React not passing state to child via props I am trying to pass my parent App state to a child component Chart. App constructor() { super(); this.state = { dataPoints: { '424353': { date: '10/10/2016', qty: '95' }, '535332': { date: '10/11/2016', qty: '98' }, '3453432': { date: '10/01/2017', qty: '94' } } }; this.addPoint = this.addPoint.bind(this); } addPoint(dataPoint) { let dataPoints = {...this.state.dataPoints}; const timestamp = Date.now(); dataPoints[timestamp] = dataPoint; this.setState({ dataPoints: dataPoints }); console.log('new state', this.state.dataPoints); } render() { return ( <div className="app"> <Chart dataPoints={this.state.dataPoints} /> <FormControl addPoint={this.addPoint} /> </div> ); } Chart composeData() { Object .keys(this.props.dataPoints) .forEach(key => { ** do stuff ** }); return **stuff**; } componentWillUpdate() { this.composeData(); } The addPoint method works, i.e. I can see in the React console that the new datapoint is added to the state. But it is not reflected in the Chart component. More oddly (to me) is the fact that when I've added a point, the console.log line in my addPoint method (above): console.log('new state', this.state.dataPoints) does not show the new data point. A: In add point addPoint(dataPoint) { let dataPoints = {...this.state.dataPoints}; const timestamp = Date.now(); dataPoints[timestamp] = dataPoint; this.setState({ dataPoints: dataPoints }); console.log('new state', this.state.dataPoints); } In the above code you do not see the updated value because setState takes time to mutate, You must log it in the setState call back this.setState({ dataPoints: dataPoints }, function(){ console.log('new state', this.state.dataPoints); }); And also in the Chart component you need to bind the composeData function if you are using this.props inside it like composeData = () =>{ Object .keys(this.props.dataPoints) .forEach(key => { ** do stuff ** }); return **stuff**; } However componentWillMount is only called once and hence you will want to call the composeData function from componentWillReceiveProps also like componentWillReceiveProps(nextProps) { this.composeData(nextProps) } componentWillMount() { this.composeData(this.props.dataPoints) } composeData(props){ Object .keys(props.dataPoints) .forEach(key => { ** do stuff ** }); return **stuff**; }
{ "pile_set_name": "StackExchange" }
Q: Facebook SDK 3.11 - получить пол юзера, который авторизировался Добрый вечер. Работаю с facebook SDK 3.11 и куда-то пропали нужные поля. Меня интересует: как получить в новом SDK пол юзера, который авторизировался. возможно ли получить EMail не от facebook а тот на котором зарегистрирован аккаунт И есть проблемка с получения дня рождения. Приходит <nul> хоте мое ДР указанно. Зарание спс. (void)loginViewFetchedUserInfo:(FBLoginView*)loginView user:(id<FBGraphUser>)user { self.lblFirstName.text = [NSString stringWithFormat:@"%@", user.first_name]; self.lblFirstName.delegate = self; self.lblSecondName.text = [NSString stringWithFormat:@"%@", user.last_name]; self.lblSecondName.delegate = self; self.lblEmail.text = [NSString stringWithFormat:@"%@@facebook.com", user.username]; self.lblEmail.delegate = self; self.loggedInUser = user; } Как написал iFreeman нужно запросить необходимые readPermissions. [[FBLoginView alloc] initWithReadPermissions:@[@"email"/* и все остальное, что еще нужно */]]; После чего этот Email можно достать очень просто [user objectForKey:@"email"] A: Похоже, что вы забываете запросить необходимые readPermissions. Нужно что-то вроде [[FBLoginView alloc] initWithReadPermissions:@[@"email", @"basic_info", @"user_likes", @"user_birthday"/* и все остальное, что еще нужно */]];
{ "pile_set_name": "StackExchange" }
Q: Read files that are owned by www-data I have a website that writes files when necessary. Those files are owned by www-data. I also have my user, which executes an application to gather information from those files. It is written in Python. However, since those files are owned by www-data, my application can't read them, and I have to execute the application as root, which I'd prefer not to do. What can I do to allow my user read the files that www-data create? EDIT, relative to comments: -rw-r--r-- 1 ivan www-data 444 2011-07-20 16:34 serverfile1.php -rw-r--r-- 1 ivan www-data 140 2011-07-20 16:34 serverfile2.php -rw-r--r-- 1 ivan www-data 478 2011-07-20 16:35 serverfile3.php -rw-r--r-- 1 www-data www-data 10 2011-07-20 17:41 info1.txt -rw-r--r-- 1 www-data www-data 21 2011-07-20 17:41 info2.txt -rw-r--r-- 1 ivan www-data 236 2011-07-20 16:35 serverfile4.php I still can't read the files info1 and info2 using the user ivan A: Add your user to www-data group and make the files group-readabe. # usermod -a -G www-data username # chmod -R g+r /var/www/files
{ "pile_set_name": "StackExchange" }
Q: Powershell, getting user input for computer name and displaying that computers BIOS info, OS info and disk info I am trying to get user input for a target computer that I can run this script for. If no computer name is specified I want to display an error message. ex. I pick dc1 and all the BIOS info, Os info and hard disk shows up for dc1 and not my local computer. Any ideas on how I can achieve this? #Clears the screen cls #Sets status to 0 just incase its not already zero, option 4 sets status to 4 and exit the loop $status = 0 #Gets the BIOS information $biosInfo = get-CIMInstance -Class CIM_BIOSElement |select-Object SMBIOSBIOSVersion, Manufacturer, SerialNumber, Version | Format-Table #Gets the Operating System information $osInfo = get-CIMInstance -Class CIM_OperatingSystem | Select-Object Caption, Version |Format-List #Gets the Disk information $discInfo= get-CIMInstance -Class CIM_LogicalDisk |Select-Object DeviceID, FreeSpace, Size |Format-List @{Name=‘DeviceID‘;Expression={$_.DeviceID}}, @{Name=‘FreeSpace(InPercent)’;Expression={[math]::Round($_.FreeSpace / $_.Size,2)*100}}, @{Name=‘Size(GB)’;Expression={[int]($_.Size / 1GB)}} #Function to select computer name function name { $a = get-cimInstance -Class CIM_ComputerSystem.computername } #Menu selection zone! Write-Host "Query Computer System Main Menu" Write-Host "" Write-Host "1 Display Current BIOS information" Write-Host "2 Display Operating System Information" Write-host "3 Display Hard Disk Information" Write-Host "4 Exit" Write-Host "" do { $status = read-host "Please enter and Option" $computer = Read-Host "Enter target computer name" if ($computer -ne $computer){Write-host "ERROR! Please enter a target computer name" } if ($status -ne 4){ } #Where the menu magic happens switch ($status){ 1{ $biosInfo ; pause} 2{ $osInfo ; pause} 3{ $discInfo ; pause} 4{ $status_text = '4 Exit' ;$status = 4} default {"Please select a number in the list!"} } } #Exits the do loop when status is equal to 4 while ($status -ne 4) A: You need to abstract your Get-CimInstance calls away in a function or a parameterized scriptblock. Instead of this, which immediately executes against your local machine: $OSInfo = Get-CimInstance -Class CIM_OperatingSystem You want something like this: $OSInfoGetter = { param([string]$ComputerName) Get-CimInstance -Class CIM_OperatingSystem -ComputerName $ComputerName } Now you can re-invoke your scriptblock with the call operator (&) and supply any computername as the argument: $OSInfo = &$OSInfoGetter $env:ComputerName For checking the computer name that the user inputs, I'd put another do{}while() loop inside the first one: do { $status = Read-Host "Please enter and Option" do{ $Computer = Read-Host "Enter target computer name" if (($InvalidName = [string]::IsNullOrWhiteSpace($Computer))){ Write-Warning "ERROR! Please enter a target computer name" } } until (-not $InvalidName) # switch goes here } while ($status -ne 4) You can substitute whatever logic you want in there, such as checking for existence of the machine in Active Directory
{ "pile_set_name": "StackExchange" }
Q: General question about analog and digital signals Newbie alert: I am not an electrical engineer, nor have I ever taken electrical engineering, so please bear with me. Whenever I read about the distinction between digital and analog signals, a graphic like this (or similar to this) is usually attached: Consider the bottom illustration for a moment (Digital Signal). To my best understanding, electrical current is continuous, so if that is the case, there is no way it will flow in such a manner in any medium. In other words: there are no "square waves". So what exactly does that depict? Is it just interpretation, whenever the voltage passes some barrier or falls under it? Meaning, when the voltage is above some arbitrarily chosen threshold we consider it as "high" but otherwise we consider it "low"? Please, I know this is not always possible, but try to answer in a way that a layman would understand. A: Basically, from an electrical viewpoint, every "digital" signal is as you say, only an approximation of a square wave. In particular it will have finite rise and fall times. At high speeds, it can be difficult to ensure it looks as nice as the theory wants. To ensure that the signal is still detected as digital (i.e. the receiver doesn't get utterly confused by a horribly shaped signal), the so-called eye diagram (aka eye pattern) is used to measure its characteristics over a number of samples. Many standards (e.g. USB and what not) define some acceptable characteristics for this diagram. Note that an eye pattern/diagram isn't restricted to just two [voltage] levels. It's also applicable when you have any number of discrete output levels. For example, Gigabit Ethernet over twisted pairs (1000BASE-T) uses not two but 5 different voltage levels. Is it just our interpretation to whenever the voltage passes some barrier or falls under it? Meaning, when the voltage is above some arbitrarily chosen threshold we consider it as "high" but otherwise we consider it "low"? Basically, yes, that's how it works, some voltage thresholds for what is "1" and what is "0" are decided by a some standard. A: Digital signals are binary. They have only two states - on or off, high or low, up or down - whatever you want to call them. As you have deduced, there is some threshold above which the value is deemed to be high and another threshold below which the value is deemed to be low. Digital is very simple to do with transistors by either turning them fully on or fully off. Analog signals are analogous to the quantity they are measuring. e.g., a weighing scales might give out a voltage proportional to the load - say 0 to 10 V for a 0 to 200 kg load. Another example is the signal from a microphone which varies with the sound pressure affecting the microphone diaphragm. In this case the frequency will vary with the pitch of the sound and the amplitude will vary with the loudness.
{ "pile_set_name": "StackExchange" }
Q: Canonical Quantization of harmonic oscillator I have a system of two particles with the usual Lagrangian, $$L=\frac12M_1{\dot{x_1}}^2+\frac12M_2{\dot{x_2}}^2-\frac12k({x_1}^2+{x_2}^2)$$ I want to find the quantum Hamiltonian of the system. I started with finding the classical Hamiltonian using, $$H=p_1\dot{x_1}+p_2\dot{x_2}-L$$ where $p_1$ and $p_2$ are the canonical momenta. How can I find the quantum Hamiltonian of the system? I think I have to apply the canonical commutator relationship $$[{x_i},{p_i}]=i\hbar$$ A: HINT: The conjugate variables are: $p_i = \frac{\partial L}{\partial \dot{x}_i}$. After computing H by Legendre transform you have to express the time derivatives of $x_1,x_2$ in terms of momenta $p_1,p_2$. After using definition of momentum operator you have the quantum Hamiltonian.
{ "pile_set_name": "StackExchange" }
Q: Cleaning system for deployment test I have a Qt Quick 2 project and I want to test its deployment on a clean Windows XP machine. This machine has Qt 5.2 and Visual Studio 2010 Express installed (I'm using Qt 5.2 compiled for msvc2010). I'd like to know how to change the system in a way that, for the deployed executable, will seem like a clean system with no dependencies installed (no Qt and MSVC2010). Regarding Qt, it seems that renaming C:\Qt will be sufficient. What about MSVC? I know that the Visual Studio 2010 installation creates a directory (C:\Program Files (x86)\Microsoft Visual Studio 10.0) and also adds new DLLs to C:\Windows\System32. Does it do anything else? Will renaming the folder in C:\Program Files and the DLLs in C:\Windows\System32 be enough? A: There's no way around it but to install a clean copy of XP SP3 into a virtual machine and try it there. You need to worry not only about what MSVC installs, but also what every other application has installed. Many applications install the MSVC redistributable, for example. It is impossible to do such tests on anything but a clean system - this excludes the OEM applications as well. You need a retail copy of Windows XP. They are available and are not too expensive.
{ "pile_set_name": "StackExchange" }
Q: ionic 2 datetime-local minute step 30 min I have a datetime-local input box in my ionic 2 app but I want to show the minutes in 30 min interval only, that is only 0 or 30 (like 9.00 or 9.30). I read about steps but could not find for minutes. Is there a way to achieve it ? A: You should be able to achieve this with setting a attribute minuteValues to your input like this: <ion-datetime displayFormat="HH:mm" [(ngModel)]="myDate" minuteValues="0,30"> The minuteValues can be an array of numbers or a string of comma separated numbers. EDIT: Based on comment. ion-datetime directive is not available in Ionic 1.x but can be used in Ionic 2.x. For Ionic 1.x you can use a plugin like ion-datetime-picker
{ "pile_set_name": "StackExchange" }
Q: Ionic app, fails to load Stripe javascript I have an ionic app, which loads javascript from https://js.stripe.com/v2/. It runs well in the emulator, but when I install the app on device, this javascript file load call fails with 404 response. I found the response has only Client-Via header with value shouldInterceptRequest . What am I doing wrong? A: I solved it as below (adding the answer to help others struck with this in future). This problem is not specific to Stripe. Cordova doesn't allow to access the resources from external sites by default. You need to whitelist an url to allow it. first install the cordova-plugin-whitelist as below ionic plugin add https://github.com/apache/cordova-plugin-whitelist.git then in your apps config.xml file add <allow-navigation href="https://api.stripe.com"/>
{ "pile_set_name": "StackExchange" }
Q: Slow LAN connection (especially receiving) on Windows 8 I was diagnosing my SMB performance issues when I noticed my whole network speed was off. These are my benchmarking results between my desktop and my Linux server: Both are connected using CAT6 and have gigabit networking. ~$ iperf -c 192.168.2.10 -r ------------------------------------------------------------ Server listening on TCP port 5001 TCP window size: 85.3 KByte (default) ------------------------------------------------------------ ------------------------------------------------------------ Client connecting to 192.168.2.10, TCP port 5001 TCP window size: 110 KByte (default) ------------------------------------------------------------ [ 5] local 192.168.2.2 port 54320 connected with 192.168.2.10 port 5001 [ ID] Interval Transfer Bandwidth [ 5] 0.0-10.0 sec 114 MBytes 95.2 Mbits/sec [ 4] local 192.168.2.2 port 5001 connected with 192.168.2.10 port 49719 [ 4] 0.0-10.0 sec 532 MBytes 446 Mbits/sec So, that's 446 Mb/s from my desktop to my server, and no more than 95 Mb/s from my server to my desktop, where both values should be (close to) 1000 Mb/s. I recall getting >900 Mb/s in both directions when I was still running Windows 7. I already tried all sorts of things, like turning off different offloading features in the NIC driver, manually downloading the latest NIC driver from Realtek and disabling autotuning using netsh interface tcp set global autotuning=disabled. EDIT: I did some extensive testing with iperf between the switches and such in the way between my Linux server (LARS-ILLIUM) and my desktop (LARS-VIGIL). LARS-FEROS and LARS-RANNOCH are both switches, and the connection is as follows: LARS-ILLIUM <---> LARS-FEROS <---> LARS-RANNOCH <---> LARS-VIGIL Of course there are other devices connected to the switches, but this is the path between LARS-ILLIUM and LARS-VIGIL. I made table of iperf results: http://prntscr.com/39r0eh I guess the table is fairly self-explainatory, but the first three rows are test results from left to right, and the bottom three rows are the other way around. All tests were UDP btw. Complete command: iperf -c 192.168.2.x -u -b 1000M Now I know that the problem isn't limited to my desktop LARS-VIGIL, but happens in the rest of my LAN as well. Still haven't a single clue what's happening though... A: I figured it out. The reason for the weird iperf results, was that every system I tested on has different default TCP window and UDP buffer sizes. After setting those manually with the -w option I get consistent results: C:\Users\Lars Veldscholte\Downloads\iperf>iperf -c 192.168.2.2 -w 416k -r ------------------------------------------------------------ Server listening on TCP port 5001 TCP window size: 416 KByte ------------------------------------------------------------ ------------------------------------------------------------ Client connecting to 192.168.2.2, TCP port 5001 TCP window size: 416 KByte ------------------------------------------------------------ [ 4] local 192.168.2.10 port 55803 connected with 192.168.2.2 port 5001 [ ID] Interval Transfer Bandwidth [ 4] 0.0-10.0 sec 1003 MBytes 841 Mbits/sec [ 4] local 192.168.2.10 port 5001 connected with 192.168.2.2 port 45938 [ 4] 0.0-10.0 sec 863 MBytes 724 Mbits/sec At least, between my server (LARS-ILLIUM) and my desktop (LARS-VIGIL). Testing on the switches in between still yields weird results: C:\Users\Lars Veldscholte\Downloads\iperf>iperf -c 192.168.2.1 -w 320k -r ------------------------------------------------------------ Server listening on TCP port 5001 TCP window size: 320 KByte ------------------------------------------------------------ ------------------------------------------------------------ Client connecting to 192.168.2.1, TCP port 5001 TCP window size: 320 KByte ------------------------------------------------------------ [ 4] local 192.168.2.10 port 55833 connected with 192.168.2.1 port 5001 [ ID] Interval Transfer Bandwidth [ 4] 0.0-10.3 sec 9.12 MBytes 7.43 Mbits/sec [ 4] local 192.168.2.10 port 5001 connected with 192.168.2.1 port 55335 [ 4] 0.0-10.4 sec 5.00 MBytes 4.01 Mbits/sec I don't know what's up with that.
{ "pile_set_name": "StackExchange" }
Q: Order by Field with two substring The server is returning me the values id, dia_hora 1 SEG-20h 2 SEG-09h 3 QUI-11h 4 SEX-09h This query work for acronyms select * from agenda_padrao ORDER BY ( FIELD(SUBSTRING(dia_hora,1,3), 'DOM', 'SEG', 'TER', 'QUA', 'QUI', 'SEX', 'SAB') ) but i need first sort acronyms and then the two numbers in ascending order like this 2 SEG-09h 1 SEG-20h 3 QUI-11h 4 SEX-09h Thank you for your help A: Use mysql function FIELD() to assign the order. ORDER BY FIELD(SUBSTRING(dia_hora,1,3), 'DOM', 'SEG', 'TER', 'QUA', 'QUI', 'SEX', 'SAB'), cast(substring(dia_hora, 5,6) as unsigned)
{ "pile_set_name": "StackExchange" }
Q: Index of nth biggest item in Python list I can't edit or sort the list. How can I get that index? A: The heapq module provides a nlargest function that efficiently finds the n largest elements of a list: >>> from heapq import nlargest >>> items = [100, 300, 200, 400] >>> indexes = [0, 1, 2, 3] >>> nlargest(2, indexes, key=lambda i: items[i]) [3, 1]
{ "pile_set_name": "StackExchange" }
Q: n bit shift register (Serial in Serial out) in VHDL I'm creating an n bit shift register. When the enable signal is high, I want the shift register to shift n times, irrespective of whether enable continues to be high or low. I've put a for loop to shift n times inside a process. My code is given below. I don't think the for loop is working, as the shifting is not restricted to n times. Where am I going wrong? library ieee; use ieee.std_logic_1164.all; entity SReg is generic ( n : integer := 4 ); port( clk: in std_logic; reset: in std_logic; enable: in std_logic; --enables shifting parallel_in: in std_logic_vector(n-1 downto 0); s_in: in std_logic; --serial input s_out: out std_logic --serial output ); end SReg; architecture behavioral of SReg is signal temp_reg: std_logic_vector(n-1 downto 0) := (Others => '0'); begin process (clk,reset) begin if (reset = '1') then temp_reg <= parallel_in; elsif (clk'event and clk='1') then if (enable ='1') then --shifting n number of bits for i in 0 to n-1 loop s_out <= temp_reg(0); temp_reg <= s_in & temp_reg(n-1 downto 1); end loop; end if; end if; end process; end behavioral; A: In VHDL, a for loop executes in zero time. This means that instead of waiting a clock cycle between each iteration, the entire loop is run within one clock cycle, with only the final result of the loop being shown at the end. This is what's happening in your code. The entire loop is executing in a single clock cycle, and the value of s_out is only going to change once - to the value it was when the loop ended, which in this case is s_in shifted by 4. What you really want is a loop where each iteration occurs on a new clock edge. This allows for s_in to be shifted out of s_out ever clock cycle. Performing a loop where each iteration occurs on a clock edge does not require a for loop command, instead it takes advantage of the sensitivity list of the process. Here's how: A process is triggered every time one of the signals on the sensitivity list ("clk, reset" in this case) changes. This means that the process is already looping every clock cycle (if a clock is in the sensitivity list). You can use this to your advantage in order to perform a for-loop type operation, where every iteration of the loop occurs on a clock cycle. First you need a counter: process(clk,reset) variable shift_counter: integer := 0; begin shift_counter keeps track of how many iterations (or shifts) have occurred so far. you'll compare shift_counter to n-1 to see if you're done yet. Next it might be a good idea to think of the states your process will be in. Perhaps a wait state for when the process is not shifting, and a shifting state for when it is. The state signal definition: TYPE POSSIBLE_STATES IS (waiting, shifting); signal state : POSSIBLE_STATES; In the process proper: case state is when waiting => Ok, so what happens when we're waiting for an enable? It would be a good idea to set all (driven) variables to a known value. This means that maybe something like this is a good idea: shift_counter := 0; temp_reg <= parallel_in; s_out <= '0'; This is useful to do because then you know exactly what your signal values are when enable goes high. Also, at the end of the shift, you can change states back to "waiting" in order to get ready for enable again. So what is going to trigger a state change from waiting to shifting ? That's easy: if(enable = '1') then state <= shifting; else state <= waiting; end if; Ok, so next state. shifting. First, we want to increment the shift counter, and perform the actual shift: when shifting => shift_counter := shift_counter + 1; s_out <= temp_reg(0); temp_reg <= s_in & temp_reg(n-1 downto 1); And then also detect when the shifting is done, in order to leave the shift state and go back to waiting: if (shift_counter >= n-1) then state <= waiting; else state <= shifting; end if; And that's it! In the below chunk of code, note that the "reset" state and the "waiting" state are distinct. This is useful because generally the asynchronous reset only occurs at startup and is not expected to process any data during this time. By moving the temp_reg <= parallel_in to the waiting state (outside of the asynchronous reset), we are allowing the module driving parallel_in to start up correctly without having to send data during reset. Also, now the waiting state can be entered as necessary, without having to perform an asynchronous reset. Also notice that I'm only driving 3 signals (4 counting the variable) in my process, and only those signals. If a signal is driven in one process, it shouldn't be driven anywhere else but that process. Not outside the process, not in another process. A signal is driven inside one process and one process only. You can compare the signal to other signals in other places (if statements, and such), but don't give the signal a value anywhere except in one process. And generally, it is defined in the reset portion, and then wherever necessary in the process proper. But only 1 process. If I'd been told this, it would have saved me tons of time while I was learning. Here's the whole code in one chunk: library ieee; use ieee.std_logic_1164.all; entity SReg is generic ( n : integer := 4); port( clk: in std_logic; reset: in std_logic; enable: in std_logic; --enables shifting parallel_in: in std_logic_vector(n-1 downto 0); s_in: in std_logic; --serial input s_out: out std_logic --serial output ); end SReg; architecture behavioral of SReg is signal temp_reg: std_logic_vector(n-1 downto 0) := (Others => '0'); TYPE POSSIBLE_STATES IS (waiting, shifting); signal state : POSSIBLE_STATES; begin process(clk,reset) variable shift_counter: integer := 0; begin if(reset = '1') then temp_reg <= (others => '0'); state <= waiting; shift_counter := 0; elsif(clk'event and clk='1') then case state is when waiting => shift_counter := 0; temp_reg <= parallel_in; s_out <= '0'; if(enable = '1') then state <= shifting; else state <= waiting; end if; when shifting => shift_counter := shift_counter + 1; s_out <= temp_reg(0); temp_reg <= s_in & temp_reg(n-1 downto 1); if (shift_counter >= n-1) then state <= waiting; else state <= shifting; end if; end case; end if; end process; end behavioral;
{ "pile_set_name": "StackExchange" }
Q: "org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean" Using docker I am trying to get docker running on my AWS and using docker-compose. I run a maven build and everything builds successfully but when I do docker-compose up, I am getting this feign exception, saying my businessDelegate is not autowiring because my feign service is getting a parameter 0 Here is my delegate class @Component public class BusinessDelegateImpl implements BusinessDelegate{ private ShippingService shippingService; @Autowired public void setShippingService(ShippingService shippingService) {this.shippingService = shippingService;} /**More Methods below**/ } Simple right? Everything is wired correctly as far as I can see. Here is my feign client class @FeignClient("shipping") public interface ShippingService { @RequestMapping(value = "/insert", method = RequestMethod.POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE) ResponseEntity<Shipping> insert(@RequestBody Shipping shipping); @RequestMapping(value = "/save", method = RequestMethod.PUT, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE) ResponseEntity<Shipping> save(@RequestBody Shipping shipping); @RequestMapping(value = "/cart/{cartId}", method = RequestMethod.GET, produces= MediaType.APPLICATION_JSON_VALUE) ResponseEntity<Shipping> findByCartId(@PathVariable("cartId") String cartId); @RequestMapping(value = "/invoice/{invoiceId}", method = RequestMethod.GET, produces= MediaType.APPLICATION_JSON_VALUE) ResponseEntity<Shipping> findByInvoiceId(@PathVariable("invoiceId") String invoiceId); @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE) ResponseEntity delete(@PathVariable("id") String id); } I had this error locally but I fixed it by putting the variable next to the PathVariable @PathVariable("id"). Now i am getting this whenever i start up a docker in AWS. The mvn build runs too. Here is the complete Stack trace if you need it. Shopping is the name of the SprintBootApp shopping | org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'businessDelegateImpl': Unsatisfied dependency expressed through method 'setShippingService' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.revature.service.implementation.ShippingService': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: PathVariable annotation was empty on param 0. shopping | at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:671) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.b eans.factory.support. AbstractAutowireCapab leBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.2.RELEASE.jar!/:1.4.2.RELEASE] shopping | at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.2.RELEASE.jar!/:1.4.2.RELEASE] shopping | at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.2.RELEASE.jar!/:1.4.2.RELEASE] shopping | at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.2.RELEASE.jar!/:1.4.2.RELEASE] shopping | at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.2.RELEASE.jar!/:1.4.2.RELEASE] shopping | at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.2.RELEASE.jar!/:1.4.2.RELEASE] shopping | at com.revature.ApigatewayApplication.main(ApigatewayApplication.java:15) [classes!/:0.0.1-SNAPSHOT] shopping | at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111] shopping | at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_111] shopping | at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_111] shopping | at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_111] shopping | at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) [apigateway.jar:0.0.1-SNAPSHOT] shopping | at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) [apigateway.jar:0.0.1-SNAPSHOT] shopping | at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) [apigateway.jar:0.0.1-SNAPSHOT] shopping | at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:58) [apigateway.jar:0.0.1-SNAPSHOT] shopping | Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.revature.service.implementation.ShippingService': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: PathVariable annotation was empty on param 0. shopping | at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:175) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:103) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1606) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:254) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1289) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1258) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1094) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:663) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | ... 27 common frames omitted shopping | Caused by: java.lang.IllegalStateException: PathVariable annotation was empty on param 0. shopping | at feign.Util.checkState(Util.java:128) ~[feign-core-9.3.1.jar!/:na] shopping | at org.springframework.cloud.netflix.feign.annotation.PathVariableParameterProcessor.processArgument(PathVariableParameterProcessor.java:49) ~[spring-cloud-netflix-core-1.2.5.RELEASE.jar!/:1.2.5.RELEASE] shopping | at org.springframework.cloud.netflix.feign.support.SpringMvcContract.processAnnotationsOnParameter(SpringMvcContract.java:237) ~[spring-cloud-netflix-core-1.2.5.RELEASE.jar!/:1.2.5.RELEASE] shopping | at feign.Contract$BaseContract.parseAndValidateMetadata(Contract.java:107) ~[feign-core-9.3.1.jar!/:na] shopping | at org.springframework.cloud.netflix.feign.support.SpringMvcContract.parseAndValidateMetadata(SpringMvcContract.java:133) ~[spring-cloud-netflix-core-1.2.5.RELEASE.jar!/:1.2.5.RELEASE] shopping | at feign.Contract$BaseContract.parseAndValidatateMetadata(Contract.java:64) ~[feign-core-9.3.1.jar!/:na] shopping | at feign.hystrix.HystrixDelegatingContract.parseAndValidatateMetadata(HystrixDelegatingContract.java:34) ~[feign-hystrix-9.3.1.jar!/:na] shopping | at feign.ReflectiveFeign$ParseHandlersByName.apply(ReflectiveFeign.java:146) ~[feign-core-9.3.1.jar!/:na] shopping | at feign.ReflectiveFeign.newInstance(ReflectiveFeign.java:53) ~[feign-core-9.3.1.jar!/:na] shopping | at feign.Feign$Builder.target(Feign.java:209) ~[feign-core-9.3.1.jar!/:na] shopping | at org.springframework.cloud.netflix.feign.HystrixTargeter.target(HystrixTargeter.java:48) ~[spring-cloud-netflix-core-1.2.5.RELEASE.jar!/:1.2.5.RELEASE] shopping | at org.springframework.cloud.netflix.feign.FeignClientFactoryBean.loadBalance(FeignClientFactoryBean.java:146) ~[spring-cloud-netflix-core-1.2.5.RELEASE.jar!/:1.2.5.RELEASE] shopping | at org.springframework.cloud.netflix.feign.FeignClientFactoryBean.getObject(FeignClientFactoryBean.java:167) ~[spring-cloud-netflix-core-1.2.5.RELEASE.jar!/:1.2.5.RELEASE] shopping | at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:168) ~[spring-beans-4.3.4.RELEASE.jar!/:4.3.4.RELEASE] shopping | ... 37 common frames omitted shopping | shopping exited with code 1 If you need more information, please let me know. I have be stuck on this for hours A: I found the issue. I needed to remove the images first and recreate it. For anyone that doesn't know how to delete images, first you need to delete the container such as docker rm <Container Id> or remove them all at once docker rm $(docker ps -a -q) then you can delete the images docker rmi <Image Id> or remove all at once docker rmi $(docker images -a -q) To get the Ids, enter docker ps -a for container Ids and docker images for image Ids Alternatively, if you have docker-compose installed, you can rebuild the images with the commands docker-compose up -d --build docker-compose pull docker-compose up
{ "pile_set_name": "StackExchange" }
Q: Installing Windows 7 using Virtual Box without having a CD I would like to create a windows 7 virtual machine on my computer, but I don't have my install disk. I currently have it installed on my computer in a dual boot with ubuntu 11.04 and was wondering if there is a way to create a virtual machine using the already installed version, without needing to procure a CD with windows 7 on it. I am reasonably tech savy but would not consider myself an expert by any means. If this is possible, would it be very difficult, and would there be any way to make it easier? A: Yes, it's possible, but it's not easy. You can check this guide in the VirtualBox Forum: http://forums.virtualbox.org/viewtopic.php?t=33356 Note that this is quite offtopic and not Ubuntu related (it's a windows thing), you will be able to obtain more and better help in the Virtualbox forum or in some Windows site.
{ "pile_set_name": "StackExchange" }
Q: What closing a kotlinx.coroutines channel does What closing a kotlinx.coroutines channel using channel.close() does and what the negative effect of not manually closing channels would be? If I don't manually close a channel will there be some unnecessary processing? Will there be a reference to the channel somewhere that prevents it from being GCd? Or does the close function just exist as a way of informing potential users of the channel that it can no longer be used. (Question reposted from Kotlin forum https://discuss.kotlinlang.org/t/closing-coroutine-channels/2549) A: Closing a channel conceptually works by sending a special "close token" over this channel. You close a channel when you have a finite sequence of elements to be processed by consumers and you must signal to the consumers that this sequence is over. You don't have to close a channel otherwise. Channels are not tied to any native resource and they don't have to be closed to release their memory. Simply dropping all the references to a channel is fine. GC will come to do clean it up.
{ "pile_set_name": "StackExchange" }
Q: Setting function with setInterval() to act at some value I've created start() function which counts from 1 onwards. I want it to do something after some time pass, for example 5 seconds. How to achieve that? I've tried with if (timecounter == 5) but that doesn't work. If I put while (timecounter < 5) {continue} and then the if statement from above, I get into infinite loop. function start() { setInterval(function () { timecounter = timecounter + 1; document.getElementById('demo').innerHTML = timecounter; }, 1000); var clickArea = document.getElementById('clickBox'); document.getElementById('boxText').style.color = 'white'; clickArea.addEventListener("click", function () { counter += 1; }); if (timecounter === 5) { alert('this'); } //Doesn't work } Thanks. A: Like a few people mentioned in the comments; your test needs to be called whenever timecounter is incremented. http://jsfiddle.net/John_C/bsAfp/ function start() { var timecounter = 0; setInterval(function () { timecounter = timecounter + 1; document.getElementById('demo').innerHTML = timecounter; if (timecounter === 5){ alert('this'); } //works now }, 1000); } start();
{ "pile_set_name": "StackExchange" }
Q: A letter contained in a string value in an array is replaced by the value of a variable with that letter's name I have an array: $path_r = array("/oldsites/web-sites","/oldsites/web_elements","/oldsites/web_old_stuff"); I do a bunch of stuff to it and everything is fine until this line of code: $path_r[$i][$j] = $name; Just prior to that line, the array ($path_r) looks like this (same as above): Array ( [0] => /oldsites/web-sites [1] => /oldsites/web_elements [2] => /oldsites/web_old_stuff ) But, just after, it looks like this: Array ( [0] => /olds0tes/web-sites [1] => /oldsites/web_elements [2] => /oldsites/web_old_stuff ) That is to say, the letter "i" in the first value is replaced by the value (zero) of the variable $i. But only once. Can't figure out why. Am I doing something wrong or is it just run-of-the-mill demonic activity? A: As you said "I do a bunch of stuff to it and everything is fine until this line of code:", so we don't know what's going on there in your code. One logical explanation why this happens is given below:- When you write:- $path_r[$i][$j] it's become something like :- "/oldsites/web-sites"[$j] (if $i = 0; // for an example), and this expression exactly means substr($string, int, $j) (based on this link explanation:- https://stackoverflow.com/a/17193651/4248328) So basically $path_r[$i][$j] = $name; is mean that assign $name at the place of $path_r[$i][$j] which is actually substr($string, int, $j) To understand it easily, check this link:- https://eval.in/653580 Conclusion:- Something like above happens in your code. Not exactly as above, but something similar like that one.
{ "pile_set_name": "StackExchange" }
Q: VolleyError doesnt give response I am using the code below to notify the user about the an error: new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error instanceof TimeoutError || error instanceof NoConnectionError) { Toast.makeText(LoginActivity.this,"Keine Internetverbindung", Toast.LENGTH_LONG).show(); } else if (error instanceof AuthFailureError) { // TODO } else if (error instanceof ServerError) { // TODO } else if (error instanceof NetworkError) { // TODO } else if (error instanceof ParseError) { // TODO } } } When I start the Application and shut down all the connections I don't get the Toast. There should be the NoConnectionError-Toast, but nothing happens. A: Unless you have missed to include <uses-permission android:name="android.permission.INTERNET" /> in your manifest file you should ideally get NoConnectionError if there is no internet connection. In case, no wifi, no 2G,3G, etc, I have else you would get if you have not declared Internet permission in AndroidManifest.xml See if this helps!
{ "pile_set_name": "StackExchange" }
Q: How to switch from using scenes to just using timeline with one scene My partner and I are working on a project in which we must develop a simple game and also have two videos e.g. museum interface. We have built a home page(scene 1) which just contains an ENTER button, we then have a Menu page(Scene 2) which contains three buttons for Video 1, Video 2 and Game. We have been told that we should not use scenes so we want to put both scenes on one timeline and also subsequent scenes. Is there a simple way to take the scene 2 and put it on the timeline of scene 1? A: You're going to need to manage the visibility of each of the pages. Start the app with page1.visible = true and page2.visible = false. When the user clicks the play button swap these values. That way both pages are on the stage at the same time and you don't have to use scenes. Depending on how complicated or how many pages you end up using you might want to look into MVC (Model/View/Controller) Architectural designs. They handle multiple views well in any language. Flash is different in that it has built in ways to handle the UI that can make it easy to do simple things, but as soon as it starts to get big, it doesn't scale well.
{ "pile_set_name": "StackExchange" }
Q: Cassandra in-memory configuration We currently evaluate the use of Apache Cassandra 1.2 as a large scale data processing solution. As our application is read-intensive and to provide users with the fastest possible response time we would like to configure Apache Cassandra to keep all data in-memory. Is it enough to set the storage option caching to rows_only on all column families and giving each Cassandra node sufficient memory to hold its data portion? Or are there other possibilities for Cassandra ? A: Read performance tuning is much complex than write. Base on my experiences, there are some factors you can take into consideration. Some point of view are not memory related, but they also help improve the read performance. 1.Row Cache: avoid disk hit, but enable it only if the rows are not updated frequently. You could also enable the off-heap row cache to reduce the JVM heap usage. 2.Key Cache: enable by default, no need to disable it. It avoid disk searching when row cache is not hit. 3.Reduce the frequency of memtable flush: adjust memtable_total_space_in_mb, commitlog_total_space_in_mb, flush_largest_memtables_at 4.Using LeveledCompactionStrategy: avoid a row spread across multiple SSTables.
{ "pile_set_name": "StackExchange" }
Q: Brownie cannot install solc on OSX Follow the procedures on this page brownie : create new project and compile with brownie. Encounter the following error, please comment how to fix it. Configuration and environment. Python 3.7.7 ganache-cli 6.14.5 (.token-venv) MacBookPro:token nelson$ brownie compile Brownie v1.9.2 - Python development framework for Ethereum ..... [ 60%] Linking CXX executable solc File "brownie/_cli/__main__.py", line 58, in main importlib.import_module(f"brownie._cli.{cmd}").main() File "brownie/_cli/compile.py", line 37, in main project.load() File "brownie/project/main.py", line 656, in load return Project(name, project_path) File "brownie/project/main.py", line 160, in __init__ self.load() File "brownie/project/main.py", line 213, in load self._compile(changed, self._compiler_config, False) File "brownie/project/main.py", line 96, in _compile optimizer=compiler_config["solc"].get("optimizer", None), File "brownie/project/compiler/__init__.py", line 97, in compile_and_format find_solc_versions(solc_sources, install_needed=True, silent=silent) File "brownie/project/compiler/solidity.py", line 158, in find_solc_versions install_solc(*to_install) File "brownie/project/compiler/solidity.py", line 90, in install_solc solcx.install_solc(str(version), show_progress=True) File "solcx/install.py", line 229, in install_solc _install_solc_osx(version, allow_osx, show_progress, solcx_binary_path) File "solcx/install.py", line 374, in _install_solc_osx "".format(cmd[0], e.returncode) OSError: make returned non-zero exit status 2 while attempting to build solc from the source. This is likely due to a missing or incorrect version of a build dependency. For suggested installation options: https://github.com/iamdefinitelyahuman/py-solc-x/wiki/Installing-Solidity-on-OSX A: The issue is coming from a dependency of Brownie called py-solc-x. From the py-solc-x wiki: The Solidity team does not provide binaries for use with macOS/Darwin. For this reason, py-solc-x attempts to install Solidity on OSX by building it from the source code. Sometimes older versions of Solidity fail to build due to incompatible versions of one or more dependencies. There are two possible solutions: Build via brew Use 3rd-party precompiled binaries 1. Building via Homebrew Brownie will make use of any Solidity versions installed using brew: brew update brew upgrade brew tap ethereum/ethereum brew install solidity To install the most recent 0.4.x / 0.5.x version of Solidity you can also use brew install solidity@4 and brew install solidity@5, respectively. To install an older version, you can use a Homebrew formula directly from Github: Find the commit in ethereum/homebrew-ethereum which references the version you wish to install Navigate the repository until you have the raw file link for solidity.rb at that commit. Install it using brew: brew unlink solidity # e.g. to install v0.5.6 brew install https://raw.githubusercontent.com/ethereum/homebrew-ethereum/1ecf6c60875740133ee51f6167aef9a4f05986e7/solidity.rb 2. Installing Third-Party Binaries The web3j team provides compiled OSX binaries for many versions of Solidity. To use a third-party binary: Download the desired version from web3j/solidity-darwin-binaries Rename the file to solc-v0.x.y where x and ycorrespond to the minor and patch version. Move the file to the ~/.solcx directory on your system. It will now be available for use in Brownie.
{ "pile_set_name": "StackExchange" }
Q: Module not found: Can't resolve 'heatmap-calendar-react' I've created a component that worked fine in my local App, but I'm trying to get it work on npm and I am getting this error: ./src/App.js Module not found: Can't resolve 'heatmap-calendar-react' in 'C:\Users\account\app\src' Could somebody please take a look at my repository and help me understand what the issue may be? https://github.com/willfretwell/heatmap-calendar-react Any help would be greatly appreciated. A: Solved, I had a typo in the main declaration.
{ "pile_set_name": "StackExchange" }
Q: Photoshop Local Zoom? Is there anyway to zoom in on only a portion of an image without enlarging the entire document? I know that you can create a second window for the same document, put the windows side by side, and zoom in on the second window, however you can't see the cursor, and the changes don't update in real time. What I have in mind would be kind of like a magnifying glass effect, and the purpose would be to make detailed adjustments or selections, while still viewing the whole document. If this is possible, maybe it requires a script or 3rd party application? Thank you for your help! A: You might find the navigator window helpful. You can pull the window off the tabs, and resize. When you zoom in on the image the navigator displays where you are in the image. It also updates immediately. I often use this functionality when retouching. You can also drag the square around the navigator window, and the main window will move to that position. A: Local zoom isn't a feature in Photoshop. This has been a requested feature for some time from Adobe. The easiest solution to your problem is to use the Windows Magnifier. It has a "lens" mode that works like what you are looking for. Additionally there are a plethora of freeware options that you could try that might have some better smoothing to avoid the pixelated "stepped" look of zooming in.
{ "pile_set_name": "StackExchange" }
Q: Dynamically load all names from module in Python How do I do from some.module import * where name of the module is defined in a string variable? A: This code imports all symbols from os: import importlib # Load the module as `module' module = importlib.import_module("os") # Now extract the attributes into the locals() namespace, as `from .. # import *' would do if hasattr(module, "__all__"): # A module can define __all__ to explicitly define which names # are imported by the `.. import *' statement attrs = { key: getattr(module, key) for key in module.__all__ } else: # Otherwise, the statement imports all names that do not start with # an underscore attrs = { key: value for key, value in module.__dict__.items() if key[0] != "_" } # Copy the attibutes into the locals() namespace locals().update(attrs) See e.g. this question for more information on the logic behind the from ... import * operation. Now while this works, you should not use this code. It is already considered bad practice to import all symbols from a named module, but it certainly is even worse to do this with a user-given name. Search for PHP's register_globals if you need a hint for what could go wrong.
{ "pile_set_name": "StackExchange" }
Q: Nurikabe: Build it yourself This is a Nurikabe puzzle. First form a 16 × 16 grid using the provided squares, then solve the grid by shading some cells so that the resulting grid satisfies the rules1 of Nurikabe: Numbered cells are unshaded. Unshaded cells are divided into regions, all of which contain exactly one number. The number indicates how many unshaded cells there are in that region. Regions of unshaded cells cannot be adjacent to one another, but they may touch at a corner. All shaded cells must be connected. There are no groups of shaded cells that form a 2 × 2 square anywhere in the grid. 1 Paraphrased from the original rules on Nikoli. A: Solution First, let's make some observations for assembly: Red quadrant cannot be on the right, or else the 5-1-5 in the top right corner would lead to a shaded cell not being able to escape. Likewise, Yellow quadrant cannot be on the left due to the 2-2 bottom-left. In fact, neither Yellow nor White can be to the right of Red, since the top row prohibits this (since two clues can never be adjacent to each other since they must be in different islands). So: Blue must be to the right of Red, and Yellow must be to the left of White. And now, Blue cannot be on top of White, due to their first column. So we can finish our grid as follows: Now, time to solve the puzzle: Initial deductions: Extend shaded squares: We can more or less complete the yellow quadrant like this: Bottom right 6 cannot escape left, and must go up at least a few: Likewise R15C12 5 needs to go up at least one. Let's focus on the red quadrant now. The bottom left corner 2x2 is only reachable by the 3, so the 3 must go there. Same goes for the R(10-11)C(1-2); it must be addressed by the 5. In fact R(12-13)C(3-4) must be addressed by the 2, and the R(12-13)C(4-5) must be addressed by the 7. This uses up all of the 7's length, so the 7 must only go left and a single up. By column 7 it must have already gone up, so it looks like this now. This finishes the 2, and also the 5 in R16C9 only has 5 squares to go, so it fills that. So 7 goes up at the very beginning and thus it is also completed. Then 5 and 6 resolve: Let's focus our efforts on the 8. It seems as if it has lots of space, but this is not really true. For one, it cannot touch the right border, or else the bottom right shaded cells cannot escape. Also since R11C14 is unshaded, R11C15 is shaded to allow for that mass to escape. So this means the 8 really only has 8 squares it can occupy. 7 must escape like this: The 2's must resolve like this. We use the shape of the 7 blocking several shaded cells, plus the fact that if a 2 has only 2 places to go then something blocking both is shaded. That resolves the central 5, also in order to escape the bottom right mass must escape between the 7 and the 5. This resolves the rightmost 5 as well. The R4C7 5 must address R6C5 and goes down. So it can't go up, so the R1C6 2 needs to address R(2-3)C(5-6) so it must go down. Furthermore this resolves the R5C9 2. That finishes up the 7. The 6 cannot touch the top border or else the right shaded mass gets isolated. So it resolves like that. So R1C9 3 resolves like this to avoid 2x2. The R6C5 which we've identified as going to the 5 must go right and never down, so R7C6 is shaded. R9C4 3 must resolve like this, or else it goes flat, which makes a 2x2. Since R8C9 is unshaded R7C9 is shaded so that mass can escape. The 5's must finish resolving like this to connect the shaded cells, complete!
{ "pile_set_name": "StackExchange" }
Q: What do I need to change in my _form.html.erb or controller? I have this in my listings controller: # GET /listings/new def new @options_for_select_ary = Subcategory.all.map{|subcategory| subcategory.subcategory_name} @listing = Listing.new end # GET /listings/1/edit def edit @options_for_select_ary = Subcategory.all.map{|subcategory| subcategory.subcategory_name} end ..and this in my _form.html.erb: <div class="field"> <%= f.label :subcategory %> <%= f.select :subcategory, options_for_select([@options_for_select_ary]) %> </div> ...it works, however, it only has one option available in the drop down. Where or what do I need to change to make it display all of the subcategories? Any help much appreciated... A: You don't need to pass the values in Array. map always returns you an array. Replace the following <%= f.select :subcategory, options_for_select([@options_for_select_ary]) %> with <%= f.select :subcategory, options_for_select(@options_for_select_ary) %> Also, you might want to change the below code # GET /listings/new def new @options_for_select_ary = Subcategory.pluck(:subcategory_name) @listing = Listing.new end # GET /listings/1/edit def edit @options_for_select_ary = Subcategory.pluck(:subcategory_name) end Or better move it to an before_action before_action :set_options, only: [:new, :edit] # GET /listings/new def new @listing = Listing.new end # GET /listings/1/edit def edit end private def set_options @options_for_select_ary = Subcategory.pluck(:subcategory_name) end EDIT undefined method `map' for nil:NilClass you might want to add :update and :create in before_action before_action :set_options, only: [:new, :edit, :create, :update]
{ "pile_set_name": "StackExchange" }
Q: getting Undefined property: stdClass::$insertion when try to parse JSON array i have this json on which i try to extract the insertion-orders array { "response" : { "status" : "OK", "count" : 1, "insertion-orders" : [{ "id" : 5, "name" : "First Choice", "code" : null, "state" : "active", "line_items" : [{ "id" :352, "timezone" : "Europe/London" }, { "id" :358, "timezone" : "Europe/London" } ], "labels" : null, "safety_pacing" : true } ] } } what im doing is TheJson is the json string: $Json = json_decode($TheJson); $JsonResponse = $Json->response; $OrdersArray = $JsonResponse->insertion-orders; the error im getting is : Notice: Undefined property: stdClass::$insertion in /home/foo/a/foo.com/user/htdocs/FunctionManager.php on line 16 Notice: Use of undefined constant orders - assumed 'orders' in /home/foo/a/foo.com/user/htdocs/FunctionManager.php on line 16 line 16 is : $OrdersArray = $JsonResponse->insertion-orders; i just don't get it , its valid json A: $JsonResponse->insertion-orders; is parsed as $JSonResponse->insert MINUS orders You can't use - in an object attribute name using the arrow notation. It'll have to be $JsonResponse->{'insertion-orders'} instead. As for your comment about it being valid JSON, it wouldn't have worked in Javascript either: json.insertion-orders will also be seen as json.insertion MINUS orders.
{ "pile_set_name": "StackExchange" }
Q: Regex for legal citations I have read countless tutorials and found the free, online regex tester, a great resource, but still cannot fashion the proper regular expression to capture legal case citations in this format. State v. Starks, 196 Ohio App.3d 589, 2011-Ohio-2344. I was able to divine this: (?!.*\d) to capture only to the last number in the string above, but then it stops at the 196 above instead of proceeding to the last number in the string following Ohio- which is what I want it to do. Any regex experts out there can help me with this one? A: Regex: ^.*?(?:\d+\D+)*(\d+) Demo Explanation: Fully matches the legal citation with capture group 1 having the last numbers.
{ "pile_set_name": "StackExchange" }
Q: How to have a primary key with a different name than "Id" I have the following situation in my ASP.NET Core application with Entity Framework Core 1.1 Database-Table named "Content" Content_ID (int not null, primary key) Title (varchar max) Description (varchar max) Model ("ContentEntry.cs"): public class ContentEntry { public int Id {get; set;} public string Title {get; set;} public string Description {get; set;} } Configuration File (ContentEntryConfiguration.cs) public class ContentEntryConfiguration : IEntityMappingConfiguration<ContentEntry> { public void Map(EntityTypeBuilder<ContentEntry> modelBuilder) { modelBuilder.HasKey(m => m.Id); modelBuilder.Property(m => m.Id).HasColumnName("Content_ID"); modelBuilder.Property(m => m.Title ).HasColumnName("Title"); modelBuilder.Property(m => m.Description).HasColumnName("Description"); modelBuilder.ToTable("Content"); } } As mentioned above, the primary key of my table is named "Content_ID". When I execute a LINQ query, I receive an error saying that the column "ID" hasn't been found on the database. After inspecting the generated query with the SQL Profiler, I noticed that the query contains "ID" instead of "Content_ID". I expect entity framework to generate a query containing the column "Column_ID" instead and map it to my model-property named "Id". Do you have an idea why this is happening and how I could fix this issue? A: I solved it, I just forgot to register the entity mapping in my DB Context Class: protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.RegisterEntityMapping<ContentEntry, ContentEntryConfiguration>(); }
{ "pile_set_name": "StackExchange" }
Q: Jfrog Xray: Unable to generate Security Report I have setup a new instance of jFrog-xray and configured artifacts. The "Security Report" button is not enabled. What do I need to do to ensure the button is enabled? NOTE: The question is wrongly tagged since jfrog-xray is not an existing tag and mission-control is the closest (product from same company) A: Once you will have some alerts and Xray will find some vulnerabilities the button will be available to you.
{ "pile_set_name": "StackExchange" }
Q: Leaflet Map not showing in bootstrap div This is a super odd problem that I can not figure out. I have my div with the map and its css styling. The Leaflet map is showing up in one rectangle and not in the div. Its as if the z index is wrong, but I can not figure it out. The JS is in the document.ready function. I added a border around the map div just to show how off everything is. CSS: #map {width:100%;height:100%;margin-left:10px;margin-top:40px} HTML: <div id="showTravel" class="row" style="display:none"> <div class="col-lg-12"> <div class="wrapper wrapper-content"> <h2 style="margin-top:-18px">All Travelers</h2> <div id="travelContent"> <div id=map></div> </div> </div> </div> </div> JS: var map=L.map('map',{ minZoom:2, maxZoom:18 }).setView([x,y],16); var buildingIcon=L.icon({ iconUrl:'/images/bicon.png', iconSize:[25,40], popupAnchor: [-3, -20], iconAnchor: [14, 38] }); L.marker(x,y],{ icon:buildingIcon, title:'town, state' }) .bindPopup('<b>first last</b><br>Email: email address<br>Cell: phone number') .addTo(map); mapLink='<a href="http://openstreetmap.org">OpenStreetMap</a>'; L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: 'Map data &copy; ' + mapLink, maxZoom:18 }).addTo(map); I have fixed the overlapping problem, but the last problem still exists i.e., When the page loads and the map is rendered on the document.ready() the map is only visible in the top left corner of the screen. And If I changes the size of the browser (maximize,minimize) then the map refreshes correctly. A: Execute the following function once the map is opened: map.invalidateSize(); This will fix your problem.
{ "pile_set_name": "StackExchange" }
Q: Whales and cancer Do whales get less cancer than they should considering they have a lot more cells and tissue? If a lot of cancer formation is random because of mutations then shouldn't whales receive a lot of cancerous growths? Is it partly because there's a lot more systems that can protect against pre-cancerous development and apoptosis degradation in the larger mammal than in a human being? A: Short answer: Yes/Maybe More detailed answer: If the rate of cancer was uniform across cells then you would expect large mammals to more frequently get cancer than small mammals, just like buying 10 lottery tickets is more likely to make you a winner than buying one ticket. However, this correlation between mass and cancer rates does not exist, and it's absence is called Peto's paradox. Some useful quotes from that paper: The incidence of cancer in humans stands at one in three [33%], whereas it is only 18% in beluga whales.... There are a number of different hypotheses,” says Carlo Maley, director of the Center for Evolution and Cancer at the University of California, San Francisco. “For example, rather than body mass influencing the number of tumour suppressors and oncogenes, maybe there are less reactive oxygen species in larger organisms due to their lower metabolic rate.... Some biologists question whether there is a paradox at all, saying that variations in cancer rates across species — which range between 20% and 46% — are more similar than different. “All species get cancer at about the same rate, typically in the latter part of life span,” says James DeGregori, a molecular biologist at the University of Colorado in Denver. “We simply don’t have the data yet to back up the notion that larger animals have come up with a way to avoid oncogenic mutations.”
{ "pile_set_name": "StackExchange" }
Q: Get windows identity before authentication ASP.net Dear stackoverflow community, Is there any way to retrieve windows username/identity even before authentication? To make you all understand the situation, I am currently migrating an old ASP.net application. Previous code works no problem but due to recent code migration, old code won't work anymore. I want this application to be a single sign-on instead of the user need to key in their username and password WHILE using Forms authentication method. It involves: Index.aspx HomePage.aspx Login.aspx Global.asax The application flow: Enter global.asax and check whether isAuthenticated is true or false, if false, enter Index.aspx, if true, extract all the user accessright into .isInroles If not authenticated, get the windows username, check the user exist in the application, and FormsAuthentication.RedirectFromLoginPage(username, False/True) and it will redirect to global.asax and redirect to Homepage. (This is where single sign-on should be. And if there's no identity it will return to Login.aspx page. User provide username and password and authenticate like normal. (This one works) The thing is, when you are using Forms Authentication, the identity will return blank until the user provide one. For example HttpContext.Current.User.Identity.Name and other few more. Is there any way to get the windows identity before authentication? If I change the web.config to windows authentication, it works perfectly fine but it require me to change the whole structure of the system because the way the system gave access right is very outdated using cookies .IsInRoles and my team won't agree because of time consuming process. Sorry I can't post the code snippet due to data confidentiality... Any logical/pseudocode advice would be great. A: The answer to this question, I restructured back the whole program authentication by using Windows authentication, and removed the current global.asax and replace with the new one since the previous global.asax was corrupted that if I comment the whole code in the global.asax it enters. That solves my problem.
{ "pile_set_name": "StackExchange" }
Q: On the Steiner System S(4,5,11) Is there a nice way to partition the edges of the complete 5-uniform hypergraph on 11 vertices into 7 copies of the Steiner system S(4,5,11)? If this is obvious or elementary, I apologize in advance. A: Unfortunately, no. It is known that the maximum number of mutually disjoint $S(4,5,11)$s on the same point set is $2$. Any such pair are always isomorphic. So, you can't find $7$ disjoint copies of an $S(4,5,11)$ in the complete $5$-uniform hypergraph on $11$ vertices (or partition it into copies); you can find only two of them at most. E. S. Kramer, D. M. Mesner, Intersections among Steiner systems, J. Combin. Theory, Ser. A, 16 (1974), 273–285
{ "pile_set_name": "StackExchange" }
Q: First answer, then ask Lately I see a lot of new users with questions, most of which receive downvotes. Isn't it possible to let new users first answer a question to get reputation and when they have like 15 points, they can ask something? This because of the big amount of not useful posted questions. When you let a new user first answer a question to get reputation, they learn how to ask a question. When they get upvotes (reputation), you can see that the new user knows something about the subject. This instead of letting them ask every kind of question without realizing that using Google can be quicker or that they are spending our time wrong by asking stupid questions. I don't want to sound offensive and of course not every new user asks silly questions. But I think that there needs to be some kind of new filter to filter the spammers/ users that don't ask the right questions. I hope that I wrote my point clear enough for you to understand my frustrations. Example 1: There is a user (no names) Who has asked in the past hour 2 question with 7 down votes[closed] and 3 down votes[closed] (Not banned/Blocked) Example 2: An other user (no names) Who has asked in the past 24 hours 2 questions both closed and and down votes up to -8. I really hope somebody see this too and that there can be a solution for this problem. A: I don't think that would work. Users for the most part come to the site because they have questions. Not because they have answers. Putting up an answer-first hurdle would, in my view, do significant damage to the site. Either users will simply not join. After all, why join a site where you can not even ask your burning question? That's the problem you have now and want to address now. Not after some period of time gaining rep. Or users will start to post very poor answers in the desperate hope of gaining the two upvotes necessary to be able to ask questions. This does by no means help the quality. A: As a relative newcomer, this would have been disastrous - I have learnt alot from asking questions, from that, I am extending my knowledge of coding through experimenting and reading other questions (many from newbies). From this, eventually aftr my knowledge and confidence grows, I will be able to answer some questions and be able to help.
{ "pile_set_name": "StackExchange" }
Q: How to make a checkbox change its state when clicked? I have created a checkbox in WinAPI using the following code: HWND checkbox = CreateWindowEx(NULL, "BUTTON", "Click Me!", WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 10, 10, 60, 20, hWnd, NULL, hInstance, NULL); I expected the checkbox to change its state automatically when clicked, however it did not! I did not find any example on MSDN, so how can I make the checkbox change its state when clicked? should I handle the WM_COMMAND message and see what state it is in, and then change its state to the opposite one? A: Use the BS_AUTOCHECKBOX style instead of BS_CHECKBOX. Button Styles BS_AUTOCHECKBOX Creates a button that is the same as a check box, except that the check state automatically toggles between checked and cleared each time the user selects the check box. Button States Elements of a Button State A button's state can be characterized by its focus state, push state, and check state. ... Check State ... The system automatically changes the check state of an automatic button, but the application must change the check state of a non-automatic button. Changes to a Button State When the user selects a button, it is generally necessary to change one or more of the button's state elements. The system automatically changes ... the check state for all automatic buttons. The application must make all other state changes, taking into account the button's type, style, and current state.
{ "pile_set_name": "StackExchange" }
Q: Two-layer RAII to support a critical section For the code, if one considers using RAII to encapsulate CriticalSection (global scope), two RAII layers are needed: InitializeCriticalSection layer (main function scope), enter EnterCriticalSection layer (multi-thread based Proc scope). // Global variable CRITICAL_SECTION CriticalSection; int main( void ) { // Initialize the critical section one time only. if (!InitializeCriticalSection(&CriticalSection) ) return; ... // Release resources used by the critical section object. DeleteCriticalSection(&CriticalSection); } DWORD WINAPI ThreadProc( LPVOID lpParameter ) { // Request ownership of the critical section. EnterCriticalSection(&CriticalSection); // Access the shared resource. // Release ownership of the critical section. LeaveCriticalSection(&CriticalSection); return 1; } As CriticalSection and the two layers all have different scopes, and also enter InitializeCriticalSection layer must be on top of EnterCriticalSection layer. class CriticalSectionGuard { public: CriticalSectionGuard(CRITICAL_SECTION * cs) : m_CS(cs) { InitializeCriticalSection(m_CS); } ~CriticalSectionGuard() { DeleteCriticalSection(m_CS); } void lock() { EnterCriticalSection(m_CS); } void unlock{ LeaveCriticalSection(m_CS); } private: CRITICAL_SECTION * m_CS; } class GetLock { public: GetLock(CriticalSectionGuard* plock) : m_csg(plock) { m_csg->lock(); } ~GetLock(void) { m_csg->unlock(); } private: CriticalSectionGuard * m_csg; }; // Global variable CRITICAL_SECTION CriticalSection; int main(void) { // Initialize the critical section one time only. CriticalSectionGuard CSG(&CriticalSection); ... } DWORD WINAPI ThreadProc(LPVOID lpParameter) { // we need pass along the CSG Pointer, which is messy. GetLock(&CSG); ... return 1; } It looks quite bad, as the CriticalSectionGuard object is not in the global scope, it need pass along to threads. Please share any suggestions or criticisms to improve the code. A: We can simplify that a lot. You are not really using RAII on the CriticalSection as you declare it in one place then initialize it in another. But CRITICAL_SECTION is a type as you pass a pointer around. Why not simplify a bit: class GetLock; class CriticalSection { public: CriticalSection() { InitializeCriticalSection(&m_CS); // get a pointer to the member } ~CriticalSection() { DeleteCriticalSection(&m_CS); } private: friend class GetLock; // Only GetLock should be locking/unlocking this object. void lock() { EnterCriticalSection(&m_CS); } void unlock{ LeaveCriticalSection(&m_CS); } private: CRITICAL_SECTION m_CS; // Make this a member // Now make the constructor initialize it. } Now its use case becomes. CriticalSection criticalSection; int main() { // Critical section variable already up and running. } If we look at the GetLock. I would not passes pointers as parameters. This means people can accidentally pass a nullptr and thus cause your code to break. Always pass by reference if you have to have parameter there. class GetLock { public: // Pass a reference to the CriticalSection GetLock(CriticalSection& plock) : m_csg(plock) { m_csg.lock(); } ~GetLock(void) { m_csg.unlock(); } private: CriticalSectionGuard& m_csg; // Keep a reference to the critical section. }; Now this can be used like: DWORD WINAPI ThreadProc(LPVOID lpParameter) { GetLock lock(criticalSection); return 1; } Note the difference above to your version: GetLock(&CSG); // This creates a temporary object. // This object is destroyed at the end of the // statement (which is the ;). // This mean you call lock() and unlock() before // the end of the line. I should also note that using global variables is considered bad practice. You should try and design your program so that you pass the things being manipulated around as parameters (or part of an object). I can't really suggest an improvement with knowing more about the code.
{ "pile_set_name": "StackExchange" }
Q: Python: Parse all elements under a div I am trying to parse all elements under div using beautifulsoup the issue is that I don't know all the elements underneath the div prior to parsing. For example a div can have text data in paragraph mode and bullet format along with some href elements. Each url that I open can have different elements underneath the specific div class that I am looking at: example: url a can have following: <div class='content'> <p> Hello I have a link </p> <li> I have a bullet point <a href="foo.com">foo</a> </div> but url b can have <div class='content'> <p> I only have paragraph </p> </div> I started as doing something like this: content = souping_page.body.find('div', attrs={'class': 'content}) but how to go beyond this is little confuse. I was hoping to create one string from all the parse data as a end result. At the end I want the following string to be obtain from each example: Example 1: Final Output parse_data = Hello I have a link I have a bullet point parse_links = foo.com Example 2: Final Output parse_data = I only have paragraph A: You can get just the text of a text with element.get_text(): >>> from bs4 import BeautifulSoup >>> sample1 = BeautifulSoup('''\ ... <div class='content'> ... <p> Hello I have a link </p> ... ... <li> I have a bullet point ... ... <a href="foo.com">foo</a> ... </div> ... ''').find('div') >>> sample2 = BeautifulSoup('''\ ... <div class='content'> ... <p> I only have paragraph </p> ... ... </div> ... ''').find('div') >>> sample1.get_text() u'\n Hello I have a link \n I have a bullet point\n\nfoo\n' >>> sample2.get_text() u'\n I only have paragraph \n' or you can strip it down a little using element.stripped_strings: >>> ' '.join(sample1.stripped_strings) u'Hello I have a link I have a bullet point foo' >>> ' '.join(sample2.stripped_strings) u'I only have paragraph' To get all links, look for all a elements with href attributes and gather these in a list: >>> [a['href'] for a in sample1.find_all('a', href=True)] ['foo.com'] >>> [a['href'] for a in sample2.find_all('a', href=True)] [] The href=True argument limits the search to <a> tags that have a href attribute defined.
{ "pile_set_name": "StackExchange" }
Q: Which operations can be done in parallel without grabbing the GIL? I'm looking at embedding Python in a multi-threaded C++ program and doing simple computations using numpy in parallel. On other words, I'm using PyRun_SimpleString to call numpy functions. Is grabbing GIL required if I only write to existing numpy arrays, and take care not to modify the same array from different threads? Edit, as mentioned in comments, this was addressed here: Global Interpreter Lock and access to data (eg. for NumPy arrays) and a possible solution is to use numpy c interface directly using ctypes which takes care of releasing GIL: https://stackoverflow.com/a/5868051/419116 For posterity, here's what actually happens when you try to do "a*=2" without grabbing GIL: Program received signal SIGSEGV, Segmentation fault. 0x0000000000acc242 in PyImport_GetModuleDict () at python_runtime/v2_7/Python/import.c:433 433 PyInterpreterState *interp = PyThreadState_GET()->interp; #0 0x0000000000acc242 in PyImport_GetModuleDict () at python_runtime/v2_7/Python/import.c:433 #1 0x0000000000accca1 in PyImport_AddModule ( name=0x13e9255 <.L.str53> "__main__") at python_runtime/v2_7/Python/import.c:672 #2 0x0000000000aab29f in PyRun_SimpleStringFlags ( command=0x13e8831 <.L.str10> "a*=2", flags=0x0) at python_runtime/v2_7/Python/pythonrun.c:976 #3 0x00000000008e3300 in main (argc=1, argv=0x7fffd2226ec0) at python_embed/interactive_nogil.cc:56 Here PyThreadState_GET is macro for _PyThreadState_Current which is a null-pointer. So apparently grabbing the GIL also involves setting up some Thread variables which are needed for any Python operation A: The GIL is required for PyRun_SimpleString because it invokes the Python interpreter. If you use PyRun_SimpleString without owning the GIL the process will segfault. There are parts of the NumPy C API that do not require the GIL, but only the parts that do not touch Python objects or the interpreter. One example is the PyArray_DATA macro.
{ "pile_set_name": "StackExchange" }
Q: can I use question Mark(?) in querystring for GET request in Servicestack? I have created services stack, now when i fire GET request i.e localhost:123/myRest/ClassName/application/123456789?Count = 10 For above, 123456789 is the application Id [RestService("/perfmon/application/{applicationId}?Count = 10")] For my application, I got the actual result fine, but the problem is that when i try to check its JSON view, not able to see because it generate URL as below localhost:123/myRest/ClassName/application/123456789?Count = 10?format = json (two questionmark so it is wrong) When i change it to localhost:123/myRest/ClassName/application/123456789?Count = 10&format = json Can I control this when for ?format=Json. it gives me JSON output for my data This happens from the default view. (see below image) A: This is a bug in the HtmlFormat that is fixed in the latest version (v3.03) of ServiceStack. Download latest dlls at: https://github.com/ServiceStack/ServiceStack/downloads
{ "pile_set_name": "StackExchange" }
Q: How to get a date difference as a negative number in PHP? I have this code in php to get the difference between two dates. I'm getting the difference but it's always positive. I need the difference to be negative when the final date has passed. I've tried format(), invert, but nothing seems to work. function dias_transcurridos($fecha_i, $fecha_f) { $dias = (strtotime($fecha_i) - strtotime($fecha_f)) / 86400; $dias = abs($dias); $dias = floor($dias); return $dias; } $hoy = date('Y-m-d'); Then I call the code in my loop: $elPlazo = dias_transcurridos($row["DateEnd"], $hoy); echo "<td>" . $elPlazo . " Días</td>\n"; How can I get $elPlazo (the difference) as a negative number when the end date has passed today? A: The problem is that you have an abs in your code. abs will take the absolute value of any number (ie. remove the negative). Removing the abs will make your function return negative differences. A: I would also think about using the built-in PHP DateTime and DateInterval objects because they can handle things like leap days: <?php function dias_transcurridos($fecha_i, $fecha_f) { $i = new DateTime($fecha_i); $f = new DateTime($fecha_f); $interval = $i->diff($f); return $interval->days; }
{ "pile_set_name": "StackExchange" }
Q: Getting Remote Process Information with Powershell (w/o remoting) We have a bunch of PC that are not part of the domain (and cannot be added). They do not have PS installed and we'd prefer not to have to install it. I want to use Powershell from a server to get the memory usage of 2 process every hour. Unfortunately get-process doesn't seem to support a -credential parameter. I did get win32_process (as shown below), but it returns a ton of info (no idea how I'd just get VMsize for two processes). $Pass = ConvertTo-SecureString -string "SECRET" -AsPlainText –Force $User = "USER" $Cred = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $Pass gwmi win32_process -computername PCName -Credential $Cred Is there a way to do this without installing PS or putting PC's in domain? A: You can use the Filter parameter to limit the processes you get info on e.g.: Get-WmiObject -cn $c win32_process -Filter "Name='PowerShell.exe'" | ft Name, PrivatePageCount
{ "pile_set_name": "StackExchange" }
Q: I want to align the text which is present in div tag in the center which is coming from $scope.Message.But not able to align it When I try to align the text in center, I was not able to do the text is coming to left. Did I miss anything? $scope.message = "Hello Stack Overflow"; function abc(form){ $scope.message = "Hello Stack Overflow"; '<div align="center">{{message}}</div>' } A: You can do this in two different way $scope.message = "Hello Stack Overflow"; function abc(form){ $scope.message = "Hello Stack Overflow"; '<div style="text-align:center;">{{message}}</div>' } or you can define a class and add style in stylesheet $scope.message = "Hello Stack Overflow"; function abc(form){ $scope.message = "Hello Stack Overflow"; '<div class="text-center">{{message}}</div>' } <style> .text-center { text-align:center; } </style>
{ "pile_set_name": "StackExchange" }
Q: Understanding kinetic and potential energy A bullet with mass $8g$ flying at the speed of $v_0=600$ $m/s$ strikes an apple and comes out at the speed of $500$ $m/s$. Calculate the work ($A$) of the force exerted by the apple on the bullet. The answer given in my book is $A=\dfrac{m}{2}(v^2-v_0^2)=-440$ $J$. That is equal to $A=\dfrac{mv^2}{2}-\dfrac{mv_0^2}{2}=E_k-E{k_0}.$ Why don't they take account of the potential energy? According to the law of conservation of energy: $A=E-E_0$ where $E$ and $E_0$ are mechanicals energies (the sum of potential energy and kinetic energy). I think that $E=\dfrac{mv^2}{2}+mgh$ and $E=\dfrac{mv_0^2}{2}+mgh$, but I am not sure if $h$ changes. Thank you in advance! A: You are right to wonder about the possibility of a change in gravitational potential energy. Actually, the problem is poorly worded. The problem appears to apply the work energy theorem which states that the net work done on an object equals its change in kinetic energy. Note my emphasis on "net". Thats because there are two external forces acting on the bullet that can do work, the force by the apple and the force of gravity. The problem only asks for the work done by the apple. Although @Phoenix87 has shown that as a practical matter the effect of gravity would be negligible the problem should technically state the bullet enters and exits the apple at the same level or to equivalently state that the change in speed due to gravity is negligible. Then you would know the change in kinetic energy is due only to the work by the apple. Otherwise, there can be an increase in kinetic energy (increase in downward component of speed) due to positive work done by gravity. Alternatively to stipulating negligible speed change due to gravity or no change in height, the problem can simply ask what is the net work done on the bullet, which would mean the work done by the apple plus gravity. Then the equation applies without ambiguity. Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Array not being fully parsed in C program I am trying to build a program that parses an array of chars from input and then returns a formatted omitting extra whites spaces. #include <stdio.h> # include <ctype.h> /* count charecters in input; 1st version */ int main(void) { int ch, outp=0; char str[1000], nstr[1000]; /* collect the data string */ while ((ch = getchar()) != EOF && outp < 1000){ str[outp] = ch; outp++; } for (int j = 0; j < outp-1; j++){ printf("%c",str[j]); } printf("\n"); for (int q = 0; q < outp-1; q++) { if (isalpha(str[q]) && isspace(str[q+1])){ for(int i = 0; i < outp; i++){ if (isspace(str[i]) && isspace(i+1)){ continue; } nstr[i] = str[i]; } } } printf("\n"); printf("Formated Text: "); for (int i = 0; i < outp-1; i++){ printf("%c", nstr[i]); } //putchar("\n");c // printf("1"); return 0; } Here is my code. The array is never fully parsed, the end is usually omitted, odd chars show up and past attempts have yielded a not fully parsed array, Why? This is exercise 1-9 from "the C programming language". A: a) You need to use an additional index variable while copying the characters from str to nstr. Do something like - for(int i = 0, j = 0; i < outp -1; i++){ if (isspace(str[i]) && isspace(i+1)){ continue; } nstr[j++] = str[i]; } b) While you are printing nstr, you are using the length of the original string str. The length of nstr will be less than that of str since you have removed the spaces. You need to find the length of nstr now or use i < strlen(nstr) -1 in the condition.
{ "pile_set_name": "StackExchange" }
Q: Why are users other than admin profile not able to access object data? I have an object A. I created a new profile called Newprofile, which is basically a read only profile's clone, in which I have granted read permission to the custom object A only. Now i created a new user named called NewUser and assigned this profile Newprofile to it. Now I set public read to the object A in OWD(to my understanding thus granting read access to other owner's records). Now when I log in as Newuser I can see the tab(after enabling the tab visibility in the profile) but i am not able to see any data records. My Understanding of sharing in salesforce is that Profile is the baseline start, where permission set is used to grant more access when number of user(s) among the profile need extra access.Profile is only set for owner's own records. When we need to deal with other owner's records then comes in OWD, role and Sharing rule. since I have set OWD to Public read i thought i would have access to the object A data records from the new user NewU even though the owner is different, and since the profile has Read access to the object it should be able to read the records A: The default view of any object's tab is the "recent items" list. By default, this list is empty, since the user hasn't used any records yet. Instead, you need to go in to a List View to see records. In Classic, click on the "Go" button next to the View dropdown. In Lightning Experience, click on the Recently Viewed title and choose a List View. Once selected, the user will be able to see the records available for that object.
{ "pile_set_name": "StackExchange" }
Q: Update route not working on merged express router params I'm learning the MERN stack and encountered an issue on the edit route of my child router. I have the below model schemas in songs.js and students.js files: const mongoose = require('mongoose'); const studentSchema = mongoose.Schema({ name: { type: String, required: true }, instrument: String, songs: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Song' }] }); const Student = mongoose.model('Student', studentSchema); module.exports = Student; const mongoose = require('mongoose'); const songSchema = mongoose.Schema({ name: { type: String, required: true }, img: String }) const Song = mongoose.model('Song', songSchema); module.exports = Song And I have songs.js and students.js files for my routers, with mergeParams set to true for my songs router const songs = express.Router({ mergeParams: true });. I'm attaching it to the students router like this: students.use('/:id/songs', songs); e.g., my url parameters become students/student1/songs/song1 All of my other routes are working, but on the update route of my songs router I'm getting an error "TypeError: Student.findById is not a function" when I redirect back to the song's index view. My edit and update routes are below: songs.get('/:songId/edit', async (req, res) => { try { const findSong = Song.findById(req.params.songId); const findStudent = Student.findById = (req.params.id); const [foundSong, foundStudent] = await Promise.all([findSong, findStudent]); res.render('songs/edit', { student: foundStudent, song: foundSong }) } catch (err) { console.log(err); } }); songs.put('/:songId', async (req, res) => { try { const updateSong = await Song.findByIdAndUpdate(req.params.songId, req.body, { new: true }); res.redirect('/students/' + req.params.id + '/songs'); } catch (err) { console.log(err); } }); I'm not sure what's causing the error here, my delete route is set up similarly and is working. Would appreciate any suggestions. A: In your rote (req.params.id) is not defining. songs.get('/:songId/edit', async (req, res) => { try { const findSong = Song.findById(req.params.songId); **const findStudent = Student.findById = (req.params.id);** const [foundSong, foundStudent] = await Promise.all([findSong, findStudent]); res.render('songs/edit', { student: foundStudent, song: foundSong }) } catch (err) { console.log(err); } });
{ "pile_set_name": "StackExchange" }
Q: Can you change canvas style parameters multiple times between draw calls? I need to draw lots of rectangles with different stroke and fill colors. When working on proof of concept, I drew them all in a single context.stroke + context.fill call for a B/W representation. Now I need to make them all colorful and am stroking/filling them one by one and its making things slow down quite a bit. Is there a way to still do it in one call? A: No, any context.stroke()/context.fill() will only use the latest strokeStyle/fillStyle that's set at the time of the stroke/fill call. So you only get 1 color choice per stroke()/fill(). And yes, changing context state (like strokeStyle/fillStyle) is relatively costly in terms of performance. If many of your colorful objects have the same color, you will gain performance by drawing all the same colored objects at the same time. (Draw all the red objects, then draw all the blue objects, etc.)
{ "pile_set_name": "StackExchange" }
Q: how to split input to two pipes I would like to do something equivalent to this: some-expensive-command > /tmp/mytempfile grep -v "pattern" /tmp/mytempfile >> output.txt grep "pattern" /tmp/mytempfile | yet-another-command Preferably elegant and without the need for the tempfile. I was thinking about piping through tee, but the best I can think of might is to combine two of the three lines and still require the intermediate storage: some-expensive-command | tee /tmp/mytempfile | grep -v "pattern" >> output.txt grep "pattern" /tmp/mytempfile | yet-another-command A: The way question reads it sounds like you want one stdin redirected to two different commands. If that's the case, take advantage of tee plus process substitution: some-expensive-command | tee >(grep 'pattern' > output.txt) >(grep -v 'pattern' | another-command) Process substitutions are in fact anonymous pipelines implemented within bash itself ( on subprocess level ). We can also make the use of a named pipeline + tee. For instance, in terminal A do $ mkfifo named.fifo $ cat /etc/passwd | tee named.fifo | grep 'root' And in another terminal B do $ grep -v 'root' named.fifo Another way to look at this is by recognizing that grep is line pattern matching tool, so by reading line at a time and using that same line in multiple commands we can achieve exactly the same effect: rm output.txt # get rid of file so that we don't add old and new output some-expensive-command | while IFS= read -r line || [ -n "$line" ]; do printf "%s\n" "$line" | grep 'pattern' >> output.txt printf "%s\n" "$line" | grep -v 'pattern' | another-command done # or if another-command needs all of the output, # place `| another-comand` after `done` clause Yet another way is to abandon grep and use something more powerful, like awk: some-expensive-command | awk '/pattern/{print >> "output.txt"}; !/pattern/{print}' | another-command. Practically speaking, don't worry about using temporary files, so long as you clean them up after using. If it works, it works.
{ "pile_set_name": "StackExchange" }
Q: Neighbor Join Algorithm Output I'm trying to implement a Neighbor Joining algorithm, at the moment I have got it working as it should, calculating the correct lengths at each step and outputting the correct values. However, I am struggling with obtaining the final output of the algorithm, I need it to output the overall calculated matrix representation because I would like to represent it visually as a graph. Through each iteration of the main loop of the algorithm I get a sub group of nodes that goes back into the start of the algorithm, but I don't believe that this subgroup could be used because it contains redundant information that I can't really specify whether or not will be needed in the final representation. I am using this algorithm here: http://en.wikipedia.org/wiki/Neighbor_joining#The_algorithm Any help would be fantastic and I can provide more information if needed, thanks. A: I have read the link you provided and it seems to me that you do need the information. Each step of the algorithm merges 2 nodes into 1, making your distance matrix smaller until everything is merged. You need to remember the distances of the nodes you merge to their resulting node. If you merge A and B, then the columns/rows of your distance matrix are replaced by a column/row belonging to a new node, u. You need to remember the distances of A and B to u. After everything is merged, you should have all distances of all nodes that have to be connected and you can start visualizing.
{ "pile_set_name": "StackExchange" }
Q: How do the slows from Shadow Slash stack with multiple Living Shadows? From the tooltip: "Living Shadow: Overlapping Shadow Slashes striking the same enemy deal no additional damage but will incur an increased slow of 30 / 37.5 / 45 / 52.5 / 60% and restore energy." Is this a flat amount for both 1 Shadow + Zed and 2 Shadows + Zed? Or is the slow percentage different for 1 or 2 shadows? A: It's a flat amount. An enemy hit with a single shadow slash from a shadow will be slowed by 20 / 25 / 30 / 35 / 40%, and an enemy hit by multiple shadow slashes, no matter the amount will be slowed by 30 / 37.5 / 45 / 52.5 / 60%.
{ "pile_set_name": "StackExchange" }
Q: Postfix - how to retry delivery of mail in queue? I have a backup mail server in case of a failure on the main one. In that case of failure, mails come on the backup server and stay there until the main one is back. If I wait some times, the delivery will be done automatically as soon as the main server is back but it can be long. So how to force a send retry of all the mails? For exemple : postqueue -p : give me a list of mails I then tried postqueue -f (from man page : Flush the queue: attempt to deliver all queued mail.). It surely flushed the queue but mails were not been delivered... A: According to postqueue(1) you can simply run postqueue -f to flush your mail queue. If the mails aren't delivered after flushing the queue but are being requeued instead, you might want to check your mail logs for errors. Taking a peek at postsuper(1) might also be helpful. Maybe the messages are on hold and need to be released first. A: postqueue -f should work. If it does not, it has a good reason for that. Check the logs. Also pfqueue is a very useful command for inspecting mail spool. A: sendmail -q retries delivery of all mails in the queue immediately.
{ "pile_set_name": "StackExchange" }
Q: How can I replace a command-line SSH tool with a PHP web call? I'm building a web control that will let our junior IT staff manage firmware on our LifeSize phones. Currently we do this by uploading the new firmware onto a central server, then running this command for each phone we want to upgrade cat new_firmware.cramfs | ssh -T [email protected] "upgrade all" This asks me for the password, then uploads the firmware. Works like a champ, but it takes someone comfortable with CLI tools, SSH access to this server, and patience to look up all the IPs of all the phones. It looks like we're stuck with a password logon, testing with certificates has been disastrous. The device being acted on is not a full-fledged computer, it's a telephone running a tiny, proprietary embedded OS. I'm working on a PHP script that can iterate over all the phones, but basically duplicate that function. This is what I have so far: <?php $firmware_filename = "new_firmware.cramfs"; $firmware_stream = fopen($firmware_filename,"rb"); $ssh_connection = ssh2_connect("1.1.1.1", 22); ssh2_auth_password($ssh_connection, "cli", "password"); $ssh_stream = ssh2_exec($ssh_connection,'upgrade all'); $written = stream_copy_to_stream($firmware_stream,$ssh_stream,-1); if($written != filesize($full_filename)){ echo "The file is " . filesize($firmware_filename) . " bytes, I only wrote $written" . PHP_EOL; }else{ echo "All Good" . PHP_EOL; } ?> But this always returns The file is 26988590 bytes, I only wrote 8192 And the upgrade does not proceed correctly. A: Well you could simply call system('cat new_firmware.cramfs | ssh -T [email protected] "upgrade all"'); and then replace using your vars: system('cat ' . $firmware . ' | ssh -T ' . $username . '@' . $host . ' "upgrade all"'); is this a solution for you? you can automate the ssh-access by placing the certificate-file into .ssh-directory. Read about SSH login without password. regards
{ "pile_set_name": "StackExchange" }
Q: Loading a PHP page into a HTML div So I am currently trying to create a portion of my website that fetches a mySQL table. I wrote the php to fetch the data, create a table, and print out the table in a separate php file named display.php. Now i am trying to load it into a div on my html page but for some reason it is not working. I am using XAMPP and php is working as my login page works. Here is the code: HTML: (I have tried both include and require) <html> <body> <div id="display" class="myCustom1"> <?php require('display.php'); ?> </div> <div id="display" class="myCustom1"> <?php include("display.php"); ?> </div> </body> </html> PHP: (if i run just the php page it creates the table) <?php $servername = "localhost"; $username = "test"; $password = "test"; $database = "data1"; //create connection & access DB $connect = mysqli_connect("$servername","$username","$password","$database"); //if error, display error if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = mysqli_query($connect,"SELECT * FROM data1enter"); echo " <table border='1'> <tr> <th>Song</th> <th>Author</th> </tr> "; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['song'] . "</td>"; echo "<td>" . $row['author'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($connect); ?> A: You are using <?php ?> tags in the html file, Change the extension of the file containing the below code to .php from .html and you will be able to use include function. <html> <body> <div id="display" class="myCustom1"> <?php require('display.php'); ?> </div> <div id="display" class="myCustom1"> <?php include("display.php"); ?> </div> </body> </html> Also make sure the include path is correct. Hope it helps !
{ "pile_set_name": "StackExchange" }
Q: Как убедиться, что динамический массив монолитен в памяти? Всегда считал, что диспетчер памяти Delphi старается выделять под динамические массивы монолитные куски памяти. Так ли это? По нашей просьбе когда-то для нас создали API для Delphi 64. К прибору идёт DLL (без исходников, знаем, что часть расчётов написана на фортране, часть - выполняет прибор) с функциями, принимающими в качества параметров массив и его длину (в пятницу с коллегами был "глухой телефон", вот сейчас у меня перед глазами проект, непосредственно копирую из него). type TTaxInputIntData = record len: int64; rsrvd1, rsrvd2:integer; rsrvd3:double; data:array of integer; end; // универсальный массив для матрицы tSF: // len - ранг матрицы // data - матрица распределения, размер должен быть строго равен (len+2)*len, первый и последний столбцы - нулевые TStructureList = record rng: integer; rsrvd1, rsrvd2:integer; rsrvd3:double; data:array of byte; end; // возвращаемые значения: // rng: ранг матрицы таксономии // размер data = rng*rng // для корректной работы нужен монолитный массив data procedure Init1(channel:byte); stdcall; external 'Delphi64TaxAPI.dll'; // обязательно к вызову. channel = 1..131, см. Руководство оператора, том 2, страницы 489 - 511 // 1..89 - расчёт на основании уже обработанных данных // 90.. 131 - должны быть загружены образцы (!!!) function CreateTaxonomicDiff(value:TTaxInputIntData; out Structure:TStructureList):integer; stdcall; external 'Delphi64TaxAPI.dll'; // возвращаемые значения: // 0 - отсутствуют значимые различия. Для поиска минорных различий используйте функцию CreateMinorTaxDiff // 1 .. N (N <= len*len) - максимально возможное среднее отклонение в единицах tSF // -1 - Det(sA) = 0, некорректная выборка // -2 - некорректная матрица распределения // -3 - суммарная длина векторов меньше, чем (len+2)*len Отмечено, что функция возвращает корректные результаты в 100% случаев, если SetLength для массива data вызывался лишь раз (т.е. данные были сразу помещены в массив и переданы в функцию). Например, так: var matrix:TTaxInputIntData; err:integer; list:TStructureList; <...> ar:=matrix.data; SetLength(ar,len*(len+2)); for i := 0 to len+1 do for j := 0 to len-1 do if (i=0) or (i = (len+1)) then ar[j*len + i]:=0 else ar[j*len+i]:= data[k]; matrix.len:=length(matrix.data); err:=CreateTaxonomicDiff(matrix, list); в err получаем положительные значения (кроме тех случаев, когда отличий нет, - тогда ноль), в list - девиации. если же затем увеличить массив data и дописать в него хотя бы один вектор: k:=length(ar); SetLength(ar, k + len+2); for j:=0 to len+1 do if (j=0) or (j = (len+1)) then ar[k+j]:=0 else ar[k+j]:= data1[m]; , то с вероятностью 10-20% (со слов коллег) в err возвращается ошибка -3. При этом, если создать новый массив и в него внести все данные, влючая новые: k:=length(matrix.data); SetLength(ar1, k + len+2); // ar1 - новый массив for i:=0 to k-1 do ar1[i]:=matrix.data[i]; for j:=0 to len+1 do if (j=0) or (j = (len+1)) then ar1[k+j]:=0 else ar1[k+j]:= data1[m]; matrix.data:=ar1; , то ошибок не случается. Понятно, что код переписали и используется второй вариант, но хотелось бы разобраться, почему возникает ошибка. Было мнение, что массив может быть немонолитен после последовательного вызова SetLength, но вы меня разубедили :) Но в чём тогда может крыться ошибка? К сожалению, поддержка со стороны разработчиков инструмента уже невозможна :( A: Массив монолитен по определению, а каждый раз, когда вы вызываете SetLength, он может менять своё местоположение в памяти. Если вы передали функции указатель на свой массив, а затем изменили его размер, то очевидно, что у функции останется мусорный указатель и вероятно возникновение AV. Соответственно, если вы передаёте свой массив куда-то во вне, то ни в коем случае, не должны изменять его размер, а так же необходимо позаботиться, чтобы он не был автоматически удалён из памяти, т.е. чтобы оставалась как минимум одна ссылка на массив, пока функция не отработает до конца. Upd: Внутри Delphi, динамический массив представляет собой вот такую структуру (картинка отсюда): Т.е. это непрерывная область памяти, где располагается 2 служебных поля (размер массива и счётчик ссылок) и ваши данные. Служебные поля находятся по отрицательному смещению от указателя на массив. Соответственно, нет никакой разницы, сколько раз вызывать SetLength для массива - структура его всегда будет оставаться такой же. Единственное отличие, так это то, что местоположение в памяти, может меняться. Но это никак не влияет на процесс чтения/записи значений в него и не может приводить к каким-либо ошибкам. A: Функция из DLL не должна иметь такой прототип - заметьте, что data: array of integer; - не динамический, а открытый массив, прямых аналогов которому в других языках нет. Параметр - открытый массив на самом деле некая хитрая структура данных, обслуживаемая магией компилятора, так что такой аргумент умеет принимать - из Дельфийского кода, конечно - и статические, и динамические массивы. В данном случае он ещё и по значению передаётся, что для обработки больших данных не фонтан. Поэтому нельзя рассчитывать на то, что функция с таким прототипом будет корректно работать (иногда везёт, видимо, из-за того, что указатель на данные идёт в начале). A: Попробую и я :). Вы не можете передавать в DLL, написаную на FORTRAN-е или любом другом языке, (или получать оттуда) данные, которые в Delphi, объявлены как array of something. Откровенно говоря, такие типы данных не должны пересекать границы выполняемых модулей, даже если обе стороны написаны на Delphi. Исключение - компиляция с run-time packages, но это уже другая история. Delphi-евские динамические массивы (как и open array параметры) настолько компиляторозависимые вещи, что рассчитывать на то, что они отобразятся на что-то адекватное в другом языке - сильно рисковать, как Вы уже и испытали. Когда оно работает, Вам просто везет. К сожалению, Вы не привели "родной" декларации функции и типов данных, возможно, у Вас их нет. Также Вы не показали, как осуществляется вызов функции с Вашими данными, этот-то код у Вас есть? Что такое здесь matrix, и какое значение у matrix.data перед этими манипуляциями: ar:=matrix.data; SetLength(ar,len*(len+2)); Какой смысл в присвоении ar:=matrix.data;, если сразу после него массиву назначается (новая?) длина и присваиваются значения всем элементам? При взгляде на такой код, меня начинают мучить подозрения, что люди не совсем понимают, что они делают. Теперь о том, как нам со всем этим жить. {$R-} type TIntegerArray1 = array[0..0] of integer; PIntegerArray1 = ^TIntegerArray1; TTaxInputIntData = record len: int64; rsrvd1, rsrvd2:integer; rsrvd3:double; data: PIntegerArray1; end; (Надеюсь, не ошибся с синтаксисом, писал прямо сюда.) Здесь будет больше работы с распределением/освобождением памяти, но это то, как следует делать такие вещи.
{ "pile_set_name": "StackExchange" }
Q: Apex Unit Test giving different results for SOQL query when using runAs I'm writing a unit test to test code that is being used both by regular salesforce users and the site guest user. In order to do so, I'm using the System.runAs method. I was getting weird results, and narrowed it down to the fact that when using runAs guest user, I get different query results. Some setup code: Contact con2 = new Contact(FirstName = 'Test1', LastName = 'Test2', MobilePhone='222-222-2222', Email='[email protected]'); insert con2; Contact con_a = [SELECT Id from contact where email = '[email protected]' LIMIT 1]; This gives me a result. However, when I do the following: User signUpFormUser = [SELECT Id, FirstName FROM User WHERE FirstName = 'SignUpForm' LIMIT 1]; System.runAs(signUpFormUser){ Contact con_s = [SELECT Id from contact where email = '[email protected]' LIMIT 1]; } I get a List has no rows for assignment to SObject exception. Why does this happen? How can I fix it? A: When you use System.runAs(), you're establishing a different execution context, one where the record visibility for a specific user is implicitly enforced just like with Apex code that is running under the with sharing regime. In that new execution context you'll have the appropriate sharing rules and visibility for its running user applied to query results. Presumably, in your organization, the Org-Wide Default for the Contact object is set to Private. Hence, con2 is owned by the original test-running user, and when the test code switches into the context of signUpFormUser, your test methods and with sharing Apex cannot see that Contact. When you directly assign an Sobject to the result of a query (rather than a List<Sobject>) and the query returns no rows, you'll always get an exception. To avoid this, assign to a List and check the count returned.
{ "pile_set_name": "StackExchange" }
Q: jquery prevent redirect until after animation This code works perfectly except when you click on a link, The page is redirected before jquery has a change to visually animate the margin back to zero. Is there a way to prevent the redirect until after jquery animates the margin back to zero? HTML <div id="sidebar"> <div class="navigation"> <ul> <a href="../../../index.html"><li><img src="dbs/images/home.png" title="" width="40" height="38" />به عقب</li></a> <a href="../../000_Movies/_assets/playlist.html"><li>فیلم ها</li></a> <a href="../../020_IAM/_assets/playlist.html"><li>وزارتخانه ها ایران زنده</li></a> <a href="../../080_Worship/_assets/playlist.html"><li>پرستش</li></a> <a href="../../330_Teen/_assets/playlist.html"><li>جوانان</li></a> <a href="../../300_Children/_assets/playlist.html"><li>کودکان</li></a> <a href="../../400_Testimony/_assets/playlist.html"><li>پزوهش ها</li></a> <a href="../../600_SOC/_assets/playlist.html"><li>دانشکده مسیح</li></a> <a href="../../750_Women/_assets/playlist.html"><li>زنان</li></a> <a href="../../800_BAHAM/_assets/playlist.html"><li>کلیپ های سری</li></a> </ul> </div> </div> JS $('.navigation a li').click(function () { $('.slider').animate({ marginLeft: 0 }, 500); }); A: .animate() takes a callback function like so: $('.navigation a li').click(function () { $('.slider').animate({ marginLeft: 0 }, 500,function() { //thing to do when you animation is finished e.g. location.href = 'http://redirect.to.url'; }); }); For complete documentation, check out the (extremely useful) jQuery docs: http://api.jquery.com/animate/
{ "pile_set_name": "StackExchange" }
Q: Mysql Distinct rows 2 columns I have a query: SELECT p.productid, p.dupproductid FROM products p, categories c WHERE c.catid = p.catid && (c.parent IN(2257) || p.catid = 2257) GROUP BY p.productid This returns: productid dupproductid 23423 0 54345 0 34234 33333 23423 33333 45345 0 34324 11111 46546 0 I want to only get unique dupproductid apart from the ones that are 0 so I can't use GROUP BY I'd like it to return productid dupproductid 23423 0 54345 0 34234 33333 45345 0 34324 11111 46546 0 A: If you want to drop the min ID then this will work for you - SELECT p.productid, p.dupproductid FROM (SELECT p.productid ,p.dupproductid ,ROW_NUMBER() OVER(PARTITION BY dupproductid ORDER BY productid DESC) as RN FROM products p, categories c WHERE c.catid = p.catid && (c.parent IN(2257) || p.catid = 2257) ) T WHERE T.productid = 0 OR RN = 1 Sql Fiddle for you - http://www.sqlfiddle.com/#!18/db18b/2
{ "pile_set_name": "StackExchange" }
Q: Find the maximum product that can be formed by taking any one element from each sub-array I am trying to write an efficient algorithm in JavaScript to solve this task. Please see the next examples of input data and correct results: Array: [ [-3,-4], [1,2,-3] ] Result: (-4)*(-3) = 12 Array: [ [1,-1], [2,3], [10,-100,20] ] Result: (-1)*3*(-100) = 300 Array: [ [-3,-15], [-3,-7], [-5,1,-2,-7] ] Result: (-15)*(-7)*1 = 105 It can be any number of sub-arrays and any number of elements in each sub-array. What I already found is that I probably should leave only min and max values in the each sub-array, I did it using .map(a => [Math.min(...a), Math.max(...a)]) and sort them using .sort((a, b) => a[0] - b[0]). And now I am stuck. Probably there is a way to calculate all possible products but I am sure that it's not an effective way to solve this task. Please help! A: The problem you post can be solved with a simple algorithm. We just need to keep tracking the maximum/minimum when iterating over each sub-array. We can keep finding the next maximum/minimum by multiplying the current maximum/minimum with the max/min value in each sub-array. We pick the maximum when the iterating is over. Its time complexity is O(n) where n is total number of elements in an array (i.e. sum of number of elements in each sub-array). Here's the complete code. find_maximum_product function keeps tracking the minimum/maximum and returns the maximum eventually, and it also keeps tracking the multipliers and return it: /** * arr: array of any number of sub-arrays and * any number of elements in each sub-array. * e.g. [[1, -1], [2, 3], [10, -100, 20]] */ function find_maximum_product(arr) { let max = 1; let min = 1; let max_multipliers = []; let min_multipliers = []; for (let i = 0; i < arr.length; i++) { const a = Math.max(...arr[i]); const b = Math.min(...arr[i]); const candidates = [max * a, max * b, min * a, min * b]; max = Math.max(...candidates); min = Math.min(...candidates); let new_max_multipliers; let new_min_multipliers; switch (max) { case candidates[0]: new_max_multipliers = max_multipliers.concat(a); break; case candidates[1]: new_max_multipliers = max_multipliers.concat(b); break; case candidates[2]: new_max_multipliers = min_multipliers.concat(a); break; case candidates[3]: new_max_multipliers = min_multipliers.concat(b); break; } switch (min) { case candidates[0]: new_min_multipliers = max_multipliers.concat(a); break; case candidates[1]: new_min_multipliers = max_multipliers.concat(b); break; case candidates[2]: new_min_multipliers = min_multipliers.concat(a); break; case candidates[3]: new_min_multipliers = min_multipliers.concat(b); break; } max_multipliers = new_max_multipliers; min_multipliers = new_min_multipliers; } if (max >= min) { return [max, max_multipliers]; } return [min, min_multipliers]; } const arrays = [ [ [-3, -4], [1, 2, -3], ], [ [1, -1], [2, 3], [10, -100, 20], ], [ [-3, -15], [-3, -7], [-5, 1, -2, -7], ], [ [14, 2], [0, -16], [-12, -16], ], [ [-20, -4, -19, -18], [0, -15, -10], [-13, 4], ], [ [-2, -15, -12, -8, -16], [-4, -15, -7], [-10, -5], ], ]; for (let i = 0; i < arrays.length; i++) { const [max, max_multipliers] = find_maximum_product(arrays[i]); console.log('Array:', JSON.stringify(arrays[i])); console.log('Result:', `${max_multipliers.join(' * ')} = ${max}`); console.log(''); } UPDATE Simpler version for just getting the maximum, not getting the multipliers: /** * arr: array of any number of sub-arrays and * any number of elements in each sub-array. * e.g. [[1, -1], [2, 3], [10, -100, 20]] */ function get_maximum_product(arr) { return arr .map((a) => [Math.min(...a), Math.max(...a)]) .reduce( (acc, current) => { const candidates = [ acc[0] * current[0], acc[0] * current[1], acc[1] * current[0], acc[1] * current[1], ]; return [Math.min(...candidates), Math.max(...candidates)]; }, [1, 1] )[1]; } A: Here is a top-down recurrence that could be adapted to bottom-up (a loop) and utilises O(n) search space. Until I can complete it, the reader is encouraged to add a third return value in the tuple, largest_non_positive for that special case. // Returns [highest positive, lowest negative] // Does not address highest non-positive function f(A, i){ const high = Math.max(...A[i]); const low = Math.min(...A[i]); if (i == 0){ if (low < 0 && high >= 0) return [high, low]; if (low <= 0 && high <= 0) return [-Infinity, low]; if (low >= 0 && high >= 0) return [high, Infinity]; } const [pos, neg] = f(A, i - 1); function maybeZero(prod){ return isNaN(prod) ? 0 : prod; } let hp = maybeZero(high * pos); let hn = maybeZero(high * neg); let ln = maybeZero(low * neg); let lp = maybeZero(low * pos); if (low < 0 && high >= 0) return [Math.max(hp, ln), Math.min(hn, lp)]; if (low <= 0 && high <= 0) return [ln, lp]; if (low >= 0 && high >= 0) return [hp, hn]; } var As = [ [[-3,-4], [1,2,-3]], [[1,-1], [2,3], [10,-100,20]], [[-3,-15], [-3,-7], [-5,1,-2,-7]], [[-11,-6], [-20,-20], [18,-4], [-20,1]], [[-1000,1], [-1,1], [-1,1], [-1,1]], [[14,2], [0,-16], [-12,-16]], [[-20, -4, -19, -18], [0, -15, -10],[-13, 4]] ]; for (let A of As){ console.log(JSON.stringify(A)); console.log(f(A, A.length - 1)[0]); console.log(''); }
{ "pile_set_name": "StackExchange" }
Q: How to create List within a Textarea? How can implement a list within a Textarea. Where User click in text area it should generate 1st listitem no and also same when pressing Enter key. A: You cannot put it inside a textarea what you can do is make a DIV editable and use HTML inside and style it to look like a textarea, This piece of code is exactly what you want and when user press enter it will generate. <div class="editable" contenteditable="true"> <ul> <li>List item</li> <li>List item</li> </ul></div>
{ "pile_set_name": "StackExchange" }
Q: Numerous 404's for "alive.txt", anybody know what that file could be? Just wondering if there is any significance to the frequency. Lately our site has been getting notably more 404 errors for alive.txt than any other uri. Is this some kind of common server log/config file, or just a fluke? A: It sounds like a monitor or a health check.
{ "pile_set_name": "StackExchange" }