qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
9,173,810
We develop a lot of systems that have an input that should have a related text label after them for a unit of measure. e.g. Meter square, meter cubed, tonnes, ft cubed etc. I don't need to do anything clever like scale between units of measure. Just ensure that it is easy to update and good practice. Was looking for something that is reasonably automatic. That binds the unit of measure to the specific property. We have screens that mix 15 different units of measure with over 200 properties I use ViewModels and Editor templates (although some things are hardcoded as dropdowns or texteditorfor etc so I could add classes). Do any other people encounter this issue? I could just hardcode the text after the field in the view. Is there anything more graceful? Maybe an attribute etc? Anyone have any thoughts on the best way to handle this. Thanks
2012/02/07
[ "https://Stackoverflow.com/questions/9173810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629323/" ]
Use display templates and more specific types. For instance, create `Currency` class which is used to handle currencies. By doing so you know if it's cents, dollars or whatever and which currency the user uses. More work, sure. But the code is more robust and it's easier to tell what unit should be used. That's why are are using `TimeSpan` and not an `int` which could contain milliseconds, seconds etc.
My thinking is presently to add an attribute e.g. ``` [Unit(UnitOfMeasure.Mph)] [Display(Name="Top Speed"] public float TopSpeed {get;set} ``` Then do something either create a Html.UnitOfMeasureDisplay helper, or try to do something with EditorTemplates to automatically include it.
35,442,329
I want to visualize README.md files from a project in github, in my website. What is the best way to do this? Like fetch the markdown code and process the mark down locally? Or there is a way to fetch the already processed markdown from github?
2016/02/16
[ "https://Stackoverflow.com/questions/35442329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1164246/" ]
One possible solution is to use a javascript-based markdown parser, such as <https://github.com/evilstreak/markdown-js>. That library can be loaded from the browser and can display the markdown. In this example (taken from the aforementioned site), you would need to fetch and insert the markdown in the output of your site: ```html <!DOCTYPE html> <html> <body> <textarea id="text-input" oninput="this.editor.update()" rows="6" cols="60">Insert proxied **Markdown** here.</textarea> <div id="preview"> </div> <script src="lib/markdown.js"></script> <script> function Editor(input, preview) { this.update = function () { preview.innerHTML = markdown.toHTML(input.value); }; input.editor = this; this.update(); } var $ = function (id) { return document.getElementById(id); }; new Editor($("text-input"), $("preview")); </script> </body> </html> ```
<https://github.com/zhlicen/md.htm> An example of zeromd.js Just serve the md.htm file and md files, and visit directly by url: /md.htm?src=README.md Or directly use my github page, Example: <https://b.0-0.plus/blog/md.htm?src=https://raw.githubusercontent.com/microsoft/vscode/main/README.md>
61,490,876
I am looking into the Oracle SQL Model clause. I am trying to write dynamic Oracle SQL which can be adapted to run for a varying number of columns each time, using this model clause. However I am struggling to see how I could adapt this (even using PL/SQL) to a dynamic/generic query or procedure here is a rough view of the table I am working on ``` OWNER||ACCOUNT_YEAR||ACCOUNT_NAME||PERIOD_1||PERIOD_2||PERIOD_3||PERIOD_4||PERIOD_5||PERIOD_6||.... --------------------------------------------------------------------------------------------------- 9640|| 2018 ||something 1|| 34 || 444 || 982 || 55 || 42 || 65 || 9640|| 2018 ||something 2|| 333 || 65 || 666 || 78 || 44 || 55 || 9640|| 2018 ||something 3|| 6565 || 783 || 32 || 12 || 46 || 667 || ``` Here is what I have so far: ``` select OWNER, PERIOD_1, PERIOD_2, PERIOD_3, PERIOD_4, PERIOD_5, PERIOD_6, PERIOD_7, PERIOD_8, PERIOD_9, PERIOD_10, PERIOD_11, PERIOD_12, ACCOUNT_YEAR, ACCOUNT_NAME from DATA-TABLE where OWNER IN ('9640') and PERIOD_1 is not null MODEL ignore nav Return UPDATED ROWS PARTITION BY (OWNER, ACCOUNT_NAME) DIMENSION BY (ACCOUNT_YEAR) MEASURES (PERIOD_1,PERIOD_2, PERIOD_3, PERIOD_4, PERIOD_5, PERIOD_6, PERIOD_7, PERIOD_8, PERIOD_9, PERIOD_10, PERIOD_11, PERIOD_12) RULES ( PERIOD_1[2021] = PERIOD_1[2018] * 1.05, PERIOD_2[2021] = PERIOD_2[2018] * 1.05, PERIOD_3[2021] = PERIOD_3[2018] * 1.05, PERIOD_4[2021] = PERIOD_4[2018] * 1.05, PERIOD_5[2021] = PERIOD_6[2018] * 1.05, PERIOD_7[2021] = PERIOD_7[2018] * 1.05, PERIOD_8[2021] = PERIOD_8[2018] * 1.05, PERIOD_9[2021] = PERIOD_9[2018] * 1.05, PERIOD_10[2021] = PERIOD_10[2018] * 1.05, PERIOD_11[2021] = PERIOD_11[2018] * 1.05, PERIOD_12[2021] = PERIOD_12[2018] * 1.05 ) ORDER BY ACCOUNT_YEAR asc; ``` As you can see in the measures and rules section, I am currently hardcoding each period column into this query I want to be able to use this model clause (well specifically the rule part in a flexible way, so I can have a query which could be run for say, just period 1 -3, or period 5-12... I have tried looking into this but all examples show the left hand side of the rule (e.g. PERIOD\_12[2021] =...) to explicitly refer to a column in a table, rather than a parameter or variable I can swap in for something else simply Any help on how I might accomplish this through SQL or PLSQL would be greatly appreciated
2020/04/28
[ "https://Stackoverflow.com/questions/61490876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11979838/" ]
I've created a demo and it somewhat does what you want. The two issues it has are- 1. User has to click twice(double click) to input values(I can't to make it work on a single click) 2. The position of the `label` overlaps the selected value(Even after giving another class or styling it dynamically) > > **If anybody has any idea about how to go through these issues, their ideas are > welcome.** > @Leff, you yourself look like a person with experience, can > you solve them? If yes, please do so and please also enlighten us(me). > > > > Also, **I've used `jquery` in this code** if you're looking for only `vanilla javascript`, you might have to do it yourself or find a person who can as I'm no expert in that area but that's the logical part. Your main problem seemed to be of `HTML` which should be resolved. Below is the demo, see if it helps you. ```js // initialize const select = new mdc.select.MDCSelect(document.querySelector('.mdc-select')); // stop the original propagation so that input field remains editable $('#food').on('click', (event) => { return false; }); // Demo Data const foodArr = ['Bread, Cereal, Rice, and Pasta', 'Vegetables', 'Fruit']; // You'll have to use ajax here to get the data $('#food').on('keyup', (event) => { //console.clear(); let $this = $(event.currentTarget); let currValue = $this.val(); let search = new RegExp(currValue, 'i'); // prepare a regex object // Your custom condition let matchArr = foodArr.filter(item => search.test(item)); //store the result in an array let $select = ""; // check if array is empty if (matchArr.length > 0) { // map the elements of the array and create option html matchArr.forEach((item) => { $select += `<li class="mdc-list-item" data-value="${item}"> ${item}</li>`; }) } else { // if array is empty, display no match $select += `<li class="mdc-list-item" id="no_match"> No match found!</li>`; } //console.log(matchArr); // if the data was selected before, unselect it $('.mdc-list-item--selected:first').attr({'data-value': ''}); $('.mdc-list-item--selected:first').text(''); $('.mdc-list-item--selected:not(:first)').removeClass('mdc-list-item--selected'); // remove all previous option elements $('.mdc-list-item:not(.mdc-list-item--selected:first)').remove(); // add new option elements $('.mdc-list-item--selected').after($select); // start the click function, so that dropdown doesn't close $this.click(); }); // When any option is selected, show it on input field $(document).on('click', '.mdc-list-item:not(#no_match)', (event) => { let $this = $(event.currentTarget); $this.addClass('mdc-list-item--selected'); $('.mdc-floating-label').addClass('mdc-floating-label--float-above'); $('.mdc-select__anchor').addClass('demo-width-class mdc-ripple-upgraded') $('.mdc-line-ripple').addClass('mdc-line-ripple--active mdc-line-ripple--deactivating') $('.mdc-line-ripple').css({'transform-origin': '182px center'}) $('#food').val($this.attr('data-value')); // return false; // event.stopImmediatePropagation() }); // if clicked on no match, value of input field should be empty, alternatively you can also make option disabled $(document).on('click', '#no_match', (event) => { $('#food').val(''); }); ``` ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>@sauhardnc</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://unpkg.com/material-components-web@v4.0.0/dist/material-components-web.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <script src="https://unpkg.com/material-components-web@v4.0.0/dist/material-components-web.min.js"></script> </head> <body> <div class="mdc-select"> <div class="mdc-select__anchor demo-width-class" style="width: 100%"> <i class="mdc-select__dropdown-icon"></i> <input type="text" class="mdc-select__selected-text" id="food"></input> <!-- Give a unique id --> <!--<div contenteditable="true" class="mdc-select__selected-text" id="fruit"></div>--> <span class="mdc-floating-label">Pick a Food Group</span> <div class="mdc-line-ripple"></div> </div> <div class="mdc-select__menu mdc-menu mdc-menu-surface demo-width-class" style="width: 100%"> <ul class="mdc-list"> <li class="mdc-list-item mdc-list-item--selected" data-value="" aria-selected="true"></li> <li class="mdc-list-item" data-value="Bread, Cereal, Rice, and Pasta"> Bread, Cereal, Rice, and Pasta </li> <li class="mdc-list-item" data-value="Vegetables"> Vegetables </li> <li class="mdc-list-item" data-value="Fruit"> Fruit </li> </ul> </div> </div> </body> </html> ```
Based on the answers here, I created my own function. Also the Material Design for Web Versions in the answers are quite old. Hope this helps for those looking for something like this. At first, instead of using MDCSelect, I used MDCTextField and MDCMenu components. I thought everything would be easier this way. It took some time though, but I'm done. The function that triggers the Menu to open when clicking on the TextField may seem a bit weird. @Zachary Haber explains this, > > It appears that the inconsistency is due to a race condition. Clicking > on the menu causes the focus to leave the input which causes the menu > to close. And the menu closing causes focus to move back to the input > making it open again. > > > The issue is that the menu often closes before the menu has a chance > to send out the selected event. > > > To review the original answer for MDCMenu click issue: <https://stackoverflow.com/a/61965646/5698079> Here is a working example; ```js const textFields = document.querySelectorAll('.mdc-text-field'); textFields.forEach(field => { mdc.textField.MDCTextField.attachTo(field); }); const menuS = document.querySelector("#menu"); const menu = new mdc.menu.MDCMenu(menuS); const searchFieldS = document.querySelector("#food"); menu.setAnchorCorner(mdc.menuSurface.Corner.BOTTOM_LEFT); document.querySelectorAll('#menu li').forEach(function(li) { li.addEventListener('click', function() { const selectedLi = this.getAttribute("data-value"); if (selectedLi != "notfound") { // If you are going to post the text field data, I recommend you to get data-value. searchFieldS.value = selectedLi; searchFieldS.setAttribute("data-value", selectedLi); } }); }); // Open the menu when text field is focused. (function() { let menuFocused = false; searchFieldS.addEventListener("focusin", () => { if (!menuFocused) menu.open = true; }); searchFieldS.addEventListener("click", () => { menu.open = true; }); menuS.addEventListener("focusin", () => { menuFocused = true; }); menuS.addEventListener("focusout", () => { // This interval is to help make sure that input.focusIn doesn't re-open the menu setTimeout(() => { menuFocused = false; }, 0); }); searchFieldS.addEventListener("focusout", () => { setTimeout(() => { if (!menuFocused) menu.open = false; }, 0); }); })(); searchFieldS.addEventListener("keyup", function(e) { const keyT = event.target.value.toUpperCase(); const menuList = document.querySelectorAll('.mdc-deprecated-list > li > .mdc-deprecated-list-item__text'); const menuLiss = document.querySelectorAll('.mdc-deprecated-list-item'); const noDataEl = document.querySelector("#menuNoData"); // const arr = []; menuList.forEach(function(searchItem) { if (searchItem.parentElement.getAttribute('id') != "menuNoData") { searchItem.parentElement.dataset.isfound = searchItem.textContent.toUpperCase().includes(keyT) ? "true" : "false"; arr.push(searchItem.parentElement.getAttribute("data-isfound")); } }); if (arr.filter(function(countArr) { return countArr == "true" }).length == 0) { noDataEl.classList.remove("hide-none"); } else { if (!noDataEl.classList.contains("hide-none")) { noDataEl.classList.add("hide-none"); } } }); ``` ```css li[data-isfound="false"] { display: none; } .hide-none { display: none !important; } ``` ```html <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script> <link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet"> <div class="mdc-menu-surface--anchor"> <label class="mdc-text-field mdc-text-field--outlined"> <span class="mdc-notched-outline"> <span class="mdc-notched-outline__leading"></span> <span class="mdc-notched-outline__notch"> <span class="mdc-floating-label" id="my-label-id">Select a fruit..</span> </span> <span class="mdc-notched-outline__trailing"></span> </span> <input id="food" type="text" class="mdc-text-field__input" aria-labelledby="my-label-id"> </label> <div id="menu" class="mdc-menu mdc-menu-surface mdc-menu-surface--fullwidth"> <ul class="mdc-deprecated-list" role="listbox" aria-label="Food picker listbox"> <li id="menuNoData" class="mdc-deprecated-list-item mdc-deprecated-list-item--disabled hide-none" aria-selected="false" aria-disabled="true" data-value="notfound" role="option" value="" data-value=""> <span class="mdc-deprecated-list-item__ripple"></span> <span class="mdc-deprecated-list-item__text">No data found.</span> </li> <li class="mdc-deprecated-list-item" aria-selected="false" data-value="grains" role="option"> <span class="mdc-deprecated-list-item__ripple"></span> <span class="mdc-deprecated-list-item__text">Bread, Cereal, Rice, and Pasta</span> </li> <li class="mdc-deprecated-list-item" aria-selected="false" data-value="vegetables" role="option"> <span class="mdc-deprecated-list-item__ripple"></span> <span class="mdc-deprecated-list-item__text">Vegetables</span> </li> <li class="mdc-deprecated-list-item" aria-selected="false" data-value="fruit" role="option"> <span class="mdc-deprecated-list-item__ripple"></span> <span class="mdc-deprecated-list-item__text">Fruit</span> </li> </ul> </div> </div> ``` CodePen: <https://codepen.io/lastofdead/pen/bGMZPzO>
9,880
While studying the etymology of the word, I found that it comes from ***gryphus***, the Latin for *griffin*. In fact *griffin* also happens to be one meaning of **grifo**. And as we all know, *griffin* is a mythical beast with the body of a lion and the head of an eagle. *Griffin* is also the name of a species of vultures. What I don't understand then is how **grifo** became the Spanish for a water faucet. It seems random but I am sure there's some logic behind it. Anyone got any idea?
2014/10/16
[ "https://spanish.stackexchange.com/questions/9880", "https://spanish.stackexchange.com", "https://spanish.stackexchange.com/users/1979/" ]
The most probable cause is that drains in antique buildings, especially churches had different forms of fantastic animals, people or normal animals, and here is where griffins appears. In Italian there is *rubinetto* and French has *robinet*. Both with faucet meaning because of the same origin, fonts had sheep sculptures. You can see this site: <http://etimologias.dechile.net/?grifo>
The term grifo is relatively new regarding faucets. It looks like it started to be called like this when faucet makers started to build them representing a griffin, in the 18th century.
578,505
What's it called when you get a type of award because you didn't get the award you were supposed to get? Let's say someone was trying to get an award, and they tried really hard, but they didn't get it, but because people felt bad that they didn't get it, they got a different award called a(n) \_\_\_ award, meaning "Hey, you didn't do it, but here's this instead, because at least you got something."
2021/11/14
[ "https://english.stackexchange.com/questions/578505", "https://english.stackexchange.com", "https://english.stackexchange.com/users/241628/" ]
This is a participation award/trophy/ribbon. According to [Wikipedia](https://en.wikipedia.org/wiki/Participation_trophy): > > A participation trophy is a trophy given to children (usually) who participate in a sporting event but do not finish in first, second or third place, and so would not normally be eligible for a trophy. It is frequently associated with millennials, those of Generation Y. > > > When it's not an official reward, you can also use the expression "got an A for effort". From [Farlex via TFD](https://idioms.thefreedictionary.com/A+for+effort): > > A verbal acknowledgement of appreciation for attempting a task, even if it did not produce a successful result. > > > > > > > You forgot to sand the wood before you painted it, but I'll give you an A for effort since you tried to help. > > > > > > > > > I have also heard names for an award for last place, but those aren't typically given as [a pat on the back](https://www.merriam-webster.com/dictionary/a%20pat%20on%20the%20back). See [What is a "prize" for last place called?](https://english.stackexchange.com/q/283337/191178)
Bauble ------ An award that is given which is nevertheless lacking in real weight and significance is sometimes referred to as a 'Bauble'. For example, in [this news article](https://www.bbc.co.uk/news/uk-politics-58575894) Dominic Raab was reported to be appointed to the constitutionally almost meaningless role of 'Deputy Prime Minister' of the UK. His new role is described thusly: > > But even with the bauble of deputy prime minister as part of his title [...], Mr Raab, the now former foreign secretary, is a less senior figure in the government. > > >
1,805,012
I'm using Visual Studio 2008 with Microsoft test tools. I need to access a text file from within the unit test. I've already configured the file with build action set to 'Content' and copy to output directory to 'Copy Always', but the file is not being copied to the output directory, which according to `System.Environment.CurrentDirectory` is > > '{project\_path}\TestResults\Pablo\_COMPU 2009-11-26 15\_01\_23\Out' > > > This folder contains all the DLL dependencies of the project, but my text file is not there. Which is the correct way to access a text file from a unit test?
2009/11/26
[ "https://Stackoverflow.com/questions/1805012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60810/" ]
You have to add the `DeploymentItem` attribute to your test class. With this attribute you specify the files which are copied into the out directory for the test run. For example: ```cs [TestMethod] [DeploymentItem(@"myfile.txt", "optionalOutFolder")] public void MyTest() { ... } ``` See also: <http://msdn.microsoft.com/en-us/library/ms182475.aspx>.
How are you running your tests? We use (TestDriven.net -> Run Tests). From my experience, some test runners (like Junit in Netbeans) won't automatically copy any additional text files that you might need for testing. So in your case you might have to do a full build, and then try running the tests again. And the correct way for accessing text files from tests is the way you're trying to do it. (Setting the files to "copy always" and "content", and accessing them from the compiled directory). Also, not sure where people are getting the idea that having tests rely on files is a bad thing. It's not. If anything, having separate test files, will only clean up your tests and make them more readable. Consider some xml parsing method that returns a large string: ```cs String expectedOutput = fileOperator.ReadStringFromFile("expectedFileContents.xml"); String result = systemUnderTest.Parse(somethingtoparse); Assert.Equals(expectedOutput, result); ``` Imagine if the output was 30 lines long, would you clutter your test code with one giant String? or just read it from a file.
28,111,722
I've got one question . Is there anybody how has idea how to invoke function in controller only for the first li object in ul when ul has a ng-repeat? Lets say ive got function in my controller like: ``` var init = function () { var a = this; }; ``` And my ul repeater seams like lets say: ``` <ul ng-repeat="up in userpartners" ng-click="setSelected(this);"> <li> {{up.id}} </li> </ul> ``` And I want to invoke init function with parameter 'this' which will be first 'li' item. Only for the first li i want to set something.
2015/01/23
[ "https://Stackoverflow.com/questions/28111722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1282272/" ]
From what I understand, you want to remove the first letter if it is not a digit. So you may make this function simpler: ``` CString GAbsMeterCalibration::TrimMeterSNString(CString meterSN) { meterSN.MakeUpper(); int length = meterSN.GetLength(); // just check the first character is always a digit else remove it if (length > 0 && unsigned(meterSN[0] - TCHAR('0')) > unsigned('9')) { return meterSN.Right(length - 1); } return meterSN; } ``` I am not using function *isdigit* instead of the conditional trick with *unsigned* because CString uses TCHAR which can be either *char* or *wchar\_t*.
I don't know if you've tried this, but, it should work. ``` CString str = _T("#12000895236GF"); // check string to see if it starts with digit. CString result = str.SpanIncluding(_T("0123456789")); // if result is empty, string does not start with a number // and we can remove the first character. Otherwise, string // remains intact. if (result.IsEmpty()) str = str.Mid(1); ``` Seems a little easier than what's been proposed.
15,430,413
Why is this code throwing a `NullReferenceException`? **Exception:** `System.NullReferenceException: Object reference not set to an instance of an object.` **Code:** ``` if ((string.IsNullOrEmpty(Request.QueryString["Sno"].ToString())) && (string.IsNullOrEmpty(Request.QueryString["Name"].ToString()))) { lblBookedBy.Text = ""; lblSno.Text = ""; } else { lblBookedBy.Text = Request.QueryString["Name"].ToString(); lblSno.Text = Request.QueryString["Sno"].ToString(); } ```
2013/03/15
[ "https://Stackoverflow.com/questions/15430413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1787471/" ]
I would recommend doing the following. ``` if (Request.QueryString["Sno"] == null || Request.QueryString["Name"] == null) { lblBookedBy.Text = ""; lblSno.Text = ""; } else { lblBookedBy.Text = Request.QueryString["Name"].ToString(); lblSno.Text = Request.QueryString["Sno"].ToString(); } ``` You are most likely getting a `NullReference` in the `if` statement. This way you are sure not to encounter this, and worst case if both of the variables are instantiated, but one or more contains an empty string it will simply set the `Text` to `empty`. Alternatively if you use `Convert.ToString` as many other suggested you can simplify the code by skipping the `if` statement. ``` lblBookedBy.Text = Convert.ToString(Request.QueryString["Name"]); lblSno.Text = Convert.ToString(Request.QueryString["Sno"]); ``` In worst case scenario one of these will be `Null`, and will result in one of the TextBoxes to show result, while the other one is empty. Also, assuming that `Request.QueryString` supports it, you could use [TryGetValue](http://msdn.microsoft.com/en-us/library/bb347013.aspx).
You are trying to cast `Request.QueryString["Sno"]` to string while it's value is `null`
21,939,324
I want to know in detail about the difference between alt and opt fragment in sequence diagram, they seem similar, I can't distinguish them. Anyone knows about this thing?
2014/02/21
[ "https://Stackoverflow.com/questions/21939324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3338003/" ]
**Alt** is alternative flow (SWITCH or if. IF with two paths) **Opt** is IF with one flow. If you use Opt, code will be executed or not !
They are basically the same. `alt` is more used for several choices, like a `switch` sentence group in C programming language. While `opt` is more used for only two choices, like a `if` sentence. But, don't get surprised, if you see both concepts used interchangeably.
2,403,458
``` public abstract class Master { public void printForAllMethodsInSubClass() { System.out.println ("Printing before subclass method executes"); System.out.println ("Parameters for subclass method were: ...."); } } public class Owner extends Master { public void printSomething () { System.out.println ("This printed from Owner"); } public int returnSomeCals () { return 5+5; } } ``` Without messing with methods of subclass...is it possible to execute `printForAllMethodsInSubClass()` before the method of a subclass gets executed? **update:** Using AspectJ/Ruby/Python...etc Would it also be possible to print the parameters? Above code formatted below: ``` public abstract class Master { public void printForAllMethodsInSubClass() { System.out.println ("Printing before subclass method executes"); } } public class Owner extends Master { public void printSomething (String something) { System.out.println (something + " printed from Owner"); } public int returnSomeCals (int x, int y) { return x+y; } } ```
2010/03/08
[ "https://Stackoverflow.com/questions/2403458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289035/" ]
To answer the "any other programming language": It's easily possible in Ruby: ``` class Master REDEFINED = [] def printForAllMethodsInSubClass puts 'Printing before subclass method executes' end def self.method_added(meth) if self < Master and not Master::REDEFINED.include? meth new_name = "MASTER_OVERRIDE_#{meth}".intern Master::REDEFINED.push meth, new_name alias_method new_name, meth define_method(meth) {|*args| printForAllMethodsInSubClass; send(new_name, *args)} end end end ``` You could also make a proxy declaration method to use in subclasses: ``` class Master def printForAllMethodsInSubClass Printing before subclass method executes end def self.master_method(name) define_method(name) {|*args| printForAllMethodsInSubClass; yield *args} end end class Owner master_method(:print_something) do puts "This was printed from Owner" end end ``` (This approach would also translate very naturally to Python decorators.)
This is possible in aspect-oriented programming languages, such as [AspectJ](http://eclipse.org/aspectj/).
18,622
I am new Ubuntu and Ask Ubuntu. I asked a question today concerning how to make a desktop icon in GNOME, but do not know how I get back to the question, to see if anybody has offered a suggestion.
2019/05/15
[ "https://meta.askubuntu.com/questions/18622", "https://meta.askubuntu.com", "https://meta.askubuntu.com/users/956403/" ]
[Jacob's answer](https://meta.askubuntu.com/a/18627/527764) explains how to search among your posts, which is especially useful if you have many posts and a great tip for us all. However, I think in your particular case, you just don't know your way around the place yet and don't know where to find any of your posts in general. If you only have a few posts, or you want to look at the most recent post, the easiest way is to look in your profile. Make sure you are on the [main site](https://askubuntu.com), not meta. Click your username or picture or reputation score in the top bar: [![click yourself screenshot](https://i.stack.imgur.com/Biwfn.png)](https://i.stack.imgur.com/Biwfn.png) And you will land on the Activity page of your profile: [![Activity page screenshot](https://i.stack.imgur.com/lxMjI.png)](https://i.stack.imgur.com/lxMjI.png) Look or scroll down and you will see mini lists of your answers and questions with titles. You can organise these lists by newest, most recently active, or highest scoring. In my case, I have written more answers than questions, so answers appear above questions. In your case it will likely be the other way around. [![Questions list in Activities](https://i.stack.imgur.com/YMNkz.png)](https://i.stack.imgur.com/YMNkz.png) You can click the **Questions** title to be taken to a more detailed list of your questions. If the question you are looking for is not there, it may have been deleted. It is hard to find deleted questions, and you may need to ask a mod for help if you need to see your deleted question. Note that you will receive a notification if anyone comments on or answers your question. The notification will appear as a red square with a number in it (corresponding to the number of messages) on the inbox icon to the right of your reputation and badges counts in the top bar. Unless you have turned off email notifications, you will sooner or later receive an email about such comments and answers too.
In the absence of any supplied information, the following assumes a default Ubuntu Gnome 18.04 desktop. In the title bar at the top right of the screen, left mouse click the section with your picture, reputation, and awards. This brings up your profile. At the top left, select "Activity", and from the list in the middle of the "Activity" screen, Select "Questions", third from the left. Your Questions on the starting (askubuntu) site will be listed. Note that this answer, along with any other helpful answer or comment, is totally useless in helping the user find their (first) question, since some "helpful" administrator moved everything to another site (Meta, since the question was arguably not about Ubuntu, but how to use the site). Now the user's second question has disappeared! Oh Meta-Meta where are you when we need you ;^O
59,940,644
I have React Native project which stops working after Xcode upgrade to version 11.3.1. The error is following ``` Could not install at this time. Failed to load Info.plist from bundle at path /Users/dmytro/Library/Developer/CoreSimulator/Devices/F0BD5650-04A4-4534-B3F6-56B74ED1B0C2/data/Library/Caches/com.apple.mobile.installd.staging/temp.aRWRdh/extracted/Target.app/Frameworks/RCTVibration.framework; Extra info about plist: ACL=<not found ``` [![enter image description here](https://i.stack.imgur.com/wOJf6.png)](https://i.stack.imgur.com/wOJf6.png) and details ``` Details This app could not be installed at this time. Domain: IXUserPresentableErrorDomain Code: 1 Failure Reason: Could not install at this time. Recovery Suggestion: Failed to load Info.plist from bundle at path /Users/dmytro/Library/Developer/CoreSimulator/Devices/F0BD5650-04A4-4534-B3F6-56B74ED1B0C2/data/Library/Caches/com.apple.mobile.installd.staging/temp.aRWRdh/extracted/Target.app/Frameworks/RCTVibration.framework; Extra info about plist: ACL=<not found> -- Failed to load Info.plist from bundle at path /Users/dmytro/Library/Developer/CoreSimulator/Devices/F0BD5650-04A4-4534-B3F6-56B74ED1B0C2/data/Library/Caches/com.apple.mobile.installd.staging/temp.aRWRdh/extracted/Target.app/Frameworks/RCTVibration.framework; Extra info about plist: ACL=<not found> Domain: MIInstallerErrorDomain Code: 35 User Info: { FunctionName = "-[MIBundle _validateWithError:]"; LegacyErrorString = PackageInspectionFailed; SourceFileLine = 128; } -- ``` [![enter image description here](https://i.stack.imgur.com/dY1Hf.png)](https://i.stack.imgur.com/dY1Hf.png)
2020/01/28
[ "https://Stackoverflow.com/questions/59940644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/923497/" ]
Using CocoaPods v1.9+, if you can't remove `use_frameworks!` from `Podfile`, you can set: ``` use_frameworks! :linkage => :static ``` > > Now that Swift supports static linking, CocoaPods has expanded this > DSL to allow specifying the type of linkage preferred. > > > Source: <https://blog.cocoapods.org/CocoaPods-1.9.0-beta/>
Go to `YourTarget` > `Build Settings` > `Packaging` > `Info.plist File` and check here the path to your `.plist` file. Also it would be helpful to clear your `derived data` folder, and re-build project again.
10,097
I just noticed that the Windows Registry on one of our computers is 180 MB (when exported to a .reg file). That seem large enough to cause a performance issue. That registry is probably 4 years old. I'm thinking of using a Registry Cleaner, assuming I can find a good one.
2009/05/19
[ "https://serverfault.com/questions/10097", "https://serverfault.com", "https://serverfault.com/users/2181/" ]
New rule: everyone must stop cleaning their registries. It is completely unnecessary and can inadvertently cause problems. Registry scanning as part of malware detection is one thing, but letting software "clean up" erroneous entries is risky. Address specific problems individually. Rant over. ;)
Agreeing with Thoreau, CCleaner is probably your best bet and a trusted solution. However, after 4 years, you might want to start thinking of just rebuilding to PC, it is a huge pain for some computers, but the results in the end exceed whatever registry cleaning or PC cleanup that you can do.
7,066,132
I'm having a problem with a boolean expression and when I did a logger.debug I had strange results, so I simplified my logging code to the following and was surprised not to see any 'false' being printed. Logging code in my controller: ``` logger.debug 'true' logger.debug true logger.debug logger.debug 'false' logger.debug false logger.debug logger.debug '1 == 1' logger.debug 1 == 1 logger.debug logger.debug '1 == 0' logger.debug 1 == 0 ``` Which prints out the following ``` true true false 1 == 1 true 1 == 0 ``` ... ? I would expect to see false. When I run '1 == 0' or 'puts false' in the console I get false. Am I missing something? Any ideas why isn't it printing the 'false'? ruby version: 1.8.7-p352 rails version: 2.3.2
2011/08/15
[ "https://Stackoverflow.com/questions/7066132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29043/" ]
Rails Logger uses `||` in the code before running `.to_s`, which fails for nil and false. <https://github.com/rails/rails/blob/master/activesupport/lib/active_support/buffered_logger.rb#L65> ``` def add(severity, message = nil, progname = nil, &block) return if @level > severity message = (message || (block && block.call) || progname).to_s ## <- this line # If a newline is necessary then create a new message ending with a newline. # Ensures that the original message is not mutated. message = "#{message}\n" unless message[-1] == ?\n buffer << message auto_flush message end ``` You can do this instead: ``` logger.debug( false.to_s) ```
Logger has got a condition somewhere (`if value`), which fails for nil and false. You want `logger.debug value.inspect`.
11,439,139
I have two questions for you: 1. [SOLVED] - In java, I have the ability to move around an image using the mouse listeners. Instead of moving the image exactly where my pointer is, how do I make it so if I click and move up the mouse, it just moves the image up. Not make the image jump to where my mouse pointer is. 2. [SOLVED] - Since I am building an editor, If I have multiple images on the window that you can move around, if there is two overlapping images, how do I detect which image I should actually move. What happens If I want to move the one behind the image instead of the front one or vice versa. What is the best method that you guys have done here. Some code that relates to both of these questions ``` addMouseMotionListener(new MouseMotionListener() { @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseDragged(MouseEvent arg0) { // TODO Auto-generated method stub //use this if(curObj != null){ Point p = arg0.getPoint(); curObj.pos.x = p.x; curObj.pos.y = p.y; ...... } } }); addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub //right now find the first one that contains the mouse. //later we can make it so they have an option to pick on that overlaps. Point p = arg0.getPoint(); SwingUtilities.convertPoint(Main.gui, p, instance); .... //this is the code to detect which image to use curObj = null; for(int i = 0; i < objects.size(); i++){ StepObject obj = objects.get(i); if(obj.isDraggable()){ if(p.x >= obj.pos.x && p.y >= obj.pos.y && p.x <= (obj.pos.x + obj.getWidth()) && p.y <= (obj.pos.y + obj.getHeight())){ curObj = obj; break; } } } ..... } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } }); ``` Any feedback is appreciated. Thanks.
2012/07/11
[ "https://Stackoverflow.com/questions/11439139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215080/" ]
> > I am actually using `Graphics` to draw an image. > > > This has been a user interface problem going back to the earliest, widely-available [object drawing programs](http://en.wikipedia.org/wiki/MacDraw). The common approach is to implement two basic operations that enable the user to expose a hidden object by changing it's rendering order: * Move backward: move the selection one step back in *z*-order. * Move to back: move the selection to the back of the *z*-order. The two complementary operations are usually included: * Move forward: move the selection one step forward in *z*-order. * Move to front: move the selection to the front of the *z*-order. [`GraphPanel`](https://sites.google.com/site/drjohnbmatthews/graphpanel) illustrates several techniques for hit-testing and handling multiple selection in Java 2D. It illustrates the simpler case in which at least *some* of the object is visible. Its rendering order is defined by a simple `List<Node>` model using `ArrayList`, which is not ideal for re-ordering; consider `LinkedList` as an alternative implementation of the `List` interface.
One type of solution is how I've solved this for a chess board. The board is composed of a grid of JPanels that each can hold one or 0 JLabels (that hold the chess piece with an image). If I click on a JPanel that holds a JLabel, the JLabel is kicked up onto the top level window's glasspane and then dragged with the mouse. When the mouse is released, the MouseListener detects what JPanel of the grid I'm over, the chess engine determines if this is a valid move, and if so, the JLabel is added to the JPanel that the mouse cursor is over. If not, the JLabel goes back to its original JPanel. The JPanels use GridBagLayout, and so if a JLabel is added to it, it is displayed centrally in the JPanel cell.
7,277,463
When I run the following program in Python, the function takes the variables in, but completely skips over the rest and re-shows the main menu for the program without doing anything. Plus, it skips the qualifying "if" statements and asks for all the variables even if the first or second options are chosen (which don't need the third variable). BTW, It shouldn't be an indent error, I just indented to show it was code inside stackoverflow. EDIT: NEVERMIND. I got it to work. The variables in the function parenthesis all have to be the same. DUH! *smacks forehead* ``` option = 1 while option !=0: print "\n\n\n************MENU************" print "1. Counting" print "2. Fibbonacci Sequence" print "0. GET ME OUTTA HERE!" print "*" * 28 option = input("Please make a selection: ") #counting submenu if option == 1: print "\n\n*******Counting Submenu*******" print "1. Count up by one" print "2. Count down by one" print "3. Count up by different number" print "4. Count down by different number" print "*" * 28 countingSubmenu = input("Please make a selection: ") x=0 y=0 z=0 q=0 def counting (x, y, z, countingSubmenu, q): x = input("Please choose your starting number: ") y = input("Please choose your ending number: ") if countingSubmenu == 1: for q in range (x, y+1, 1): print q elif countingSubmenu == 2: for q in range (x, y, -1): print q elif countingSubmenu == 3: z = input("Please choose an increment: ") for q in range (x, y+1, z): print q else: z = input("Please choose an increment: ") for q in range (x, y, -z): print q return x, y, z, q if countingSubmenu == 1: counting(countingSubmenu, x, y, z, q) if countingSubmenu == 2: counting(countingSubmenu, x, y, z, q) if countingSubmenu == 3: counting(countingSubmenu, x, y, z, q) if countingSubmenu == 4: counting(countingSubmenu, x, y, z, q) ```
2011/09/01
[ "https://Stackoverflow.com/questions/7277463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/924358/" ]
Your function is defined as `counting (x, y, z, countingSubmenu, q)`, but when you're calling it, you're argument list is `counting(countingSubmenu, x, y, z, q)`.
You didn't mention which version of Python you are using, but I suspect it's from the 3.x series. [Python 3 changed the behavior of input()](http://www.python.org/dev/peps/pep-3111/) to match what was previously raw\_input() in the 2.x series. So, input() now always returns a string. So you either need to call int() or eval() on the result (personally, I suggest int()).
2,430,084
Is there a straightforward way of determining the number of decimal places in a(n) integer/double value in PHP? (that is, without using `explode`)
2010/03/12
[ "https://Stackoverflow.com/questions/2430084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243231/" ]
``` $str = "1.23444"; print strlen(substr(strrchr($str, "."), 1)); ```
Int --- Integers do not have decimal digits, so the answer is always zero. Double/Float ------------ Double or float numbers are approximations. So they do not have a defined count of decimal digits. A small example: ``` $number = 12.00000000012; $frac = $number - (int)$number; var_dump($number); var_dump($frac); ``` Output: ``` float(12.00000000012) float(1.2000000992884E-10) ``` You can see two problems here, the second number is using the scientific representation and it is not exactly 1.2E-10. String ------ For a string that contains a integer/float you can search for the decimal point: ``` $string = '12.00000000012'; $delimiterPosition = strrpos($string, '.'); var_dump( $delimiterPosition === FALSE ? 0 : strlen($string) - 1 - $delimiterPosition ); ``` Output: ``` int(11) ```
2,954,879
Any body can explain me how session works in PHP. for eg. 3 users logged into gmail. how the server identifies these 3 uers. what are the internel process behind that.
2010/06/02
[ "https://Stackoverflow.com/questions/2954879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669388/" ]
Gmail uses Python I think, not PHP. PHP by default writes its sessions to the `/tmp` directory. It can be configured to store the sessions in the database. It identifies the sessions via a cookie, but can also be configured to pass a query string but it is very ugly.
**How Does PHP Session Works** * Firstly PHP creates a unique identifier number (a random string of 32 hexadecimal number, e.g 3c7foj34c3jj973hjkop2fc937e3443) for an individual session. * PHPSESSID cookie passed that unique identification number to users browser to save that number. * A new file is creating to the server with the same name of unique identification number with sess\_ prefix (ie sess\_3c7foj34c3jj973hjkop2fc937e3443.) * Web browser sent that cookie to the server with each request. * If PHP gets that unique identification number from PHPSESSID cookie (on each request), then PHP search in the temporary directory and compare that number and file name. If both are same then it retrieves the existing session otherwise create a new session for that user. A session destroys when the user closes the browser or leaving the site. The server also terminated the session after the predetermined period of session time These are the simple mechanism are using PHP to handle the session. I hope this article with help you to understand how PHP SESSION is working. See this article for more details. [How Does PHP Session Works](http://blog.sohelrana.me/php-session-works/)
14,715,099
And also, why is it not necessary for, eg: ``` printf ("abc") ```
2013/02/05
[ "https://Stackoverflow.com/questions/14715099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2000809/" ]
`NSLog` takes an `NSString` as argument. `@"abc"` denotes an `NSString` because of the @ sign, so that is a valid argument for `NSLog`. `printf` is a normal C function that takes a C string, which is simply created using "".
Because it requires NSString. Adding @declares value as type of NSObject (simplification).
2,312,516
**Edit 2.** Since the question below appears to be open for degree seven and above, I have re-tagged appropriately, and also suggested this on MathOverflow ([**link**](https://mathoverflow.net/a/271653)) as a potential **polymath project**. **Edit 1.** A re-phrasing thanks to a comment below: > > Is it true that, for all $n \in \mathbb{N}$, there exists a degree $n$ polynomial $f \in \mathbb{Z}[x]$ such that both $f$ and $f'$ have all of their roots being distinct integers? (If not, what is the minimal $n$ to serve as a counterexample?) > > > The worked example below for $n = 3$ uses $f$ with roots $\{-9, 0, 24\}$ and $f'$ with roots $\{-18, -4\}$. (See also the note at the end, and the linked arXiv paper.) --- > > **Question.** For all $n \in \mathbb{N}$: Is it possible to find a polynomial in $\mathbb{Z}[x]$ with $n$ distinct $x$-intercepts, and all of its turning points, at lattice points? > > > This is clearly true when $n = 1$ and $n = 2$. A bit of investigation around $n = 3$ leads to, e.g., the polynomial defined by: $$f(x) = x^3 + 33x^2 + 216x = x(x+9)(x+24)$$ which has $x$-intercepts at $(0,0)$, $(-9, 0)$, and $(-24, 0)$. Taking the derivative, we find that: $$f'(x) = 3x^2 + 66x + 216 = 3(x+4)(x+18)$$ so that the turning points of $f$ occur at $(-4, -400)$ and $(-18, 972)$. I am not even sure if this is true in the **quartic**${^1}$ case; nevertheless, this question concerns the more general setting. In particular, is the statement true for all $n \in \mathbb{N}$ and **if not**, then what is the minimal $n$ for which this is not possible? --- $1$. **Will Jagy** kindly resolves $n=4$ since the monic quartic $f$ with integer roots $\{-7, -1, 1, 7\}$ leads to an $f'$ with roots $\{-5, 0, 5\}$. This example is also found as **B5** in the paper [**here**](https://arxiv.org/pdf/math/0407256.pdf) (PDF 22/24). The same paper has the cubic example above as **B1**, and includes a quintic example as **B7**: $$f(x) = x(x-180)(x-285)(x-460)(x-780)$$ $$\text{ and }$$ $$f'(x) = 5(x-60)(x-230)(x-390)(x-684)$$ The linked arXiv (unpublished) manuscript seems to suggest that this problem is open.
2017/06/06
[ "https://math.stackexchange.com/questions/2312516", "https://math.stackexchange.com", "https://math.stackexchange.com/users/37122/" ]
Generalizing Will Jagy's quartic solution as follows. If $a$ and $n$ satisfy the Pell equation $$ a^2+1=2n^2, $$ then the quartic $$P(x)=(x^2-1)(x^2-a^2)$$ works as its derivative is $$ P'(x)=4x(x^2-n^2). $$ Solutions to this Pell equation are found as follows. Let $$ (1+\sqrt2)^{2k+1}=A\_k+N\_k\sqrt2. $$ Then $$ A\_k^2-2N\_k^2=(A\_k+N\_k\sqrt2)(A\_k-N\_k\sqrt2)=(1+\sqrt2)^{2k+1}(1-\sqrt2)^{2k+1}=(-1)^{2k+1}=-1, $$ so $a=A\_k$, $n=N\_k$ is a solution. With $k=1$ we get $A\_1=7$, $N\_1=5$ and Will's polynomial $$ P(x)=(x+7)(x+1)(x-1)(x-7) $$ with derivative $$ P'(x)=4(x+5)x(x-5). $$ Similarly, with $k=2$ we arrive at $A\_2=41$, $N\_2=29$ and the polynomial $P(x)=(x^2-1)(x^2-41^2)$ with extrema at $0$ and $\pm 29$.
Try working backwards: find an integer polynomial $F$ of degree $n-1$ with all integer roots, such that its antiderivative has $n$ distinct roots. One way to check for this by looking for $n$ sign changes. [Here](https://www.wolframalpha.com/input/?i=(antiderivative%205!(x-1)(x-2)(x-3)(x-4))-950)'s an example for $n-4$, I'll edit when I find a general solution.
17,538,558
Please visit my fiddle 1st: <http://jsfiddle.net/vHLXX/> This is phone no. input field, if the length is 11 (value of the text input field) on click on the submit button alerts "yes" else "no". Now, I want if the 1st three string isn't 011 i want alert "invalid!" How can I get this (with jquery)? here is the html: ``` <span>enter you mobile no.</span> <input maxlength="11" size="11" type="text" class="main-input" value=""/> <input type="button" class="Create" value="Submit"> ``` and Jquery Code: ``` $('.main-input').on('keyup', function () { values = $(this).val(); newValue = values.substring(); }); $('.Create').click(function () { if (values.length === 11) { alert("yes"); } else { alert("no"); }; }); ``` PS: Could edit you my fiddle? Thank you.
2013/07/09
[ "https://Stackoverflow.com/questions/17538558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218931/" ]
``` if (values.indexOf("011") != 0) alert("invalid!"); ```
``` $('.main-input').on('keyup', function () { values = $(this).val(); newValue = values.substring(); }); $('.Create').click(function () { if(values.indexOf("011") !== 0){ alert("invalid!"); return; } if (values.length === 11) { alert("yes"); } else { alert("no"); }; }); ``` Above codes firstly, check the input text if it starts with `011`, if not, alert("invalid!"). If so, keep checking if its length is 11.
3,541,963
consider this string ``` prison break: proof of innocence (2006) {abduction (#1.10)} ``` i just want to know whether there is `(# floating point value )}` in the string or not i tried few regular expressions like ``` re.search('\(\#+\f+\)\}',xyz) ``` and ``` re.search('\(\#+(\d\.\d)+\)\}',xyz) ``` nothing worked though...can someone suggest me something here
2010/08/22
[ "https://Stackoverflow.com/questions/3541963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/426791/" ]
On some systems, the `delete` key is defined as an alias to `C-d`. This is done through `function-key-map` on GNU Emacs <23 and `local-function-key-map` on GNU Emacs 23. (I've observed this behavior on Debian and Ubuntu 10.04 under X.) The purpose of such translations is to isolate people who code modes from the terminal intricacies: a mode that wants to shadow the delete command only needs to rebind `C-d` and not wonder if it should rebind `delete` (is that a delete left or delete right?) or `deletechar` or something else. If there is a global or local binding for `delete`, it shadows this translation to `C-d`. However, if you press `ESC delete`, if there is no global or local binding for `ESC delete`, the second key is translated to `C-d`. This translation has precedence over the interpretation of `ESC delete` as `M-delete`. So `ESC delete` becomes equivalent to `C-M-d`. This is arguably a bug in Emacs: the effect of `ESC delete` should be the same as `M-delete`, and there is no reason why `ESC delete` would run `down-list` which has nothing to do with deletion. There are several possible fixes; I don't know which is best. One that should work with any version of Emacs is ``` (global-set-key [?\e delete] 'backward-kill-word) ```
You might want to call `global-set-key` interactively to see how it interprets meta-delete. Also try `local-set-key` to ensure the strange binding is not mode-specific.
440,343
I try to fine-tune a macro depending on whether it is following a specific character/text. E.g., ``` This is it! \great! Wait, what is \great? ``` should become ``` This is it! Grrreeeaaat! Wait, what is great? ``` because the first occurence of `\great` was after an exclamation mark, the second just in the middle of the sentence. So I think I need something like a *look behind* but couldn't find anything except for `\lastbox`. Isn't there something like `\pastlet` complementing `\futurelet`, which allows checking for the next character, i.e. a look ahead?
2018/07/12
[ "https://tex.stackexchange.com/questions/440343", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/97512/" ]
Use the current space factor code. I also load `amsthm` because ``` \documentclass{article} % not needed if amsthm is loaded \def\frenchspacing{\sfcode`\.1006\sfcode`\?1005\sfcode`\!1004% \sfcode`\:1003\sfcode`\;1002\sfcode`\,1001 } %%% \makeatletter \newcommand{\afterbigpunctornot}{% \ifnum\spacefactor>\sfcode`: \expandafter\@firstoftwo \else \expandafter\@secondoftwo \fi } \makeatother \newcommand{\great}{\afterbigpunctornot{G}{g}reat} \begin{document} This is it. \great! Wait, what is \great? This is it! \great! Wait, what is \great? This is it? \great! Wait, what is \great? This is it, \great! Wait, what is \great? This is it; \great! Wait, what is \great? This is it: \great! Wait, what is \great? \frenchspacing This is it. \great! Wait, what is \great? This is it! \great! Wait, what is \great? This is it? \great! Wait, what is \great? This is it, \great! Wait, what is \great? This is it; \great! Wait, what is \great? This is it: \great! Wait, what is \great? \end{document} ``` [![enter image description here](https://i.stack.imgur.com/sHhf4.png)](https://i.stack.imgur.com/sHhf4.png) The idea is that the colon has the highest space factor code among all non “big” punctuation marks. We have to redefine `\frenchspacing` because the default definition just sets all space factor codes to 1000. If you need the change only after the exclamation mark, we have to set its space factor code to a unique one. ``` \documentclass{article} % not needed if amsthm is loaded \sfcode`!=\numexpr\sfcode`!+1\relax \def\frenchspacing{\sfcode`\.1006\sfcode`\?1005\sfcode`\!1004% \sfcode`\:1003\sfcode`\;1002\sfcode`\,1001 } %%% \makeatletter \newcommand{\afterexclamation}{% \ifnum\spacefactor=\sfcode`! \expandafter\@firstoftwo \else \expandafter\@secondoftwo \fi } \makeatother \newcommand{\great}{\afterexclamation{Grrrr}{g}reat} \begin{document} This is it! \great! Wait, what is \great? This is it. \great! Wait, what is \great? This is it? \great! Wait, what is \great? This is it, \great! Wait, what is \great? This is it; \great! Wait, what is \great? This is it: \great! Wait, what is \great? \frenchspacing This is it! \great! Wait, what is \great? This is it. \great! Wait, what is \great? This is it? \great! Wait, what is \great? This is it, \great! Wait, what is \great? This is it; \great! Wait, what is \great? This is it: \great! Wait, what is \great? \end{document} ``` [![enter image description here](https://i.stack.imgur.com/PbMPL.png)](https://i.stack.imgur.com/PbMPL.png)
``` \documentclass[10pt]{report} \sfcode`\!=1001 \newcommand\great{\ifnum\spacefactor=1001 Grrreeeaaat\else great\fi} \begin{document} This is it! \great! Wait, what is \great? \end{document} ``` [![enter image description here](https://i.stack.imgur.com/c6qCe.png)](https://i.stack.imgur.com/c6qCe.png) See also [Detect beginning of a sentence in a macro for capitalization](https://tex.stackexchange.com/questions/4834/detect-beginning-of-a-sentence-in-a-macro-for-capitalization)
8,019,798
I have tried following the FB mobile web "getting started guide" at: <https://developers.facebook.com/docs/guides/mobile/web/> for a web app that I open full-screen on my iphone. but when I try to login using the fb login page that opens up, I get a blank white screen after I click the "login" button. The user IS logged in though.. I know this because if I close and reopen my web app, I check the login status and try to get some user info, and it works fine... When I try the same web app in my desktop's chrome or my iphone's safari, the login process is ok... it break only from within the full screen web app. any ideas?? I'm merely following the sample code from FB :-( thanks.
2011/11/05
[ "https://Stackoverflow.com/questions/8019798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389023/" ]
I found a better answer on this post: [FB.login broken flow for iOS WebApp](https://stackoverflow.com/questions/11197668/fb-login-broken-flow-for-ios-webapp) ``` var permissions = 'email,publish_stream,manage_pages,read_stream'; var permissionUrl = "https://m.facebook.com/dialog/oauth?client_id=" + m_appId + "&response_type=code&redirect_uri=" + encodeURIComponent(m_appUrl) + "&scope=" + permissions; window.location = permissionUrl; ``` Mark's answer above doesn't work anymore... Facebook tend to break things often like this. Showing the login page using window.location does the trick. My app required a refresh after my login, so it worked out great. So you might have to rethink your flow if you don't want refresh.
I have found a workaround to the issue... seems there is an undocumented 'redirect\_uri' attribute I can use in the login() method, e.g. ``` login({scope:'email', redirect_uri:'where_to_go_when_login_ends'}) ``` It IS documented for fb desktop SDKs, so I gave it a go and it sort of works. When I say "sort of", I mean that on web mobile, it seems ok, but if you try to run it in a desktop browser, the login popup will redirect to the given url within the login popup - not within its parent window. I hope this is good enough and does not cause any side effects, I really can't tell. But this is what I'll use in the meantime for lack of other options :^)
44,726,664
I have two MySQL tables, one named "stations" and another named "records." "stations" is related to the records listed in "records" by **stations.id=records.stationID**. Many of my "stations" are not related to any data which appears in the "records" table, and I would like to delete the rows of "stations" in which their corresponding id does not match any value in records.stationID. I have tried: ``` DELETE FROM stations WHERE stations.id NOT IN (SELECT DISTINCT records.stationID FROM records); ``` which worked in principle, but I let it run for 8 hours overnight and it hadn't completed in the morning. I think this is because it requires the subquery to be executed for each record in "stations," which contains 9000+ rows. (is that correct?) How can I expedite the deletion process? I've tried various inner joins as well, i.e.: ``` DELETE FROM stations INNER JOIN records on stations.id=records.stationID WHERE stations.id not in records.stationID; ``` which gives me a syntax error. I also tried the following, which don't appear to do anything, really: ``` DELETE stations.* FROM stations INNER JOIN records ON records.stationID=stations.id WHERE stations.id NOT IN (SELECT DISTINCT records.stationID FROM records); ``` and ``` DELETE FROM stations INNER JOIN records on records.stationID=stations.id WHERE stations.id NOT IN (SELECT DISTINCT records.stationID from records); ``` Any ideas? **SOLVED:** I just needed to add an index to the "records" table. Thanks to all for the help
2017/06/23
[ "https://Stackoverflow.com/questions/44726664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6382627/" ]
Try to use this: ``` DELETE stations FROM stations LEFT JOIN records on stations.id=records.stationID WHERE records.stationID IS NULL; ``` Also check do you set index for `records.stationID`.
Try a **LEFT OUTER JOIN :** ``` SELECT * FROM stations LEFT OUTER JOIN records ON stations.stationID= records.stationID WHERE records.stationID IS null ```
23,245
I hesitate between which and that after because: > > I prefer orange cars because blue cars would be thought of as the police(,) **which/that** is always aggressive. > > > Is it a restrictive/non-restrictive issue here?
2014/05/12
[ "https://ell.stackexchange.com/questions/23245", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/6391/" ]
There are two issues here: * The relative clause is non-restrictive clause, and only *wh-* forms may head non-restrictive relative clauses. Both *wh-* and *that* may head restrictive relative clauses. In restrictive clauses, but not non-restrictive clauses, the relativizer may be omitted if it does not stand for the subject of the relative clause (as it does in your example). * At least in US usage, *the police* is considered a body of people and referred to with *who* rather *which*, so if you wish to say that the police are always aggressive you should use *who*. > > I prefer orange cars because blue cars would be thought of as the police, who are always aggressive. > > > It may be, however, that what you are trying to say is that the use of *blue cars* arouses thoughts of aggressiveness, just as it arouses thoughts of the police. It is true that a *which* clause in this position leads the reader to think that the referent of *which* is the entire preceding clause, *blue cars would be thought of as the police*. But it is not idiomatic English to say that this thought is *always aggressive*—that would mean that the thought was threatening to attack you! What you should say in this case is something more like > > I prefer orange cars because blue cars would be thought of as the police, which always suggests aggressiveness. > > >
'which' is used before non-restrictive clause whereas 'that' is used before restrictive clause. Restrictive clause forms unavoided part of the sentence which cannot be left off and non-restrictive clauses are avoidable clauses which cannot be peeled off the sentence. Here police which normally is considered aggressive makes clause 'always aggressive' non-mandatory so you can use 'which' in that senetence.
56,271,938
``` (async function iife () { const numbers = [1, 2, 3, 4] let count = 0 async function returnNumberAsync (number) { return new Promise(resolve => { setTimeout(() => resolve(number), 0) }) } await Promise.all(numbers.map(async number => { count += await returnNumberAsync(number) })) console.log(count) })() ``` This snippet logs `4` to the console, which is completely beyond me. As soon as I assign the promised value inside `map` to its own local variable … ``` const result = await returnNumberAsync(number) count += result; ``` … it logs `10` like I'd expect. What's happening when I `count += await …`??
2019/05/23
[ "https://Stackoverflow.com/questions/56271938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2072165/" ]
When you do `count += await <expression>`, the initial value of `count` to be added to the resolve value is saved *before* the `await` part is resolved. So ``` count += await returnNumberAsync(number) ``` is like ``` count = count + await returnNumberAsync(number) ``` as you can see: ```js (async function iife () { const numbers = [1, 2, 3, 4] let count = 0 async function returnNumberAsync (number) { return new Promise(resolve => { setTimeout(() => resolve(number), 0) }) } await Promise.all(numbers.map(async number => { count = count + await returnNumberAsync(number) })) console.log(count) })() ``` In each of the 4 closures, `count` is seen to be 0 before the `await`s resolve, so only in the final `await` microtask, where it resolves to ``` count += await returnNumberAsync(4) // or count = 0 + await returnNumberAsync(4) // or count = 4 ``` does `4` get assigned to `count`. The fact that other numbers were assigned to `count` earlier is ignored. They did happen, but the assignment of the final iteration is all you see with the current code.
It would be more clear what is happening if you rewrite the `async/await` inside the `map()` to `.then`. ```js function returnNumberAsync(number) { return new Promise(resolve => { setTimeout(() => resolve(number), 0); }); } (async function iife() { const numbers = [1, 2, 3, 4]; let count = 0; await Promise.all( numbers.map(number => Promise.resolve(count).then(temp => returnNumberAsync(number).then(res => { count = temp + res; }) ) ) ); console.log(count); })(); ```
34,310,679
When I push up to bitbucket using Sourcetree app I get the following code placed into my files. Is there a way I can stop this from happening, My merges are fine when I commit my changes. ``` <<<<<<< HEAD >>>>>>> de31d33546973a5ebe11787596ffbb4a8000d6fe ``` Thanks
2015/12/16
[ "https://Stackoverflow.com/questions/34310679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5138922/" ]
Those mean you have conflicts in your files and you should resolve them. Go through all files having that and compare between code under `HEAD` and code under `de31d33546973a5ebe11787596ffbb4a8000d6fe`, then keep only what you need. > > > ``` > <<<<<<< HEAD > > ``` > > code of HEAD > > > > ``` > >>>>>>> de31d33546973a5ebe11787596ffbb4a8000d6fe > > ``` > > code of de31d33546973a5ebe11787596ffbb4a8000d6fe > > >
When I face the same problem. the best way to get rid of is to **reset all changes,** and to push the last commit to repository. Or you have to solve all the conflicts in the files before pushing them to repository.
33,366,624
I'm trying to launch Jupyter with a base directory being the root of my second hard drive. I used to be able to do that just fine with Ipython 3.x until I upgraded to the latest version. If I cd to D:\ and type `jupyter notebook --debug` the end of the trace I get is: ``` [I 12:15:14.792 NotebookApp] Refusing to serve hidden directory, via 404 Error [D 12:15:14.792 NotebookApp] Using contents: services/contents [W 12:15:14.813 NotebookApp] 404 GET /tree (::1) 23.00ms referer=None [D 12:15:15.062 NotebookApp] 304 GET /custom/custom.css (::1) 152.00ms ``` I've tried running the command from an elevated command prompt but to no avail. **How can I run jupyter at the root of my D:\ drive on Windows?**
2015/10/27
[ "https://Stackoverflow.com/questions/33366624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2543372/" ]
I am able to see hidden files and folders by launching `jupyter lab` from the command line with the following command: `jupyter lab --ContentsManager.allow_hidden=True` To do this I: * Click the `Anaconda3 (64-bit) menu, then * Click the `Anaconda3 Prompt (anaconda3)` from the Windows menu. * I pasted in the command above and hit `Enter.` The default web browser loads with the `jupyter lab` interface and I can see hidden files and folders. Specifically I am using the to see the hidden `.aws` directory.
a few days ago i had same problem . When you arrange files sharing rules in windows machine , python files can be being hidden unknowingly while you want to hide another files , too . if jupyter files are in the hidden files like i mentioned above , it has solved by doing this steps; 1. Go to computer , 2. Hit Alt on the keyboard 3. and then hit Tools tab 4. Select Files Option from the tools tab 5. Select view tab from opened Files Option screen 6. Hit Show hidden files radio button at the Advanced tab After doing these steps , this problem had solved in my computer.
58,345,027
there is a number like ``` int a = 12345; ``` I need to do it separately ``` int arr[4]{1,2,3,4,5}; ``` But the fact is, I don’t know what the number will be it can be long or short.
2019/10/11
[ "https://Stackoverflow.com/questions/58345027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11209230/" ]
Think about what happens when you divide a number by 10. What is 12345 divided by 10? It is 1234. How much is the remainder of that division? It is 5. You've now split the least significant digit from the rest. How might you get the next digit? Keep in mind that you already have 1234. Well, you repeat the division by 10 and now you have 123 and 4. Repeat until you no longer have digits. There's the algorithm that you're looking for. This works with 10 because that is the radix (i.e. base) of the decimal representation. The same algorithm works with other representations by using the radix in question. This algorithm demonstrates how dividing by radix corresponds to "shifting" digits right (multiplication shifts left) and remainder operation "masks" away all digits except least significant one.
Here is my code. ``` // num is input number void split(long long num) { int i; vector<long long> ve; ve.clear(); while(num>0){ long long rem=num%10; ve.pb(rem); num/=10; } //for output array reverse(ve.begin(),ve.end()); for(i=0;i<ve.size();i++) cout<<ve[i]<<endl; } ``` Let me know if you have any questions.
8,602,949
I have a question about Url.Action. My position is on <http://localhost/User/Edit> and for some case I have to generate a link with a javascript function, so it would be like this: ``` return '<a href="@Url.Action("Group","Edit")/' +myParameterInJavascript +'>link</a>'; ``` If I look to the link, it would be ok, I got: <http://localhost/Group/Edit/ParameterFromJs> But, then when my current position is <http://localhost/Group/Edit/ParameterFromJs> and I generate the same link again, the URL will become : <http://localhost/Group/Edit/ParameterFromJs/ParameterFromJs> Why don't I just get the url <http://localhost/Group/Edit/ParameterFromJs>? Why was my action Edit/ParameterFromJs, and not just Edit? Can you give me some hint or tips? Thanks in advance UPDATE : This is my routing: ``` routes.MapRoute("group-edit", "Group/Edit/{groupName}", new { controller = "Group", action = "Edit" } ); ```
2011/12/22
[ "https://Stackoverflow.com/questions/8602949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/865343/" ]
Try using routing: ``` var url = '@Url.Action("Group", "Edit", new { id = "__id__" })'.replace('__id__', myParameterInJavascript); return '<a href="' + url + '">link</a>'; ```
Try to use something like that: ``` <a href="@Url.Action("Edit", "Group", new { EditParam = myParameterInJavascript })"> ``` When You put parameter use "?" not "/" ``` http://localhost/Group/Edit?ParameterFromJs ```
14,341,782
Is there any way to implement cross database querying in Entity Framework? Let's imagine I've two Entities User and Post, User entity is in database1 and Post is in database2, which means those entities are in separate databases. How should I get user's posts in Entity Framework ?
2013/01/15
[ "https://Stackoverflow.com/questions/14341782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/560153/" ]
I know this is an old question, but this is actually possible. If the databases are on the same server, then all you need to do is use a `DbCommandInterceptor`. As an example, if I attach a `DbCommandInterceptor` to `MyContext`, I can intercept all command executions and replace the specified table(s) in the query with my full-db paths. ``` public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) { // Here, I can just replace the CommandText on the DbCommand - but remember I // want to only do it on MyContext var context = contexts.FirstOrDefault() as MyContext; if (context != null) { command.CommandText = command.CommandText .Replace("[dbo].[ReplaceMe1]", "[Database1].[dbo].[Customers]") .Replace("[dbo].[ReplaceMe2]", "[Database2].[dbo].[Addresses]") .Replace("[dbo].[ReplaceMe3]", "[Database3].[dbo].[Sales]"); } base.ReaderExecuting(command, interceptionContext); } ``` The nice thing also about this approach is that the EF Model Mapping still works properly and respects column attributes, requires no views, and requires no stored procedures.
No, you can't. You will have to create to contexts and do the joining your self. See [here](https://stackoverflow.com/questions/7404690/can-you-have-a-dbcontext-that-is-associated-with-multiple-databases). You could resolve to database trickery, creating a view in one database the reflects a table in the other one.
1,217,460
I have a multiline Bash variable: `$WORDS` containing one word on each line. I have another multiline Bash variable: `$LIST` also containing one word on each line. I want to purge `$LIST` from any word present into `$WORDS`. I currently do that with a `while read` and `grep` but this is not sexy. ``` WORDS=$(echo -e 'cat\ntree\nearth\nred') LIST=$(echo -e 'abcd\n1234\nred\nwater\npage\ncat') while read -r LINE; do LIST=$(echo "$LIST" | grep -v "$LINE") done <<< "$WORDS" echo "$LIST" ``` I think I can do it with `awk` but did not managed to make it work. Can someone explain me how to do it with awk?
2017/06/08
[ "https://superuser.com/questions/1217460", "https://superuser.com", "https://superuser.com/users/124122/" ]
This should accomplish what you're trying to do. ``` WORDS=$(echo -e 'cat\ntree\nearth\nred') LIST=$(echo -e 'abcd\n1234\nred\nwater\npage\ncat') echo "$LIST" | awk -v WORDS="$WORDS" ' BEGIN { split(WORDS,w1,"\n") for (w in w1) { w2[w1[w]] = 1 } } { if (w2[$0] != 1) { print $0 } }' ``` Here's how it works. First I'm using the `-v` option on the awk command line to pass the list of words as a variable. This variable will be visible inside the awk program with the name WORDS. The BEGIN block gets executed before any input is processed. It contains two lines ``` split(WORDS,w1,"\n") ``` This split command takes the WORDS list and turns it into an array called w1. ``` for (w in w1) { w2[w1[w]] = 1 } ``` This for loop walks through the w1 array and generates an associative array called w2. Converting the array to an associative array will improve performance. Next we have the main body of the loop that processes the LIST. ``` if (w2[$0] != 1) { print $0 } ``` This will check each line of input against our associative array and only print the line if the word was not found. Since we assigned each key to be 1 in our BEGIN block, we need only check to see if the value of that key equals 1 to know if it is defined.
I suggest ``` echo "$LIST" | grep -vf <(echo "$WORDS") ```
4,408,813
I'm converting an image from .png to .eps and it hugely increases the file size. Can anyone explain why this is, and how to prevent it increasing so much. I'm using Unix [convert](http://www.imagemagick.org/script/convert.php): `convert image.png image.eps` Thanks for any help
2010/12/10
[ "https://Stackoverflow.com/questions/4408813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/418810/" ]
Converting a PNG file (designed for bitmap data) into an EPS (designed for vector data) is always going to result in a larger file size, as the EPS is effectively just wrapping an EPS data structure around the original image data (which it most likely won't store in anywhere near as effective a manner as a PNG file). The correct solution is to store bitmaps as PNGs and vector graphics as EPS or SVG, etc. (i.e.: Use the appropriate file format for the content in question rather than attempting to impose a meaningless "one size fits all" approach.)
It is possible that the problem is that the `convert` application you use just does not support embedding PNG into EPS. When using properly configured Adobe Acrobat Professional I newer got unexpectedly huge increase of the file size. But you should properly configure first your "PNG to PDF" conversion settings. Then you should export (or Save As) generated PDF as EPS from Acrobat.
187,415
I try to launch Firefox over SSH, using ``` ssh -X user@hostname ``` and then ``` firefox -no-remote ``` but it's very very slow. How can I fix this? Is it a connection problem?
2015/02/28
[ "https://unix.stackexchange.com/questions/187415", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/90717/" ]
X11 is an outdated protocol. For example if a software writes the letter "A" over and over into the same spot it will be retransmitted over and over again. A lot of modern GUIs tend to redraw stuff which didn't change and X11 will happily retransmit every atomic screen-output. In other words, it does not transmit pixels but commands. This is the opposite how VNC and Teamviewer are working which basically are transfering pixels. This also leads to a partially synchronous operation where one command has to wait for another command to finish. SSH uses a ton of CPU power and doesn't multithread. For example my server is running SSH on a single core at 100% but this only equals to around 20MByte/s of uncompressed data and around 5MByte/s of compressed data for X11. Firefox is highly X11 unfriendly. It rarelly uses commands - which X11 could handle efficiently - but mostly small and badly compressable bitmaps which it packs into X11 bitplane operations. Combining two things which should never come close anyway. Worst case: Any small animation. Even a 64x64 pixel animated GIF can literally freeze your firefox connection. That said lets dive deeper. On a highspeed line - e.g. 100Mbit or higher - compression is usually more of a burden than a bone. Your milage may vary. Try ssh with "-C". With SSH2 there is no more manual selection of compression level, you stuck with something comparable to "gzip -3" or have to do some trickery tunneling. It might be possible to get faster compression using the pretty fast "lzop -1" or better compression using "xz -9e". I played around with "lzop -1" some ten years ago and results where unimpressive. The speed of your crypto stuff depends a lot on your CPU. See <https://possiblelossofprecision.net/?p=2255> for a easy way to check which cypher runs fastest on your system. Expect two times of speed between fastest and slowest. Though over the last 20 years I have never seen a slow cypher as standard, the cypher usually are defaulting to something close to the fastest. Now here is you best bet: Disable Hardware-Acceleration in Firefox. This is rarelly required as Firefox disables it anyway over Network but in some circumstances it fails to do so and thats where Firefox gets really, really, really slow. This is all one can say about Firefox, SSH and X11. If this doesn't do the trick try something else: Run X11 without SSH by doing something like this on the X11-Server ``` startx -- -listen tcp & sleep 5 export DISPLAY=:0 xhost +yourx11client +yourx11client.local ``` and on the X11-client: ``` export DISPLAY=yourx11server:0 ``` Hint, X11 server and client nominations are "reversed". The server is the display, the client is running the application. This will easily speed up Firefox ten times. Though some pages will still make it very sluggish and unresponsive, e.g. videos. An even more drastic step: Drop X11 as a network protocol, use VNC. Either by using a remote screen or a fully virtualized VNC session: ``` vncserver :1 -name VNC1 -geometry 1024x768 -depth 15 ``` and in $HOME/.vnc/xstartup something like: ``` #!/bin/sh # Uncomment the following two lines for normal desktop: unset SESSION_MANAGER exec /etc/X11/xinit/xinitrc [ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup [ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources xsetroot -solid grey xterm -geometry 80x30 ``` I highly suggest using the xsetroot command as default X11 background looks horrible and is hard to compress. Connect with any VNC-Client you like. I have been able to watch TV and play games over this kind of VNC connection. You can even run multiple vncservers for multiple users at once. This is by far the most responsive remote system.
Also we got a good solution with Xvfb (X virtual framebuffer) on remote server as admin (Centos 7 example) ``` yum install Xvfb xauth x11vnc firefox ``` on remote server as normal user ``` Xvfb :1 & x11vnc -display :1 --localhost & export DISPLAY=:1 firefox ``` on local computer: ``` vncviewer -via www.example.com 127.0.0.1 ``` Another solution is xpra ------------------------ <https://wiki.archlinux.org/title/Xpra#Run_applications_in_a_persistent_xpra_server_on_the_remote_host> on server: ``` xpra start :100 DISPLAY=:100 firefox ``` on client: ``` xpra attach --ssh="ssh" ssh:user@serverhost:100 ```
223,075
On all web services that require passwords, like gmail, you are asked to set a long password. Like 8 characters or more. The reason being higher security. But the same services limit the number of login attempts to 3-4 tries before locking your account and asking for more info. Something which I find very annoying, but that's another topic. So how is a short password insecure if they limit login attempts? If the password has 5 characters someone cannot try all combinations in just 3 attempts.
2019/12/21
[ "https://security.stackexchange.com/questions/223075", "https://security.stackexchange.com", "https://security.stackexchange.com/users/187422/" ]
It's not as simple... ### About online brute force If an account becomes completely locked after 3 attempts, it will be easy to make a [*`DOS`* (Denial Of Service) attack](https://en.wikipedia.org/wiki/Denial-of-service_attack) by locking all accounts! Servers have to base locking decision not only on number of bad tries, but will use IP address, browser ID and include *duration* for locking, so that if someone just used the wrong keyboard, they will be able to reconnect in some *delay*... From there, considering *`botnets`*, an attacker could use a lot of different IP addresses and make many different tries. With some `smooth` options and long delays, ***short passwords*** become weak. * Example: Considering a full brute force against 5 characters chosen from `a-z, A-Z, 0-9, $+"*/%&()_`: 72 characters ``` 72^5 => 1'934'917'632 # all possible combinations 72^5 / 300000 => 6'449 # botnet 72^5*900/300000/3 => 1'934'917 # 3 attempts -> 15' penalty ``` In seconds: this represents ~22 days to test all combinations. Note 1: 300000 machines is some arbitrary mean value from [Botnet @Wikipedia](https://en.wikipedia.org/wiki/Botnet#Historical_list_of_botnets). For a 6M botnet, the job will end in approximately one day. Note 2: the same calculation with a 12-character-long password will result in approximately 615'015'399'199 years. ### About offline brute force Passwords are commonly stored *hashed*. If someone could steal your password file (by using remote exploit, social engineering or else), they could use **brute force** against the *hash* stored in the password file. From there, the attacker is not limited to 3 attempts anymore!! If your password length is >= 12 characters: `72^12 => 19'408'409'961'765'342'806'016`. This becomes heavy, even through botnet... But any [`john`-like password cracker](https://www.openwall.com/john/) will browse the stolen password file and extract quickly all common word based passwords and all short passwords. Brute force, by using the fastest supercomputer in 2019, could check up to 10^14 tests / second... (see [Brute-force attack on Wikipedia](https://en.wikipedia.org/wiki/Brute-force_attack)). So: ``` 72^12 / 10^14 = 194084099 => more than 6 years. ``` ### About long password vs passphrases Because I prefer (whenever possible) to use passphrases instead of passwords, I really like this [XKCD's strip (/936)](https://xkcd.com/936/): [![XKCD 936](https://i.stack.imgur.com/iLkQA.png)](https://i.stack.imgur.com/iLkQA.png) ... With 5 words instead of 4. Here is a small mathematical demo: * Considering a 12-letter password with 72 characters bunch: ``` $ bc <<<72^12 19.408.409.961.765.342.806.016 -> >6 years ``` * Considering 5 words **randomly** chosen in American dictionary with words containing 5 to 9 plain letters (a-z, no accents): ``` $ bc <<<"$( LANG=C grep '^[a-z]\{5,9\}$' /usr/share/dict/american-english| wc -l) ^ 5" 122.045.635.410.545.172.078.149 -> >38 years ``` even more combinations, with minimal phrase length: 5x5=25 alphabetical letters: ``` bc <<<'26^25' 236.773.830.007.967.588.876.795.164.938.469.376 ``` (Nota brute force cracking passphrase implie combination of letters, this will reduce the total combination, but stay higher than `41'429 ^ 5`... 41429 is the result of `wc -l` in my previous test) You could even add some *salt* by adding caps, numbers, and/or any special characters... while you're still able to remember them!
To prevent "password spraying" where someone tries a common password against many accounts.
2,834,263
I want to change an image periodically in a `UIImageView` in my application, and the image will come from the web. Can I run JavaScript enabled pages in a `UIWebView`? Or are there any other ways to implement this?
2010/05/14
[ "https://Stackoverflow.com/questions/2834263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/221325/" ]
Fully qualify the exception type. ``` public void insertIntoCell.. throws com.sun.star.lang.IndexOutOfBoundsException { } ``` I'm presuming here that you do not intend to throw `java.lang.IndexOutOfBoundsException`, which is an unchecked `RuntimeException`, but I could be wrong. You can also use a [single-type import declaration](http://java.sun.com/docs/books/jls/third_edition/html/packages.html#7.5.1) instead: ``` import com.sun.star.lang.IndexOutOfBoundsException; //... public void insertIntoCell.... throws IndexOutOfBoundsException { } ``` But this can potentially cause a lot more confusion down the pipe.
IndexOutOfBoundsException is ambiguous because there are two classes named IndexOutOfBoundsException within two different packages (com.sun.star.lang and java.lang). You need to tell the compiler which one you mean by prefixing IndexOutOfBoundsException with the correct package name.
36,765,142
I have an xElement data `<a><item><item1/><item2/></item></a>` Need to replace item node with another node . How can we achieve this? I just need to replace item node with some other node say `<b><b1/></b>` I want output as `<a><b><b1/></b></a>`
2016/04/21
[ "https://Stackoverflow.com/questions/36765142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3913587/" ]
This never worked for me on Windows 10 even if it is a linux container: ``` -v /var/run/docker.sock:/var/run/docker.sock ``` But this did: ``` -v /usr/local/bin/docker:/usr/bin/docker ``` Solution taken from this issue i opened: <https://github.com/docker/for-win/issues/4642>
This is what actually made it work for me ``` docker run -p 8080:8080 -p 50000:50000 -v D:\docker-data\jenkins:/var/jenkins_home -v /usr/local/bin/docker:/usr/bin/docker -v /var/run/docker.sock:/var/run/docker.sock -u root jenkins/jenkins:lts ```
53,691,618
I'm building a React Native app using TypeScript. I'm trying to use a [`SectionList`](https://facebook.github.io/react-native/docs/sectionlist). I followed the docs, and here is my code: ``` renderSectionHeader = ({ section: { title } }: { section: { title: string } }) => ( <ListItem title={title} /> ); render() { const { sections } = this.props; return ( <SafeAreaView style={styles.container}> <SectionList keyExtractor={this.keyExtractor} sections={[ {title: 'Title1', data: ['item1', 'item2']}, {title: 'Title2', data: ['item3', 'item4']}, {title: 'Title3', data: ['item5', 'item6']}, ]} renderItem={this.renderItem} renderSectionHeader={this.renderSectionHeader} /> </SafeAreaView> ); } ``` But the line `renderSectionHeader={this.renderSectionHeader}` throws the following TSLint Error: ``` [ts] Type '({ section: { title } }: { section: { title: string; }; }) => Element' is not assignable to type '(info: { section: SectionListData<any>; }) => ReactElement<any> | null'. Types of parameters '__0' and 'info' are incompatible. Type '{ section: SectionListData<any>; }' is not assignable to type '{ section: { title: string; }; }'. Types of property 'section' are incompatible. Type 'SectionListData<any>' is not assignable to type '{ title: string; }'. Property 'title' is missing in type 'SectionListData<any>'. [2322] ``` Are the types of `SectionList` broken? Or is the example wrong? Or am I doing something wrong?
2018/12/09
[ "https://Stackoverflow.com/questions/53691618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8331756/" ]
This is the `SectionListData` declaration, so you just need to remove the `title` property, and replace it with `key`, then `TSLint Error` will disappear. ``` export interface SectionBase<ItemT> { data: ReadonlyArray<ItemT>; key?: string; renderItem?: SectionListRenderItem<ItemT>; ItemSeparatorComponent?: React.ComponentType<any> | null; keyExtractor?: (item: ItemT, index: number) => string; } export interface SectionListData<ItemT> extends SectionBase<ItemT> { [key: string]: any; } ``` [enter image description here](https://i.stack.imgur.com/L4Boz.png)
The following works for me ``` interface Group { title: string; data: readonly Item[]; // Important to add readonly } private scroll: RefObject<SectionList<Item>>; public renderItem = ({ item }: ListRenderItemInfo<Item>): ReactElement => ( <ReactItem /> ); public renderSectionHeader = ({ section, }: { section: SectionListData<Item>; }): ReactElement | null => ( <ReactSectionHeader /> ) const groupedItemToRender = [ { title: 'title1', data: [ItemObject, ItemObject] }, { title: 'title2', data: [ItemObject, ItemObject] }, ]; <SectionList ref={this.scroll} sections={groupedItemToRender} renderItem={this.renderItem} renderSectionHeader={this.renderSectionHeader} /> ```
32,184
If a layer 2 managed switch supports management functions and entails a "management plan" it must require an OS. If it is a typical network operating system, \*nix based, does is have a full file system? Would I be able to write an application and run it on the cpu of the switch?
2016/06/12
[ "https://networkengineering.stackexchange.com/questions/32184", "https://networkengineering.stackexchange.com", "https://networkengineering.stackexchange.com/users/21360/" ]
I think it depends what brand and what OS it is running. Cisco devices run their own proprietary version of IOS, which as far as I know doesn't support custom applications. Juniper, on the other hand, is running JunOS based on FreeBSD, so there might be some chance, but I think it will be limited at best. Some small companies may use something like embedded linux, since they probably won't develop their own system. To sum it up, it depends on the manufacturer and what OS are they using. But even if you can develop application, it will have very limited resources, as network devices are designed specifically for their function and many features use special hardware instead of software (especially on switch).
As a philosophy ARISTA encourages customers and partners to run standard Linux applications on their switches, publishing all necessary APIs etc. As for resources, ARISTA is making very low latency-switches with high port density for 10G/40G/100G, and therefore high CPU power and ample memory is provided. One example of such an integrated application is Splunk for network monitoring/statistics.
7,456,148
I'm looking for an algorithm to overlay a color on top of existing picture. Something similar to the following app (wall painter): <http://itunes.apple.com/us/app/wall-painter/id396799182?mt=8> I want a similar functionality so I can paint walls in an existing picture and change them to a different color. I can work both in yuv or rgb mode.
2011/09/17
[ "https://Stackoverflow.com/questions/7456148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306764/" ]
Look at the [time](http://linux.die.net/man/7/time) command. It tracks both the CPU time a process uses and the wall-clock time. You can also use something like [gprof](http://sourceware.org/binutils/docs/gprof/) for profiling your code to find the parts of your program that are actually taking the most time. You could do a lower-tech version of profiling with timers in your code. [Boost](http://www.boost.org/) has a nice [timer](http://www.boost.org/doc/libs/1_47_0/libs/timer/) class, but it's easy to roll your own.
What do you use for timing execution time so far? There's C89 `clock()` in `time.h` for starters. On unixoid systems you might find `getitimer()` for `ITIMER_VIRTUAL` to measure process CPU time. See the respective manual pages for details. You can also use a POSIX shell's `times` utility to benchmark the processor time used by a process and its children. The resolution is system dependent, like just anything about profiling. Try to wrap your C code in a loop, executing it as many times as necessary to reduce the "jitter" in the time the benchmarking reports.
32,919,631
Ionic modal comes with the standard animation of `slide-in-up`. Is it possible that we can change the animation to `fade-in`?
2015/10/03
[ "https://Stackoverflow.com/questions/32919631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1995781/" ]
In order to add custom transitions for Ionic Modal We will be using Ionic Modal Options `enterAnimation` and `leaveAnimationfrom` ModalOptions interface. For a modal there are transition states: On Enter of modal and and On Leave of modal when we close it. If you look at the Ionic Modal options interface you will find 2 options to add animations for both the states. ``` export interface ModalOptions { showBackdrop?: boolean; enableBackdropDismiss?: boolean; enterAnimation?: string; leaveAnimation?: string; cssClass?: string; } ``` We will use these options in modal to specify transition class we create using Animation class from `ionic-angular`. So lets see how we can create and custom animations step by step. Create 2 transition classes for enter and leave: **on-enter-translate.transition.ts** ``` import { Animation, PageTransition } from 'ionic-angular'; export class ModalTranslateEnterTransition extends PageTransition { public init() { const ele = this.enteringView.pageRef().nativeElement; const wrapper = new Animation(this.plt, ele.querySelector('.modal-wrapper')); wrapper.beforeStyles({ 'transform': 'translateX(100%);', 'opacity': 1 }); wrapper.fromTo('transform', 'translateX(100%)', 'translateX(0)'); wrapper.fromTo('opacity', 1, 1); this .element(this.enteringView.pageRef()) .duration(500) .easing('cubic-bezier(.1, .7, .1, 1)') .add(wrapper); } } ``` **on-leave-translate.transition.ts** ``` import { Animation, PageTransition } from 'ionic-angular'; export class ModalTranslateLeaveTransition extends PageTransition { public init() { const ele = this.leavingView.pageRef().nativeElement; const wrapper = new Animation(this.plt, ele.querySelector('.modal-wrapper')); const contentWrapper = new Animation(this.plt, ele.querySelector('.wrapper')); wrapper.beforeStyles({ 'transform': 'translateX(100%)', 'opacity': 1 }); wrapper.fromTo('transform', 'translateX(0)', 'translateX(100%)'); wrapper.fromTo('opacity', 1, 1); contentWrapper.fromTo('opacity', 1, 0); this .element(this.leavingView.pageRef()) .duration(500) .easing('cubic-bezier(.1, .7, .1, 1)') .add(contentWrapper) .add(wrapper); } } ``` Then import those modules in **app.module.ts** ``` export class AppModule { constructor(public config: Config) { this.setCustomTransitions(); } private setCustomTransitions() { this.config.setTransition('modal-translate-up-enter', ModalTranslateEnterTransition); this.config.setTransition('modal-translate-up-leave', ModalTranslateLeaveTransition); } } ``` And create modal using following options: ``` var modal = this.modalCtrl.create(AddToCartModalPage, { productId: this.productId, skuId: this.skuId, zipcode: this.zipcode, sellerProfileId: this.sellerProfileId, branchId: this.branchId, changeSeller: this.changeSeller }, { showBackdrop: false, enableBackdropDismiss: false, cssClass: 'add-to-cart-modal', enterAnimation: 'modal-translate-up-enter', leaveAnimation: 'modal-translate-up-leave' }); ``` Find more information my article here: [Blog](https://www.vistaran.tech/blog/ionic-modals-custom-transitions/) Find complete demo repository here: [Github](https://github.com/vistaran/ionic-modal-custom-transitions)
You can add your own animation css, ex: ``` .slide-in-right { -webkit-transform: translateX(100%); transform: translateX(100%); } .slide-in-right.ng-enter, .slide-in-right > .ng-enter { -webkit-transition: all cubic-bezier(0.1, 0.7, 0.1, 1) 400ms; transition: all cubic-bezier(0.1, 0.7, 0.1, 1) 400ms; } .slide-in-right.ng-enter-active, .slide-in-right > .ng-enter-active { -webkit-transform: translateX(0); transform: translateX(0); } .slide-in-right.ng-leave, .slide-in-right > .ng-leave { -webkit-transition: all ease-in-out 250ms; transition: all ease-in-out 250ms; } ``` and usage with 'slide-in-right' the same for 'fade-in' <https://forum.ionicframework.com/t/slide-in-right-animation-for-ionicmodal/18882>
690,176
Have a look at this code: ``` #include <iostream> using namespace std; int main() { const char* str0 = "Watchmen"; const char* str1 = "Watchmen"; char* str2 = "Watchmen"; char* str3 = "Watchmen"; cerr << static_cast<void*>( const_cast<char*>( str0 ) ) << endl; cerr << static_cast<void*>( const_cast<char*>( str1 ) ) << endl; cerr << static_cast<void*>( str2 ) << endl; cerr << static_cast<void*>( str3 ) << endl; return 0; } ``` Which produces an output like this: ``` 0x443000 0x443000 0x443000 0x443000 ``` This was on the *g++* compiler running under *Cygwin*. The pointers all point to the same location even with no optimization turned on (`-O0`). Does the compiler always optimize so much that it searches all the string constants to see if they are equal? Can this behaviour be relied on?
2009/03/27
[ "https://Stackoverflow.com/questions/690176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
You surely *should not* rely on that behavior, but most compilers will do this. Any literal value ("Hello", 42, etc.) will be stored once, and any pointers to it will naturally resolve to that single reference. If you find that you need to rely on that, then be safe and recode as follows: ``` char *watchmen = "Watchmen"; char *foo = watchmen; char *bar = watchmen; ```
No, it can't be relied on, but storing read-only string constants in a pool is a pretty easy and effective optimization. It's just a matter of storing an alphabetical list of strings, and then outputting them into the object file at the end. Think of how many "\n" or "" constants are in an average code base. If a compiler wanted to get extra fancy, it could re-use suffixes too: "\n" can be represented by pointing to the last character of "Hello\n". But that likely comes with very little benifit for a significant increase in complexity. Anyway, I don't believe the standard says anything about where anything is stored really. This is going to be a very implementation-specific thing. If you put two of those declarations in a separate .cpp file, then things will likely change too (unless your compiler does significant linking work.)
53,507,437
I'm creating an app with React, Redux, Ant-Design, LESS and many other modules. I have to fetch the Primary color from the DB and I assign it to a CSS variable (--primary-color). I darken the color and assign it to an other CSS variable (--primary-color-darken). I use CSS variables instead of LESS variables because the LESS variables are hardcoded after the compilation and cannot be changed. I succeed to overwrite the AntD css class with my CSS variable, but with hover class it doesn't work. The browser seems to understand the style correctly but compute the wrong one. ``` //LESS code //Default assigned CSS variables :root { --primary-color: #EB3052; --primary-color-darken: #D62D4C; --primary-hover-color: var(--primary-color-darken); } //Default value for Ant-Design @primary-color: #EB3052; @primary-hover-color: #D62D4C; //Overwrite the Ant-Design class .ant-btn.ant-btn-primary, .ant-btn-primary { background-color: var(--primary-color); border-color: var(--primary-color); &:hover { background-color: var(--primary-hover-color) !important; border-color: var(--primary-hover-color) !important; } } ``` I reassign variable inline with a wrapper component that wrap all the app content. ``` [other wrapper] <div class="CssVariableApplicator" style="--primary-color:#FFFF22;--primary-color-darken:#e6e61f;" data-reactroot=""> [content] </div> ``` Look at the printscreens for the behavior: 1. Styled Primary color correctly: <https://i.stack.imgur.com/RV057.png> 2. Computed Primary colorcorrectly: <https://i.stack.imgur.com/h7967.png> 3. Styled Hover Primary color correctly]: <https://i.stack.imgur.com/tSWIN.png> 4. Computed Hover Primary color incorrectly: <https://i.stack.imgur.com/Ed4e9.png>
2018/11/27
[ "https://Stackoverflow.com/questions/53507437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Wrap in `:global` like so: ```css :global(.ant-btn-primary) { background-color: var(--secondary-color); &:hover { background-color: var(--secondary-hover-color) !important; border-color: var(--secondary-hover-color) !important; } } ```
Just add the atribute :hover on the CCS class ```css .ant-btn-primary { background: #yourColor; border-color: #yourColor; } .ant-btn-primary:hover { background: #yourColor; border-color: #yourColor; } ```
257
I am looking for video lectures to go through to guide my reading in intro molecular and cellular biology. I've had intro bio and I study evolutionary theory, but my molecule- and cell-level knowledge is weak. I'm finding it impossible to know where to look in a big book like Alberts, or to read Lodish without a guide, so I really need lectures to help me out. I've tried the MIT OCW assignments and a few other similar sites, but I can't seem to find a course that includes lectures. Does anyone know of any? Ideally they'd follow Watson et al. for molecular and Lodish for cellular, but I can find other textbooks too.
2011/12/21
[ "https://biology.stackexchange.com/questions/257", "https://biology.stackexchange.com", "https://biology.stackexchange.com/users/16/" ]
While not exclusively cell and molecular biology, I would also like to add the [Journal of Visualized Experiments](http://www.jove.com/). It's like Youtube for experiments. :)
The Journal of Visualized Experiments ([jove.com](http://www.jove.com/)) is excellent but based on experimental protocols. [ItunesU](https://www.apple.com/apps/itunes-u/) also has great resources. Stay away from youtube - a lot of people there don't know what they are talking about.
476,446
If f is differentiable at $x$ then for $\alpha\neq1$ $$f'(x)=\lim\_{c\to 0} {{f(x+c)-f(x+\alpha c)}\over{c-\alpha c}}.$$ I am not really sure what it is I need to even show to prove the statement.
2013/08/26
[ "https://math.stackexchange.com/questions/476446", "https://math.stackexchange.com", "https://math.stackexchange.com/users/91800/" ]
Using just the derivative definition: $$ \lim\_{c\to0}{{f(x+c)-f(x+\alpha c)}\over{c-\alpha c}}=\frac{1}{1-\alpha}\lim\_{c\to0}{{f(x+c)-f(x)}\over{c}}-\frac{\alpha}{1-\alpha}\lim\_{\alpha c\to0}{{f(x+\alpha c)-f(x)}\over{\alpha c}}\\=\frac{f'(x)}{1-\alpha}-\frac{\alpha f'(x)}{1-\alpha}=f'(x) $$
Hint: try with $$\frac{f(x+c)-f(x+\alpha c)}{c(1-\alpha)}=\frac{f(x+c)-f(x)+f(x)-f(x+\alpha c)}{c(1-\alpha)}=\\\frac{1}{1-\alpha}\frac{f(x+c)-f(x)}{c}-\frac{1}{1-\alpha}\frac{f(x+\alpha c)-f(x)}{c};$$ Now $$f(x+\alpha c)-f(x)=f'(x)\alpha c+O(c^2),$$ and so $$\lim\_{c\rightarrow 0}\frac{f(x+c)-f(x+\alpha c)}{c(1-\alpha)}= \frac{1}{1-\alpha}f'(x)-\frac{\alpha}{1-\alpha}\lim\_{c\rightarrow 0}\frac{f'(x)c+O(c^2)}{c}=\left(\frac{1}{1-\alpha}-\frac{\alpha}{1-\alpha}\right)f'(x)=f'(x).$$
84,842
Does anyone here know how I can create tileable images like this one: [![enter image description here](https://i.stack.imgur.com/ewXV1.jpg)](https://i.stack.imgur.com/ewXV1.jpg) Can I use photoshop? any good tutorial? I am a novice when it comes to design.
2017/02/08
[ "https://graphicdesign.stackexchange.com/questions/84842", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/85988/" ]
This is an ordinary black and white image clouds or a desaturated color image. This clouds, for example, is an inverted to a negative. I suggest you to invert it back and you can see: [![enter image description here](https://i.stack.imgur.com/zNizB.jpg)](https://i.stack.imgur.com/zNizB.jpg) Quite dark! Probably the negative was adjusted a little brighter. The photo is an ordinary one only technically. There seems to be two different kinds of clouds at different altitudes. Nearly every photo editing program should have these capabilities (=desaturate, invert, adjust brightness and contrast), no need to get any "high cost" or "complex to use" software for this. But if you want to start from scratch, not from a photo, then the abilities of Photoshop or other complex software are welcome.
So these days there are tile plugins etc, but the way to do this manually is, at its most basic: Take an image. Make a selection that is exactly 1/2 the width and 1/2 the height, copy it, and then paste it into a new layer or doucment such that it is in the opposite quadrant of the image (if it is the upper left, paste it lower right, etc). You now have an image where the old outer edges (the parts that will meet in a tile) are at the center, and every new outer edge is already seamlessly matched to the other edges. You now focus on the "inner cross" where the four quarters meet, using clone tools etc to try an make that cross disappear. You can then use it as-is, or re-rearrange the quadrants back to the original configuration. If you do rearrange them again, you can touch up anything at the center.
46,967,067
i am new to ionic and there are some problems i am facing like the file structure is very different. like there is no `lib` folder no `app.js` file there is no `angular.module('myApp')` code anywhere. help me out with it my whole work is pending. i have tried re-installing ionic and cordove but didn't made any difference. image attached below. [![enter image description here](https://i.stack.imgur.com/soApO.png)](https://i.stack.imgur.com/soApO.png)
2017/10/27
[ "https://Stackoverflow.com/questions/46967067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4826930/" ]
In python 3, using dictionary.items() returns an iterator of key-value pairs. You can print through them like this. ``` for key, value in d.items(): print(key, value) ``` you can also print them directly: ``` for i in d: print (i, d[i]) ``` You can add the numbering and format this however you want EDIT: as mentioned, you can use list comprehensions. You could do something like ``` print_list = [(k,v) for k,v in d.items()] for i in print_list: print (i, print_list[i] ``` this will print a numbered list of key/value tuples.
I did the following code. it uses pandas ``` import pandas as pd ast = { "number":6,"message":"success","people": [{"name":"Sergey Ryazanskiy","craft":"ISS"},{"name":"Randy Bresnik", "craft":"ISS"}, {"name":"Paolo Nespoli","craft":"ISS"}, {"name" : "Alexander Misurkin","craft":"ISS"},{"name":"Mark Vande Hei","craft":"ISS"} ,{"name":"Joe Acaba","craft":"ISS"} , {"name": "Erick Salas", "craft": "SSI"}]} my_dataframe = pd.DataFrame(ast['people']) print('People:') print(my_dataframe[['name','craft']].to_string()) my_sum = my_dataframe['craft'].value_counts() print('Count of crafts') print(my_sum.to_string()) People: name craft 0 Sergey Ryazanskiy ISS 1 Randy Bresnik ISS 2 Paolo Nespoli ISS 3 Alexander Misurkin ISS 4 Mark Vande Hei ISS 5 Joe Acaba ISS 6 Erick Salas SSI Count of crafts ISS 6 SSI 1 ```
52,948,611
I am creating Binding DLL for Xamarin.Mac using the Binding project in visual studio Mac. I am able to build Binding DLL successfully, However while going to use that binding DLL in Xamarin.Mac project then it returns bellow error. MMP : error MM5109: Native linking failed with error code 1. Check build log for details. --- Error Detail : -------------- > > Building: CompatibleToXamarinForms.Mac (Release|iPhone) Build started > 23-10-2018 17:16:33. > > > > > --- > > > Project > "/Users/XYZ/Desktop/John/Agora/CompatibleToXamarinForms/CompatibleToXamarinForms.Mac/CompatibleToXamarinForms.Mac.csproj" > (Build target(s)): > > > Target \_CoreCompileImageAssets: > Tool /Applications/Xcode.app/Contents/Developer/usr/bin/actool execution started with arguments: --errors --warnings --notices > --output-format xml1 --output-partial-info-plist > ... > "\_\_\_gxx\_personality\_v0", referenced from: > -[AgoraLiveTranscoding init] in AgoraRtcEngineKit(libagora\_rtc\_sdk.a-x86\_64-master.o) > -[AgoraLiveInjectStreamConfig init] in AgoraRtcEngineKit(libagora\_rtc\_sdk.a-x86\_64-master.o) > -[AgoraPublisherConfiguration toJsonString] in AgoraRtcEngineKit(libagora\_rtc\_sdk.a-x86\_64-master.o) > agora::rtc::RtcEngineEventHandlerIosImpl::onMediaEngineLoadSuccess() > in AgoraRtcEngineKit(libagora\_rtc\_sdk.a-x86\_64-master.o) > \_\_\_\_ZN5agora3rtc28RtcEngineEventHandlerIosImpl24onMediaEngineLoadSuccessEv\_block\_invoke > in AgoraRtcEngineKit(libagora\_rtc\_sdk.a-x86\_64-master.o) > agora::rtc::RtcEngineEventHandlerIosImpl::onMediaEngineStartCallSuccess() > in AgoraRtcEngineKit(libagora\_rtc\_sdk.a-x86\_64-master.o) > \_\_\_\_ZN5agora3rtc28RtcEngineEventHandlerIosImpl29onMediaEngineStartCallSuccessEv\_block\_invoke > in AgoraRtcEngineKit(libagora\_rtc\_sdk.a-x86\_64-master.o) > ... > ld: symbol(s) not found for architecture x86\_64 > clang : error : linker command failed with exit code 1 (use -v to see invocation) > > > MMP : error MM5109: Native linking failed with error code 1. Check build log for details. Done building target "\_CompileToNative" > in project "CompatibleToXamarinForms.Mac.csproj" -- FAILED. > > > Done building project "CompatibleToXamarinForms.Mac.csproj" -- FAILED. > > > Build FAILED. > > > /Users/XYZ/Desktop/John/Agora/CompatibleToXamarinForms/CompatibleToXamarinForms.Mac/obj/iPhone/Release/mmp-cache/registrar.m(36313,17): > warning G7AC58F0F: method 'deviceBrowserView:selectionDidChange:' in > protocol 'IKDeviceBrowserViewDelegate' not implemented [-Wprotocol] > /Users/XYZ/Desktop/John/Agora/CompatibleToXamarinForms/CompatibleToXamarinForms.Mac/obj/iPhone/Release/mmp-cache/registrar.m(39971,2): > warning GB7F1753F: method possibly missing a [super > splitView:effectiveRect:forDrawnRect:ofDividerAtIndex:] call > [-Wobjc-missing-super-calls] clang : error : linker command failed > with exit code 1 (use -v to see invocation) MMP : error MM5109: Native > linking failed with error code 1. Check build log for details. > 2 Warning(s) > 2 Error(s) > > > Time Elapsed 00:00:22.65 > > > ---------------------- Done ---------------------- > > > Build: 2 errors, 2 warnings > > > Can you please someone help to resolve this issue. > > >
2018/10/23
[ "https://Stackoverflow.com/questions/52948611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10489885/" ]
You will need to use `getComputedStyle()` for that: ``` var navColor = getComputedStyle(nav).color; ```
You can query the applied css rule by calling `getComputedStyle(document.querySelector("nav")).color`
65,628,070
How to get UTC from timezone with python? Timezone: `Asia/Pontianak` From timezone (Asia/Pontianak), will resulted `+7`, `+8` or something like that.
2021/01/08
[ "https://Stackoverflow.com/questions/65628070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13717698/" ]
In `test`, the `println` that prints the thread ID is executed outside of the future, therefore it's executed synchronously. The code inside the future will get executed on a thread of the `ExecutionContext` (in this case the actor system's dispatcher). It's worth noting that some parallel execution happened: the thread print for `a = 4` happened before the `a + 1` print for `a = 3`. If you move the thread `println` into the future, that `println` will execute asynchronously: ``` Future { println(s"Flow A : ${Thread.currentThread().getName()}") println(a+1) }(ec) ``` Note that in your test code, you're not likely to see much parallel execution anyway: the amount of work involved in spawning the future is close to the amount of work done in the future (even with the second print in the future), so the spawned futures often complete before the next future can spawn. `mapAsync` can best be thought of as synchronously calling code which returns a future (the future may or may not be completed at the time it's returned) and stores that future in a buffer of size `parallelism`. When a future in that buffer completes successfully, the value it completed with is emitted and the slot in the buffer frees up, allowing `mapAsync` to demand another element (I'm technically describing `mapAsyncUnordered` because it's simpler: `mapAsync` won't emit until every future created prior to the completed one has successfully completed and emitted; I don't actually know off the top of my head if a later element completing opens up a slot in the buffer or not). Whether this actually results in parallelism depends on the particulars of the future and how it's completed (e.g. if the future is an ask of the same actor every time, the effective parallelism is unlikely to ever be more than 1). `async` probably should have been called `stageBoundary` or something similar in my opinion, precisely because it often leads people to think that `mapAsync` and `map(...).async` have much if anything in common. `async` is a signal to the `Materializer` that the stages between the previous `async` and this `async` should not be fused with the stages after the `async`. In the usual `ActorMaterializer`, fused stages execute in a single actor. This has the advantage of eliminating the overhead of transferring elements from stage to stage, at the cost of limiting, in general, the number of elements executing in a fused stage to 1. There's an implicit buffer between fused stages: the downstream stage will signal demand based on the empty slots in its buffer. The two stages will process in parallel, in the sense that the (possibly fused) stage before the `async` can process an element at the same time that the (possibly fused) stage after the `async` is processing an element. This is basically pipelined execution. So in `Source(1 to 10).mapAsync(10)(test).to(Sink.ignore).run()` the entire stream is materialized as a single actor where, (effectively: this is a description which complies with the requirements of how streams are materialized) in a single actor (so thus all of these, except for tasks scheduled onto an `ExecutionContext`, execute synchronously, in order): * `Sink.ignore` signals effectively unbounded demand to `mapAsync` * `mapAsync` has 10 empty slots, so requests 10 elements from the source * `source` emits 1 * `mapAsync` prints the current thread, creates a `Promise[Unit]`, creates a closure object which looks something like ``` new ClosureClassName { val a: Int = 1; def run(): Unit = println(a+1) } ``` and schedules a task on `ec` which will run the `run` method of the closure and complete the promise's future. The `ec` will schedule the task on a thread for asynchronous execution according to the logic of the `ec`; meanwhile our actor saves the future in its buffer (call it `futureBuffer(0)`) * let's say that by the time we save `futureBuffer(0)`, it's completed (with `()`, the singleton value for `Unit`), `mapAsync` emits `()` to `Sink.ignore` and clears `futureBuffer(0)` * `Sink.ignore`, well, ignores the `()` it's received * `source` now emits 2 * `mapAsync` executes as above, only with `a = 2` in the closure * this time, let's say that due to the vagaries of thread scheduling, `futureBuffer(0)` (now the future for `a = 2`) hasn't yet completed, so * `source` now emits 3 * `mapAsync` executes as above, with `a = 3` in the closure, saving the future as `futureBuffer(1)` * now both `futureBuffer(0)` and `futureBuffer(1)` have completed, so `futureBuffer(0)`'s value is emitted to `Sink.ignore` and `futureBuffer(0)` is cleared * `Sink.ignore` ignores the value * `futureBuffer(1)`'s value is emitted to `Sink.ignore` and `futureBuffer(1)` is cleared * `Sink.ignore` ignores the value So there's been a tiny bit of parallelism through `mapAsync`: the realized degree of parallelism is essentially the number of uncompleted futures. For `Source(1 to 100).map(test).async.to(Sink.ignore).run()` that will materialize as something like ``` Actor A (Source.map) ^ | Future[Unit] sent down, demand signal sent up v Actor B (Sink.ignore) ``` Let's say that the materializer settings have a receiving buffer of 2 elements per actor. * B: `Sink.ignore` signals effectively unbounded demand to `Actor B` * B: `B` has 2 free slots in its buffer, so it sends a message to `Actor A` demanding 3 elements * A: `A` passes this demand to `map`, which demands 1 element from the source * A: source emits 1 * A: `map` prints the current thread etc. as above. It doesn't save the resulting (possibly completed or uncompleted) future in a buffer (it doesn't have one), it emits the future to `A` * A: `A` passes the future to `B` From here on, `A` and `B` are processing in parallel (at least some of the time in this case, since `B` is just sending elements to the bit bucket) * A: source emits 2; meanwhile `B` passes the future it's received to `Sink.ignore`, which ignores the future (not even caring whether the future has completed, or even whether the future failed) and so on... once B has received three elements, it will signal demand for two more (assuming, as is likely, that the `Sink` hasn't yet finished ignoring the future and the buffer of 2 elements is empty). It's worth noting throughout this, that an actor may change from message to message which thread it's running on (whether it does is up to the `ActorSystem`'s dispatcher), but an actor maintains a single-thread illusion: it's only ever using one thread at a time.
The computation in your example does run in parallel, the reason why it shows the same thread is because the items from `Source(1 to 10)` are dispatched to one actor that this whole stream is run by. If you change your `test` to be say: ``` private def test(a: Int) = { println(s"Flow A : ${Thread.currentThread().getName}") Future { println(s"Inside future Flow A : ${Thread.currentThread().getName}") println(a + 1) }(ec) } ``` you will see that the computation of the code passed to `Future` is in fact executed on the threadpool: ``` Flow A : MyDemo-akka.actor.default-dispatcher-4 Inside future Flow A : pool-1-thread-1 2 Flow A : MyDemo-akka.actor.default-dispatcher-4 Flow A : MyDemo-akka.actor.default-dispatcher-4 Inside future Flow A : pool-1-thread-2 3 Flow A : MyDemo-akka.actor.default-dispatcher-4 Inside future Flow A : pool-1-thread-3 4 Flow A : MyDemo-akka.actor.default-dispatcher-4 Inside future Flow A : pool-1-thread-4 5 Flow A : MyDemo-akka.actor.default-dispatcher-4 Inside future Flow A : pool-1-thread-5 6 Flow A : MyDemo-akka.actor.default-dispatcher-4 Inside future Flow A : pool-1-thread-6 7 Flow A : MyDemo-akka.actor.default-dispatcher-4 Inside future Flow A : pool-1-thread-7 8 Flow A : MyDemo-akka.actor.default-dispatcher-4 Inside future Flow A : pool-1-thread-8 9 Inside future Flow A : pool-1-thread-9 10 Flow A : MyDemo-akka.actor.default-dispatcher-4 Inside future Flow A : pool-1-thread-10 11 ``` If you adjust your stream to add `async` and log before and after it: ``` Source(1 to 10) .mapAsync(10)(test) .wireTap(_ => println(s"after mapAsync : ${Thread.currentThread().getName}")) .async .wireTap(_ => println(s"after async : ${Thread.currentThread().getName}")) .to(Sink.ignore) .run() ``` You can observe how the parallel execution results are then dispatched by the same akka thread and also that `async` introduces an async boundary in the stream: ``` Flow A : MyDemo-akka.actor.default-dispatcher-5 Inside future Flow A : pool-1-thread-1 2 after mapAsync : MyDemo-akka.actor.default-dispatcher-5 Flow A : MyDemo-akka.actor.default-dispatcher-5 after async : MyDemo-akka.actor.default-dispatcher-4 Flow A : MyDemo-akka.actor.default-dispatcher-5 Inside future Flow A : pool-1-thread-2 3 Flow A : MyDemo-akka.actor.default-dispatcher-5 Inside future Flow A : pool-1-thread-3 4 Flow A : MyDemo-akka.actor.default-dispatcher-5 Inside future Flow A : pool-1-thread-4 5 Flow A : MyDemo-akka.actor.default-dispatcher-5 Inside future Flow A : pool-1-thread-5 6 Flow A : MyDemo-akka.actor.default-dispatcher-5 Inside future Flow A : pool-1-thread-6 7 Flow A : MyDemo-akka.actor.default-dispatcher-5 Inside future Flow A : pool-1-thread-7 8 Flow A : MyDemo-akka.actor.default-dispatcher-5 Inside future Flow A : pool-1-thread-8 9 Inside future Flow A : pool-1-thread-9 10 Flow A : MyDemo-akka.actor.default-dispatcher-5 Inside future Flow A : pool-1-thread-10 11 after mapAsync : MyDemo-akka.actor.default-dispatcher-5 after async : MyDemo-akka.actor.default-dispatcher-4 after mapAsync : MyDemo-akka.actor.default-dispatcher-5 after async : MyDemo-akka.actor.default-dispatcher-4 after mapAsync : MyDemo-akka.actor.default-dispatcher-5 after async : MyDemo-akka.actor.default-dispatcher-4 after mapAsync : MyDemo-akka.actor.default-dispatcher-5 after async : MyDemo-akka.actor.default-dispatcher-4 after mapAsync : MyDemo-akka.actor.default-dispatcher-5 after async : MyDemo-akka.actor.default-dispatcher-4 after mapAsync : MyDemo-akka.actor.default-dispatcher-5 after mapAsync : MyDemo-akka.actor.default-dispatcher-5 after async : MyDemo-akka.actor.default-dispatcher-4 after mapAsync : MyDemo-akka.actor.default-dispatcher-5 after async : MyDemo-akka.actor.default-dispatcher-4 after mapAsync : MyDemo-akka.actor.default-dispatcher-5 after async : MyDemo-akka.actor.default-dispatcher-4 after async : MyDemo-akka.actor.default-dispatcher-4 ```
58,917,530
I'd bind a button to input using v-bind with a function : The code inside my **template** : ``` <template> <input type="email" v-model="email" v-bind:placeholder="$t('fields.email_place_holder')" /> <input v-bind:disabled="{ isDisable }" type="submit" v-bind:value="$t('buttons.notify_me')" class="notify-me-button" /> </template> ``` The code inside my **script** : ``` methods: { isDisable() { return email.lenght > 0; } } ``` But the `button` does not change its status , I tried to change the **css style** with the same way and the result is the same.The problem is that button responds once time on the first value returned by `isDisable()`.
2019/11/18
[ "https://Stackoverflow.com/questions/58917530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7551963/" ]
The easy way to do it is to check if the value exists or not. For example: ``` <input type="text" v-model="user.name" required /> ``` For the submit button just use disable ``` <button type="submit" :disabled="!user.name">Submit</button> ``` Only when the field is filled then the submit button is enabled for submit.
Try this: ```html <button type="button" class="btn btn-primary btn-sm ripple-surface" v- bind:disabled='!isDisabled'>Save</button> ``` ```js computed: { isDisabled() { return this.categoryName.length > 0; } }, ```
54,131,363
I have a JSON data which looks like this: ``` { "status": "status", "date": "01/10/2019", "time": "10:30 AM", "labels": { "field1": "value1", "field2": "value2", ... "field100": "value100" } "description": "some description" } ``` In my Java code, I have two classes: 1. `Alerts` class which has the following fields - status, date, time, description and `Labels` class. 2. The inner `Labels` class which is supposed to hold all the fields from `field1` through `field100` (and more) I'm parsing this JSON into GSON like this: ``` Alerts myAlert = gson.fromJson(alertJSON, Alert.class); ``` The above code parses the JSON into the `Alert` object and the `Labels` object. Question: Instead of mapping the fields (`field1`, `field2`, etc) inside Labels object as individual String fields, how can I parse them into a map? For example, the Labels object would look like this: ``` public class Labels { // I want to parse all the fields (field1, field2, etc) into // this map Map<String, String> fields = new HashMap<>(); } ``` How do I do this?
2019/01/10
[ "https://Stackoverflow.com/questions/54131363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1244329/" ]
You can use TypeToken to directly specify labels. ``` import java.lang.reflect.Type; import com.google.gson.reflect.TypeToken; Type mapType = new TypeToken<Map<String, String>>(){}.getType(); Map<String, String> myMap = gson.fromJson("{'field1':'value1','field2':'value2'}", mapType); ```
For general cases - some more flexible way: gson can register type adapters: ``` Gson gson = new GsonBuilder().registerTypeAdapter(Labels.class, new LabelsDeserializer()).create(); ``` And deserializer for your case is: ``` public class LabelsDeserializer implements JsonDeserializer<Labels> { @Override public Labels deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { if (!jsonElement.isJsonNull()) { Labels label = new Labels(); jsonElement.getAsJsonObject().entrySet().forEach(entry -> label.getFields().put(entry.getKey(), entry.getValue().getAsString())); return label; } else { return null; } } } ``` For serlializing it's needed to implement JsonSerializer<...>
71,305,004
Unhandled Exception: type '(dynamic) => Store' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform' The Json Data its on Object type How Can we Access the Datum and Return List of Datum Values The Below Code is Model of Json Data ``` List<Store> storeFromJson(String str) => List<Store>.from(json.decode(str).map((e) => Store.fromJson(e))); String storeToJson(List<Store> data) => json.encode(List<dynamic>.from(data.map((e) => e.toJson()))); class Store { Store({ required this.success, required this.message, required this.code, required this.data, }); bool success; String message; int code; List<Datum> data; factory Store.fromJson(Map<String, dynamic> json) => Store( success: json["success"], message: json["message"], code: json["code"], data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))), ); Map<String, dynamic> toJson() => { "success": success, "message": message, "code": code, "data": List<dynamic>.from(data.map((x) => x.toJson())), }; } class Datum { Datum({ required this.store, required this.storeId, required this.storeType, required this.createdAt, }); String store; int storeId; StoreType? storeType; int createdAt; factory Datum.fromJson(Map<String, dynamic> json) => Datum( store: json["store"], storeId: json["store_id"], storeType: storeTypeValues.map[json["store_type"]], createdAt: json["created_at"], ); Map<String, dynamic> toJson() => { "store": store, "store_id": storeId, "store_type": storeTypeValues.reverse[storeType], "created_at": createdAt, }; } ```
2022/03/01
[ "https://Stackoverflow.com/questions/71305004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can **not** update the style of the browser picker at the moment.
There isn't (currently) a way to modify it. This is one of the browser special permissions dialogs (See <https://permission.site/> for more). I believe it is vital that these dialogs cannot be forged or be misleading to maintain trust with the users- although I wasn't able to find anything in the spec calling this out. I first recall this being discussed around the [Permissions API](https://w3c.github.io/permissions/#requesting-more-permission)- however I only could find this note: > > NOTE > > This is intentionally vague about the details of the permission UI and > how the user agent infers user intent. User agents should be able to > explore lots of UI within this framework. > > >
36,383,965
I'm using the latest [Django OAuth2 Toolkit (0.10.0)](https://github.com/evonove/django-oauth-toolkit) with Python 2.7, Django 1.8 and Django REST framework 3.3 While using the `grant_type=password`, I noticed some weird behavior that any time the user asks for a new access token: ``` curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/ ``` A **new** access token and refresh token is **created**. The **old** access and refresh token are still usable until token timeout! **My Issues:** * What I need is that every time a user asks for a new access token, the old one will become invalid, unusable and will be removed. * Also, is there a way that the password grunt type wont create refresh token. I don't have any use for that in my application. One solution I found is that [REST Framework OAuth](http://jpadilla.github.io/django-rest-framework-oauth/authentication/) provides a configuration for One Access Token at a time. I'm not eager to use that provider, but I might wont have a choice.
2016/04/03
[ "https://Stackoverflow.com/questions/36383965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5601726/" ]
If you like to remove all previous access tokens before issuing a new one, there is a simple solution for this problem: **Make your own token view provider!** The code bellow will probably help you to achieve that kind of functionality: ``` from oauth2_provider.models import AccessToken, Application from braces.views import CsrfExemptMixin from oauth2_provider.views.mixins import OAuthLibMixin from oauth2_provider.settings import oauth2_settings class TokenView(APIView, CsrfExemptMixin, OAuthLibMixin): permission_classes = (permissions.AllowAny,) server_class = oauth2_settings.OAUTH2_SERVER_CLASS validator_class = oauth2_settings.OAUTH2_VALIDATOR_CLASS oauthlib_backend_class = oauth2_settings.OAUTH2_BACKEND_CLASS def post(self, request): username = request.POST.get('username') try: if username is None: raise User.DoesNotExist AccessToken.objects.filter(user=User.objects.get(username=username), application=Application.objects.get(name="Website")).delete() except Exception as e: return Response(e.message,status=400) url, headers, body, status = self.create_token_response(request) return Response(body, status=status, headers=headers) ``` The part you should notice is the Try-Except block. In there we finding the Access tokens and removing them. All before we creating a new one. You can look at how to create your own [Provider using OAuthLib](http://oauthlib.readthedocs.org/en/latest/oauth2/server.html#create-your-endpoint-views). Also, this might be useful as well: [TokenView in django-oauth-toolkit](https://github.com/evonove/django-oauth-toolkit/blob/master/oauth2_provider/views/base.py#L155). You can see there the original Apiview. As you said, you were using this package. As for the **refresh\_token**, as previously mentioned in other answers here, you can't do what you are asking. When looking at the code of `oauthlib` password grunt type, you will see that in its initialization, refresh\_token is set to True. Unless you change the Grunt type it self, it can't be done. But you can do the same thing we did above with the access tokens. Create the token and then delete the refresh token.
> > What I need is that every time a user asks for a new access token, the > old one will become invalid, unusable and will be removed. > > > Giving a new token when you ask for one seems like an expected behavior. Is it not possible for you to [revoke](https://django-oauth-toolkit.readthedocs.org/en/latest/tutorial/tutorial_04.html#revoking-a-token) the existing one before asking for the new one? **Update** --- If you are determined to keep just one token - The class [OAuth2Validator](https://github.com/evonove/django-oauth-toolkit/blob/3074e8c3f62ab7a3ccc3db2bb426414402ba041a/oauth2_provider/models.py#L175) inherits OAuthLib's `RequestValidator` and overrides the method [save\_bearer\_token](https://github.com/evonove/django-oauth-toolkit/blob/3074e8c3f62ab7a3ccc3db2bb426414402ba041a/oauth2_provider/models.py#L175). In this method before the code related to [AccessToken model](https://github.com/evonove/django-oauth-toolkit/blob/3074e8c3f62ab7a3ccc3db2bb426414402ba041a/oauth2_provider/models.py#L175) instance creation and its .save() method you can query (similar to [this](https://github.com/evonove/django-oauth-toolkit/blob/3074e8c3f62ab7a3ccc3db2bb426414402ba041a/oauth2_provider/oauth2_validators.py#L230)) to see if there is already an AccessToken saved in DB for this user. If found the existing token can be deleted from database. I strongly suggest to make this change configurable, in case you change your mind in future (after all multiple tokens are issued for reasons like [this](https://stackoverflow.com/a/5340457/865587)) A more simpler solution is to have your own validator class, probably one that inherits `oauth2_provider.oauth2_validators.OAuth2Validator` and overrides `save_bearer_token`. This new class should be given for `OAUTH2_VALIDATOR_CLASS` in `settings.py` --- > > Also, is there a way that the password grunt type wont create refresh > token. I don't have any use for that in my application. > > > Django OAuth Toolkit depends on OAuthLib. Making refresh\_token optional boils down to `create_token` method in `BearerToken` class of oAuthLib at [this line](https://github.com/idan/oauthlib/blob/3d73326d4956fdf0bb8342df87c66fd13e217836/oauthlib/oauth2/rfc6749/tokens.py#L267) and the class for password grant is [here](https://github.com/idan/oauthlib/blob/3d73326d4956fdf0bb8342df87c66fd13e217836/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py). As you can see the `__init__` method for this class takes `refresh_token` argument which by default is set to `True`. This value is used in `create_token_response` method of the same class at the line ``` token = token_handler.create_token(request, self.refresh_token) ``` `create_token_response` method in [`OAuthLibCore`](https://github.com/evonove/django-oauth-toolkit/blob/master/oauth2_provider/oauth2_backends.py) class of Django OAuth toolkit is the one, I believe, calls the corresponding `create_token_response` in OAuthLib. Observe the usage of `self.server` and its initialization in `__init__` method of this class, which has just the validator passed as an argument but nothing related to `refresh_token`. Compare this with [OAuthLib Imlicit grant type](https://github.com/idan/oauthlib/blob/3d73326d4956fdf0bb8342df87c66fd13e217836/oauthlib/oauth2/rfc6749/grant_types/implicit.py#L231)'s `create_token_response` method, which explicitly does ``` token = token_handler.create_token(request, refresh_token=False) ``` to not create `refresh_token` at all So, unless I missed something here, **tldr**, I don't think Django OAuth toolkit exposes the feature of optional `refresh_token`.
1,256,191
> > Prove that $371\cdots 1$ is not prime. > > > I tried mathematical induction in order to prove this, but I am stuck. My partial answer: To be proved is that $37\underbrace{111\cdots 1}\_{n\text{ ones}}$ is never prime for $n\geq 1$. Let $P(n)$ be the statement that $37\underbrace{111\cdots 1}\_{n\text{ enen}}$ is not prime. For $n=1$, we can write $371=7\cdot 53$, and therefore $P(1)$ is true. Let $P(k)$ be true for $k>1$. Then we now have to prove that $P(k+1)$ is true. I found that $37\underbrace{111\cdots 1}\_{k\text{ ones}}$ can be written as $37\cdot 10^k+10^{k-1}+10^{k-2}+\cdots +10^0$ and that $37\underbrace{1111\cdots 1}\_{k+1\text{ ones}}$ can be written as $37\cdot 10^{k+1}+10^{k}+10^{k-1}+\cdots+10^0$. I think I'm pretty close to the answer know, but I don't know how to proceed.
2015/04/28
[ "https://math.stackexchange.com/questions/1256191", "https://math.stackexchange.com", "https://math.stackexchange.com/users/221219/" ]
First note that $111111=3 \cdot 7 \cdot 11\cdot 13\cdot 37$. If $371\cdots 1$ is divisible by any of these prime factors, so will be that number followed by six ones. It suffices to look at the factorizations of $371$, $3711$, $37111$, $371111$, $3711111$, and $37111111$. $371 = \mathbf{7} \cdot 53$ $3711 = \mathbf{3} \cdot 1237$ $37111 = 17 \cdot \mathbf{37} \cdot 59$ $371111 = \mathbf{13} \cdot 28547$ $3711111 = \mathbf{3} \cdot 1237037$ $37111111 = \mathbf{37} \cdot 1003003$
**Hint** $\ $ Do a [covering congruence argument](https://math.stackexchange.com/a/1153492/242) mod $\color{#c00}6$ using the divisors $3,7,13,37\,$ of $\,10^{\color{#c00}6}-1$
46,775,309
Im using EsLint with VsCode. How can I have an error appear when trying to import a module that doesn't exist ? for example ``` import foo from './this-path-doesnt-exist' ``` Should underline in red. Does this require an eslint plugin ?
2017/10/16
[ "https://Stackoverflow.com/questions/46775309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6797267/" ]
If you are using eslint as your linter, you can use [eslint-plugin-import](https://www.npmjs.com/package/eslint-plugin-import) . > > This plugin intends to support linting of ES2015+ (ES6+) import/export > syntax, and prevent issues with misspelling of file paths and import > names > > >
In addition to the eslint plugin suggested, you can enable semantic checking for a JS file in VS Code by adding `// @ts-check` at the top of the file: ``` // @ts-check import foo from './this-path-doesnt-exist' ``` [![enter image description here](https://i.stack.imgur.com/bVRYn.png)](https://i.stack.imgur.com/bVRYn.png) This will enable a number of other checks in the file as well, including type checking, so it may not be appropriate for every code base but it can help catch many common programming mistakes. [More info about ts-check](https://code.visualstudio.com/Docs/languages/javascript#_type-checking-and-quick-fixes-for-javascript-files)
30,478,070
When I'm trying to drop table then I'm getting error ``` SQL Error: ORA-00604: error occurred at recursive SQL level 2 ORA-01422: exact fetch returns more than requested number of rows 00604. 00000 - "error occurred at recursive SQL level %s" *Cause: An error occurred while processing a recursive SQL statement (a statement applying to internal dictionary tables). *Action: If the situation described in the next error on the stack can be corrected, do so; otherwise contact Oracle Support. ```
2015/05/27
[ "https://Stackoverflow.com/questions/30478070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162620/" ]
I noticed following line from error. ``` exact fetch returns more than requested number of rows ``` That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row. Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows. So, I truncated `dual` table and inserted only row which `X` value. And, everything working fine.
One possible explanation is a database trigger that fires for each `DROP TABLE` statement. To find the trigger, query the `_TRIGGERS` dictionary views: ``` select * from all_triggers where trigger_type in ('AFTER EVENT', 'BEFORE EVENT') ``` disable any suspicious trigger with ``` alter trigger <trigger_name> disable; ``` and try re-running your `DROP TABLE` statement
45,381,783
How do I get ARC onto its own line? I put them both in the same div to share a background, but I am having trouble separating the two. My menu bar is perfectly centered until I put in "ARC". ```css .header{ background-image: url(https://static.pexels.com/photos/204495/pexels-photo-204495.jpeg); background-size: contain; background-repeat: no-repeat; background-position: center; height: 80vh; display: flex; width: 100%; } .header ul li{ float: left; color: white; list-style: none; padding: 7px 6px; margin: 0; text-align: center; font-size: 15px; display: flex; } .menu{ width: 100%; text-align: center; display: block; justify-content: center; margin: 0 auto; padding: 0; } ``` ```html <div class="header"> <ul class="menu"> <li>Home</li> <li>Services</li> <li>Contact</li> <li>Contact</li> </ul> <br> <div class="title"> <h1>ARC</h1> </div> </div> ```
2017/07/28
[ "https://Stackoverflow.com/questions/45381783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8286358/" ]
Here's one way. The inner query gets the max date for each id. Then you can join that back to your main table to get the rows that match. ``` select * from <your table> inner join (select id, max(<date col> as max_date) m where yourtable.id = m.id and yourtable.datecolumn = m.max_date) ```
Have you tried the following: ``` SELECT ID, COUNT(*), max(date) FROM table GROUP BY ID; ```
8,756
I recently bought a Canon 1000d DSLR. I'm just an amateur and don't use my camera daily. I use it once or twice a week. Is it okay if I leave the batteries in the camera during this idle time?
2011/02/15
[ "https://photo.stackexchange.com/questions/8756", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/2867/" ]
Yes, it is completely fine to leave your camera's batteries in for an extended period of time. As long as the camera is completely off, then you shouldn't have a problem. Hope this helps!
It's okay. I do it all the time. Just check if it turns on every day.
58,310,570
Having fun in c++ on CodeWars trying to reverse the letters of the words in a string, words delimited by spaces ie. "Hello my friend" --> "olleH ym dneirf", where extra spaces are not lost. My answer is failing the tests, but when I diff my answer and the suggested answer there is no output. I also tried checking the length of the original and reversed strings and there is a significant difference in their lengths, depending on the string. However, when I compare the outputs they are again identical in terms of length, and there is no trailing whitespace. ``` int main() { std::string s("The quick brown fox jumps over the lazy dog."); std::cout <<"Old: "<<s<<std::endl; std::cout <<"New: "<<reverse(s)<<std::endl; //lengths are not the same std::cout <<"Length of s: "<<s.length()<<std::endl; std::cout <<"Length of reverse(s): "<<reverse(s).length()<<std::endl; //check for trailing whitespace std::cout <<"Last 5 chars of reverse(s): "<<reverse(s).substr(reverse(s).length() - 6)<<std::endl; } ``` ``` std::string reverse(std::string str) { std::string word; std::string revWord; std::string result; char space(' '); int cursor = 0; for(int i = 0; i < str.length(); i++){ std::string revWord; if (str[i] == space || i == str.length() - 1){ if (i == str.length() - 1) i++; word = str.substr(cursor, i - cursor); for(int j = word.length(); j >= 0; j--){ revWord.push_back(word[j]); } word = revWord; if(i != str.length() - 1) result.append(word + " "); cursor = i+1; } } return result; } ``` Console Output: ``` Old: The quick brown fox jumps over the lazy dog. New: ehT kciuq nworb xof spmuj revo eht yzal .god Length of s: 44 Length of reverse(s): 54 Last 5 chars of reverse(s): .god ``` Any ideas?
2019/10/09
[ "https://Stackoverflow.com/questions/58310570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7696758/" ]
You're likely ending up with unprintable 'characters' in your string since you're trying to access off the end of a string. ```cpp for(int j = word.length(); j >= 0; j--){ revWord.push_back(word[j]); } ``` Here you set a variable to be equal to the word length, and then this variable is used to read one byte past the end of the string. The data stored here is a NUL byte, which is there so that the `std::string` can be used to produce a matching C-style string without making a copy of its data. I believe you're also ending up with a space at the end of your string, adding one more extra character.
There is a much simpler way to implement your `reverse()` function, using the [`std::reverse()`](https://en.cppreference.com/w/cpp/algorithm/reverse) algorithm to modify the original `std::string` object inline and not use any additional `std::string` objects at all: ```cpp std::string reverse(std::string str) { std::string::size_type word_start = 0, word_end; std::string::iterator iter = str.begin(); do { word_end = str.find(' ', word_start); if (word_end == std::string::npos) { std::reverse(iter + word_start, str.end()); break; } std::reverse(iter + word_start, iter + word_end); word_start = str.find_first_not_of(' ', word_end + 1); } while (word_start != std::string::npos); return str; } ``` [Live demo](https://ideone.com/RAOKq7)
8,097,902
Which of the two of these are preferable (and why) from the service installer, I've seen both mentioned on different websites (and here on stackoverflow [Automatically start a Windows Service on install](https://stackoverflow.com/questions/1036713/automatically-start-a-windows-service-on-install/1042986#1042986) and [How to automatically start your service after install?](https://stackoverflow.com/questions/212734/how-to-automatically-start-your-service-after-install/212736#212736)). ``` // Auto Start the Service Once Installation is Finished. this.AfterInstall += (s, e) => new ServiceController("service").Start(); this.Committed += (s, e) => new ServiceController("service").Start(); ```
2011/11/11
[ "https://Stackoverflow.com/questions/8097902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/353147/" ]
I consider the latter a little more proper (although a quick check of my codebase and I coded essentially the former). The difference I see is the chance of a Rollback happening. In the commit phase you are past the risk of a rollback. But if you start your service in the AfterInstall (which is just part of the overall Install phase (the four phases being Install, Rollback, Commit, Uninstall)) you have the possibility of a Rollback being issued by a subsequent InstallerClass. You would then need to stop your service and uninstall it (which Microsoft's default service installer classes do for you so it's not much of an issue. In summary, there isn't too much of a difference.
In C# in your service project you will have an installer class called ProjectInstaller.cs, modify it to override the AfterInstall event handler to autostart the service like the code below ``` [RunInstaller(true)] public partial class ProjectInstaller : System.Configuration.Install.Installer { public ProjectInstaller() { InitializeComponent(); } protected override void OnAfterInstall(IDictionary savedState) { base.OnAfterInstall(savedState); using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName)) { serviceController.Start(); } } } ``` This will automatically start your windows Service after installation
19,471,495
I want to know what is exactly CLSID data type, as it is used in C++, and I want to use it in delphi. * what is CLSID?
2013/10/19
[ "https://Stackoverflow.com/questions/19471495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2896601/" ]
A CLSID is a GUID that identifies a COM object. In order to instantiate a registered COM object, you need to know its CLSID. Typically in Delphi you would be calling `CoCreateInstance`. You simply call the function and pass a CLSID. The declaration of `CoCreateInstance` declares the class ID parameter as having type `TCLSID` which is a simple alias of `TGUID`. So pass one of those. Here are the declarations, as lifted from the Delphi source: ``` type TCLSID = TGUID; function CoCreateInstance(const clsid: TCLSID; unkOuter: IUnknown; dwClsContext: Longint; const iid: TIID; out pv): HResult; stdcall; ``` An example of a call to `CoCreateInstance`, taken from my code base: ``` const CLSID_WICImagingFactory: TGUID = '{CACAF262-9370-4615-A13B-9F5539DA4C0A}'; if not Succeeded(CoCreateInstance(CLSID_WICImagingFactory, ...)) then ... ``` You will likely be creating a different interface, and so will need to substitute the appropriate CLSID for that interface. There is one other little trick that is worth knowing about. If you pass an interface type as a parameter of type `TGUID`, and that interface type has a GUID, then the compiler will substitute the GUID for you. So the above code could equally well be written: ``` type IWICImagingFactory = interface // this is the GUID of the interface, the CLSID [{ec5ec8a9-c395-4314-9c77-54d7a935ff70}] .... end; .... if not Succeeded(CoCreateInstance(IWICImagingFactory, ...)) then ... ```
> > **What is a CLSID?** A Class ID (CLSID) is a 128 bit (large) number that represents a unique id for a software application or application > component. Typically they are displayed like this > "{AE7AB96B-FF5E-4dce-801E-14DF2C4CD681}". > > > You can think of a CLSID as a "social security number" for a piece of > software, or a software component. > > > **What are they used for?** CLSIDs are used by Windows to identify software components without having to know their "name". They can also > be used by software applications to identify a computer, file or other > item. > > > **Where do they come from?** Microsoft provides a utility (program) called GUIDGEN.EXE that generates these numbers. They are generated by > using the current time, network adapter address (if present) and other > items in your computer so that no two numbers will ever be the same. [**[1]**](http://www.fileresearchcenter.com/showglossaryterm.html?term=CLSID) > > > and > > COM classes are named by CLSIDs, which are UUIDs as defined by OSF/DCE > RPC [**[2]**](http://www.w3.org/Addressing/clsid-scheme) > > > *Two quotes are cited*
28,275,450
I want java to look for .properties file in same folder with jar which is running. How can I do it and how can I determine if app is running in IDE or as explicit jar file
2015/02/02
[ "https://Stackoverflow.com/questions/28275450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4393559/" ]
Firstly I have to say that this is inherently a bad practice, though life often is not perfect and sometimes we have to roll with the bad design punches. This is the class I mustered up for a pet project of mine that required such functionality: ``` public class ArbitraryPath { private static Logger logger = LogManager.getLogger("utility"); private static boolean isRunFromJar = false; public static String resolveResourceFilePath(String fileName, String folderName, Class<?> requestingClass) throws URISyntaxException{ // ARGUMENT NULL CHECK SAFETY HERE String fullPath = requestingClass.getResource("").toURI().toString(); isRunFromJar = isRunFromJar(fullPath); String result = ""; if(!isRunFromJar){ result = trimPathDownToProject(requestingClass.getResource("").toURI()); } result = result+folderName+"/"+fileName+".properties"; return result; } private static String trimPathDownToProject(URI previousPath){ String result = null; while(!isClassFolderReached(previousPath)){ previousPath = previousPath.resolve(".."); } previousPath = previousPath.resolve(".."); result = previousPath.getPath(); return result; } private static boolean isClassFolderReached(URI currentPath){ String checkableString = currentPath.toString(); checkableString = checkableString.substring(0,checkableString.length()-1); checkableString = checkableString.substring(checkableString.lastIndexOf("/")+1,checkableString.length()); if(checkableString.equalsIgnoreCase("bin")){ return true; } else { return false; } } private static boolean isRunFromJar(String fullPath) throws URISyntaxException{ String solidClassFolder = "/bin/"; String solidJarContainer = ".jar!"; if(!fullPath.contains(solidClassFolder)){ if(fullPath.contains(solidJarContainer)){ return true; } else { logger.error("Requesting class is not located within a supported project structure!"); throw new IllegalArgumentException("Requesting class must be within a bin folder!"); } } else { return false; } } } ``` I guess a little explaining is in order... Overall this will try to resolve a filepath for a properties file located in an arbitrary project. This means that the ArbitraryPath class does not need to be located in the same project as the properties file, this comes in handy when you want to separate for example the JUnit tests in a separate project. It will identify the project based on the class you give it, the class should be in the same project as the properties file you are trying to find. So first of all it gets the path of the class you gave it in this line: ``` String fullPath = requestingClass.getResource("").toURI().toString(); ``` Then it checks whether or not this class is within a JAR file or if it is executed from the IDE. This is done by checking whether the path contains "/bin/" which would normally mean that it is executed from an IDE or ".jar!" which would normally mean that it is executed from a JAR. You can modify the method if you have a different project structure. If it is determined that it is **NOT** run from JAR then we trim the path down to the project folder, going backwards down the path until we reach the BIN folder. Again, change this if your project structure deviates from the standard. (If we determine that it **IS** run from a JAR file then we don't trim anything since we have already got the path to the base folder.) After that, we have retrieved a path to the project folder so we add the name of the folder (if there is one) where the properties file is located, and add the filename and extension of the properties file which we want to locate. We then return this path. We can then use this path in an InputStream like such: ``` FileInputStream in = new FileInputStream(ArbitraryPath.resolveResourceFilePath("myPropertiesFile", "configFolder", UserConfiguration.class)); ``` Which will retrieve the myPropertiesFile.properties in the myConfiguration folder in the project folder where UserConfiguration.class is located. Please note that this class assumes you have a standard project configuration. Feel free to adapt it to your needs etc. Also this is a really hackish and crude way to do this.
``` String absolutePath = null; try { absolutePath = (new File(Utils.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())).getCanonicalPath(); absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator))+File.separator; } catch (URISyntaxException ex) { Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); } ```
1,283
I started looking at one of the rather [complicated questions](https://puzzling.stackexchange.com/questions/548/fastest-way-to-collect-an-arbitrary-army) and began formulating answers based on compartmentalizing the problem into smaller, simpler problems. I need a place to write down the current progress but since I have no idea if this will ever reach an appropriate solution I don't know if it will ever turn into an accurate answer. Is it appropriate to stick all of the "progress" in an answer and edit it more progress as I encounter it? Or should I do all of my work "offline" and only post an answer when it is complete?
2014/06/24
[ "https://puzzling.meta.stackexchange.com/questions/1283", "https://puzzling.meta.stackexchange.com", "https://puzzling.meta.stackexchange.com/users/1622/" ]
Here are two separate points: 1. **Are answers, which doesn't fully answer the question acceptable?** I think yes, because: 1. Many questions here are not about facts, but solutions, sometimes of a complicated problems, so any help can be appreciated by the user who ask. 2. They can contain useful and related to the question information. 3. As we can see, they are encouraged by asking person and community. Also they are encouraged by similar communities, for example, MathSE. 2. **Where can I save my intermediate progress?** 1. You can use your local files, or internet resources. 2. You can create and delete an answer, so only you can see it. (I use it, but I am not sure is it good or bad). 3. I think it is bad to add an public answer and then edit it significantly, it is hard to follow.
While I hesitate to suggest posting an incomplete answer, I have seen a number of such answers posted and upvoted, so I'd say post one or two and see what the community has to say about them. I think it's much more reasonable and accepted here than elsewhere on the network.
37,219,819
I know I must missed something because none of the example of works in my computer. Take the simplest first [example](http://semantic-ui.com/modules/dropdown.html#/usage) at the website. I copied the code AS IS and it doesn't work at all for me. I included the *semantic.min.css* and *semantic.min.js* also just in case I included the jQuery using google CDN. Following is my **html** code. ``` <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="semantic/dist/semantic.min.css"> <script src="semantic/dist/semantic.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script> </head> <body> <script> $('.ui.dropdown') .dropdown() ; </script> <div class="ui dropdown"> <input type="hidden" name="gender"> <i class="dropdown icon"></i> <div class="default text">Gender</div> <div class="menu"> <div class="item" data-value="male">Male</div> <div class="item" data-value="female">Female</div> </div> </div> </body> </html> ``` The output is like this.. [![enter image description here](https://i.stack.imgur.com/SYM6D.png)](https://i.stack.imgur.com/SYM6D.png) Thank you! I am pretty new to JavaScript and semantic UI.
2016/05/13
[ "https://Stackoverflow.com/questions/37219819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5736676/" ]
i use this order of linking js files and work fine ``` <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="../bower_components/jquery/dist/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="../bower_components/semantic/dist/semantic.min.css"> <script src="../bower_components/semantic/dist/semantic.min.js"></script> </head> <body> <select name="gender" class="ui dropdown" id="select"> <option value="">Gender</option> <option value="male">Male</option> <option value="female">Female</option> </select> <script type="text/javascript"> $('#select') .dropdown() ; </script> </body> </html> ```
I need to include jQuery before including .js and .css
17,469,682
I'm working on a Django 1.5 project and I have a custom user model (let's call it `CustomUser`). Another app (SomeApp) needs to reference this custom user model. For the purposes of ForeignKey and such, the Django documentation says to use ``` User = settings.AUTH_USER_MODEL ``` However, some functions in SomeApp.models need to access what would have formerly been known as `User.objects`. But User is now a string and not a class, so `User.objects` fails. The alternative would be ``` from django.contrib.auth import get_user_model User = get_user_model() ``` Which works in other modules, but when I use this in models.py of SomeApp, Django raises an error: > > ImproperlyConfigured("AUTH\_USER\_MODEL refers to model '%s' that has not been installed" % settings.AUTH\_USER\_MODEL) > > > Any ideas? EDIT 1 - Traceback: ``` Traceback (most recent call last): File "<console>", line 1, in <module> File "...\django-badger\badger\__init__.py", line 7, in <module> from badger.models import Badge, Award, Progress File "...\django-badger\badger\models.py", line 26, in <module> User = get_user_model() File "...\lib\site-packages\django\contrib\auth\__init__.py", line 127, in get_user_model raise ImproperlyConfigured("AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL) ImproperlyConfigured: AUTH_USER_MODEL refers to model 'MyApp.AuthUser' that has not been installed ``` EDIT 2 - INSTALLED\_APPS settings: ``` INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'south', 'MyApp', # this is where my user model is defined 'SomeApp', # I try to use get_user_model() in this app's models.py; doesn't work. 'social_auth', ) ```
2013/07/04
[ "https://Stackoverflow.com/questions/17469682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224511/" ]
The Django documentation has the answer: <https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.get_user_model> The most relevant section: *Generally speaking, you should reference the User model with the AUTH\_USER\_MODEL setting in code that is executed at import time. get\_user\_model() only works once Django has imported all models.* The real solution is to make sure that you only use `get_user_model()` inside of a method, so that it won't get executed at import time.
Are you running South 0.8.3? Ensure that you running South at least **0.8.4** GitHub [issue](https://github.com/pennersr/django-allauth/issues/449#issuecomment-28977159) South Release [Notes](http://south.readthedocs.org/en/latest/releasenotes/0.8.4.html#release-notes)
283,170
We already had multiple questions about unbalanced data when using [logistic regression](https://stats.stackexchange.com/questions/6067/does-an-unbalanced-sample-matter-when-doing-logistic-regression), [SVM](https://stats.stackexchange.com/questions/94295/svm-for-unbalanced-data), [decision trees](https://stats.stackexchange.com/questions/28029/training-a-decision-tree-against-unbalanced-data), [bagging](https://stats.stackexchange.com/questions/15036/bagging-with-oversampling-for-rare-event-predictive-models) and a number of other similar questions, what makes it a very popular topic! Unfortunately, each of the questions seems to be algorithm-specific and I didn't find any general guidelines for dealing with unbalanced data. Quoting [one of the answers by Marc Claesen](https://stats.stackexchange.com/a/131259/35989), dealing with unbalanced data > > (...) heavily depends on the learning method. Most general purpose > approaches have one (or several) ways to deal with this. > > > But when exactly should we worry about unbalanced data? Which algorithms are mostly affected by it and which are able to deal with it? Which algorithms would need us to balance the data? I am aware that discussing each of the algorithms would be impossible on a Q&A site like this. I am rather looking for general guidelines on when it could be a problem.
2017/06/02
[ "https://stats.stackexchange.com/questions/283170", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/35989/" ]
Not a direct answer, but it's worth noting that in the statistical literature, some of the prejudice against unbalanced data has historical roots. Many classical models simplify neatly under the assumption of balanced data, especially for methods like ANOVA that are closely related to experimental design—a traditional / original motivation for developing statistical methods. But the statistical / probabilistic arithmetic gets quite ugly, quite quickly, with unbalanced data. Prior to the widespread adoption of computers, the by-hand calculations were so extensive that estimating models on unbalanced data was practically impossible. Of course, computers have basically rendered this a non-issue. Likewise, we can estimate models on massive datasets, solve high-dimensional optimization problems, and draw samples from analytically intractable joint probability distributions, all of which were functionally impossible like, fifty years ago. It's an old problem, and academics sank a lot of time into working on the problem...meanwhile, many applied problems outpaced / obviated that research, but old habits die hard... Edit to add: I realize I didn't come out and just say it: there isn't a low level problem with using unbalanced data. In my experience, the advice to "avoid unbalanced data" is either algorithm-specific, or inherited wisdom. I agree with AdamO that in general, unbalanced data poses no conceptual problem to a well-specified model.
For me the most important problem with unbalanced data is the baseline estimator. For example, you have two classes with 90% and 10% sample distribution. But what does this mean for a dummy or naive classifier? You can infer this meaning by comparing it with a baseline’s performance. You can always predict the most frequent label in the training set, so the model has to be better or at least than 90% (this is the baseline)! Typical baselines include those supported by scikit-learn’s "dummy" estimators: Classification baselines: * "stratified": generates predictions by respecting the training set’s class distribution. * "most\_frequent": always predicts the most frequent label in the training set. * "prior": always predicts the class that maximizes the class prior.
8,859
The word for G-d in [Genesis 1:1](https://www.sefaria.org/Genesis.1.1?lang=bi&aliyot=0) is plural in all the manuscripts, there's no debating that it's plural. So really it should read "In the Beginning Gods created the heavens and the earth." Why is this plural? ... or, is there debating on what it says?
2011/07/13
[ "https://judaism.stackexchange.com/questions/8859", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/746/" ]
It's not in the plural form, see how the verb is. Another example in Hebrew is the word "maim" (water), which has no singular or plural. This may seem plural to you but it actually isn't, simply because God is one. Your question is basically on the quality of the translation. One can see (at least as a reflection) the importance each culture (or language) gives to something by how many words it has for it. Meaning a culture giving importance to fish would name each one different exposing the nuances while someone that hates fish would just call all of them fish and would't see the difference from one to another. Hebrew has many words for God, soul etc. Lots of different words are commonly translated to one general losing great part of it's meaning. But that happens with all translations.
The text in Hebrew is: (transliterated) > > "Bereshit bara Elohim et hashamayim ve'et ha'aretz" > > > Grammatically, there are 3 nouns, 1 verb and one adverb. The one verb is singular, 2 of the nouns have a plural suffix, and one of the nouns is singular, and the adverb "Bereshit" is also singular. Since there are no verbs written in the plural, none of the possible subjects are plural either (in this case, all the nouns happen to be singular nouns). A literal translation of the phrase, without any correction for English grammar would be > > "In beginning, created (singular masculine) Elohim, the sky and the earth" > > > The word Elohim itself, can be translated in one of six ways. G-d, gods, Powers, Leaders, Judges, Forces
39,883
What are the differences between Ethereum Sharding Proposal and Plasma? I know plasma can run on top of sharding, but what are the differences innterms of paradigm and technology?
2018/02/16
[ "https://ethereum.stackexchange.com/questions/39883", "https://ethereum.stackexchange.com", "https://ethereum.stackexchange.com/users/22865/" ]
The first phase implementation of sharding and Plasma are both essentially sidechains that tie into the main chain via smart contracts. However, the responsibilities of these smart contracts and properties of the sidechains is different for each project. Plasma sidechains are somewhat similar to state channels (e.g. Lightening and Raiden) in that they use the main chain primarily to adjudicate fraud on the sidechain. Anyone can create a Plasma sidechain, which itself may consist of subchains, so any number can be created. In contrast, shard sidechains act more like extensions to the main chain by periodically commiting a state root hash of transactions from their shard. There are no deposits to bond the sidechain transactions. Instead a proof of stake process on the main chain assigns notaries from a pool to validate blocks (called collations) on a fixed (SHARD\_COUNT) number of shards. See also: <https://github.com/ethereum/wiki/wiki/Sharding-FAQs#how-does-plasma-state-channels-and-other-layer-2-technologies-fit-into-the-trilemma>
The above answer is outdated on sharding, notaries are used instead of validators. See <https://github.com/ethereum/wiki/wiki/Sharding-FAQ#how-does-plasma-state-channels-and-other-layer-2-technologies-fit-into-the-trilemma>. After editing the above post, it is outdated again with the [latest spec](https://notes.ethereum.org/SCIg8AH5SA-O4C1G1LYZHQ#) ditching the contract on the PoW main chain, and instead using a PoS beacon chain which is planned to become the main chain, with the PoW main chain planned to be later phased out. See also <https://github.com/ethereum/wiki/wiki/Sharding-FAQs#what-might-a-basic-design-of-a-sharded-blockchain-look-like>. > > What might a basic design of a sharded blockchain look like? > ============================================================ > > > A simple approach is as follows. For simplicity, this design keeps > track of data blobs only; it does not attempt to process a state > transition function. > > > There exist nodes called **proposers** that accept blobs on shard `k` > (depending on the protocol, proposers either choose which `k` or are > randomly assigned some `k`) and create **collations**, thus they also > act as a collator, and so agents that act as both a proposer and > collator may be referred to as prolators. A collation has a > **collation header**, a short message of the form "This is a collation of blobs on shard `k`, the parent collation is 0x7f1e74 and the Merkle > root of the blobs is 0x3f98ea". Collations of each shard form a chain > just like blocks in a traditional blockchain. > > > There also exist notaries that download (to ensure availability) and > verify (only in the case of an EVM existing, by executing data to ensure validity) collations in a shard > that they are randomly assigned and where they are shuffled to a new > shard every period via e.g. a random beacon chain and vote on the > availability of the data in a collation (assuming no EVM, with an EVM > they may also act as an executor and vote on the validity of data). > > > The source of randomness for the beacon chain is some publicly > Verifiable Random Function such as RANDAO or a blockhash produced by a > BLS aggregate signature. The former is preferred due to favouring > availability over consistency and does not require an honest / > uncoordinated majority assumption (i.e. no bribing attack or colluding > majority), while it probabilistically requires a [lower stake > power](https://ethresear.ch/t/rng-exploitability-analysis-assuming-pure-randao-based-main-chain/1825) > to [revert a > chain](https://gitter.im/ethereum/sharding?at=5af228fc40f24c43046242f9), > although this is minimized through using a n-of-n committee. N-of-n > means, using 3-of-3 as an example: "at every tick of the global clock > a new proposer and a new 3-member committee is elected for the RANDAO > beacon. In order for a proposal to make it through (a proposal is the > preimage corresponding to the last commitment) the proposal needs to > get all three signatures from the committee." > ([source](https://gitter.im/ethereum/sharding?at=5af95f18bd10f34a68fe366c)). > Thus, n-of-n means that all n (or n out of n) members of the committee > must sign off on the proposal. > > > A committee can then also check these votes from notaries and decide > whether to include a collation header in the main chain, thus > establishing a cross-link to the collation in the shard. Other parties > may challenge the committee, notaries, proposers, validators (with > Casper Proof of Stake), etc., e.g. with an interactive verification > game, or by verifying a proof of validity. > > > A "main chain" processed by everyone still exists, but this main > chain's role is limited to storing collation headers for all shards. > The "canonical chain" of shard `k` is the longest chain of valid > collations on shard `k` all of whose headers are inside the canonical > main chain. > > > Note that there are now several "levels" of nodes that can exist in > such a system: > > > * **Super-full node** - fully downloads every collation of every shard, as well as the main chain, fully verifying everything. > * **Top-level node** - processes all main chain blocks, giving them "light client" access to all shards. > * **Single-shard node** - acts as a top-level node, but also fully downloads and verifies every collation on some specific shard that it > cares more about. > * **Light node** - downloads and verifies the block headers of main chain blocks only; does not process any collation headers or > transactions unless it needs to read some specific entry in the state > of some specific shard, in which case it downloads the Merkle branch > to the most recent collation header for that shard and from there > downloads the Merkle proof of the desired value in the state. > > >
3,305,004
As an answer to a question I asked yesterday ([New Core Data entity identical to existing one: separate entity or other solution?](https://stackoverflow.com/questions/3293832/new-core-data-entity-identical-to-existing-one-separate-entity-or-other-solution)), someone recommended I index an attribute. After much searching on Google for what an 'index' is in SQLite/Core Data, I'm afraid I'm not closer to knowing exactly what it is or how it speeds up fetching based on an attribute. Keep in mind I know nothing about SQLite/databases in general other than a vague idea based on reading way, way, way, too much about Core Data the past few months.
2010/07/22
[ "https://Stackoverflow.com/questions/3305004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196760/" ]
Simplistically, indexing is a kind of presorting. If you have a numerical attribute index, the store maintains linked list in numerical order. If you have a text attribute, it maintains a linked list in alphabetical order. Depending on the algorithm, it can maintain other kinds of information about the attributes as well. It stores the data in the index attached to the persistent store file. It makes fetches based on the indexed attribute go faster with the tradeoff of larger file size and slightly slower inserts.
All these answers are good, but overly technical. An index is pretty much identical to the index you'd find in the back of a book. Thus if you wanted to find which page a certain word occurred at, you'd go through it alphabetically and thus quickly find the all the pages where that word occurred. If you didn't have an index, then the user would have to resort to going thru EVERY single page word by word, which could take quite a while. Thus, the index is created pretty much in this way ONLY once, and not every time the user wants to search.
29,005,275
**Important note** The focus of this question is on API endpoints that differentiate *which resources are returned depending who authenticates*, e.g. Alice gets resource A and B returned, and Bob gets resource X and Y. It is **NOT** about differentiating the representation of resources returned. All the endpoints return JSON representations of resources. **Preface** Please consider the following three potential API endpoint designs, all returning `thing` resources of a user. *Endpoint A* ``` GET /things ``` If authentication credentials for `<user_x>` are provided with the request, it returns `thing` resources that *specifically relate to `<user_x>`*. For example, authenticating user Alice gets resource A and B returned, and authenticating user Bob gets resource X and Y. So the differentiation of the response for different authenticating users is on which resource instances are returned and **NOT** on what information of these instances is returned (i.e. the resource representation). When authentication fails a 401 response is returned. *Endpoint B* ``` GET /user/<user_x>/things ``` *Endpoint C* ``` GET /things/?user_id=<user_x> ``` Both endpoint B and C provide the `thing` resource instances related to `<user_x>`, *iff* the authenticating user has the right to access these `thing` resources. The representation of the `thing` resource instances returned, e.g. what information about the resources is returned, can vary depending which user authenticates. For instance, `<user_x>` or an admin user might get back richer data per resource instance then a user with limited access rights. Authenticating users that don't have any access rights to `thing` resources of `<user_x>` will get a 401 response. **My questions** I would like to have answers to the following questions: *1) Is Endpoint A RESTful?* *2) Does Endpoint A have a good URI design?* *3) Are Endpoints B and C RESTful?* *4) Do Endpoints B and C have a good URI design?* I'm looking forward to your answers. I also provided [my own answers](https://stackoverflow.com/a/29005276/889617) below and would be grateful for feedback on that as well. Thank you! — Freddy Snijder
2015/03/12
[ "https://Stackoverflow.com/questions/29005275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889617/" ]
UPDATED 18 March 2015 13:05 CET to include feedback in the comments of the question and answers given. **RESTfulness** From a purist point of view non of the endpoints are RESTful. For instance, the question doesn't state if the responses contain links to the resources such that the client can retrieve the resources without needing knowledge about how the URIs to the resources are constructed. In fact, [as pointed out in this blogpost](http://www.intridea.com/blog/2010/4/29/rest-isnt-what-you-think-it-is), almost no API defined in practice, other then the World Wide Web itself, can be considered RESTful. So is there nothing useful to say about these endpoints? I think there is. We can talk about statelessness and idem-potency of processing the endpoints, which is important to scalability. And we can talk about safety of endpoints which is important to security. For all endpoints you could state the following: *Is it stateless?* Yes, user authentication credentials are a part of the application state and are send with every request, thus everything the server needs to know to handle the request, without keeping state, is in the request. (The complete state is transferred) *Since these endpoints process GET requests, are they idem potent?* Endpoint A) : Yes, because the request to endpoint A, including the user authentication credentials, should be considered as a whole: no matter how often you repeat the same request, with the same credentials, you will always get the `thing` resources for the authenticating user. **However**, If you only consider the URI, the request is actually not idem potent, because the response changes depending on the credentials provided. Endpoint B) and C) : Similar to A), you will always get the `thing` resources of `<user_x>` provided in the URI, no matter how often your repeat it. On top of that the requests are also idem potent only considering the URI itself, everything you need to know about the request is in the URI, the user credentials can only change the representation of the returned `thing` resources, not which resources are returned. *Since these endpoints process GET requests, are they safe?* Yes, because the request does not alter any data and does not have any other side effect. **URI design** Although from a purist REST perspective URI design is considered irrelevant, in a practical situation where software developers and API end-users use and deal with the *URI design is relevant*. *Does Endpoint A have a good URI design?* **Yes and No**. When this URI is hidden from an application user, and this will not be bookmarked or shared this design is fine. However, when this URI is exposed to end-users this URI is not designed well because when sharing this as a link the recipient won't see the same data unless she authenticates as the same user. *Do Endpoints B and C have a good URI design?* Yes, the end-user can understand semantically what the endpoint is about and the URIs are sharable between users. So, instead of defining all three end points you could chose to only define endpoints B and C because they can provide everything what endpoint A could provide, plus it is obvious from the URL what is requested. Please let me know what you think. Thank you! — Freddy Snijder
Well, first of all, in HTTP the representation of a resource is handled by the header Content-Type and Accept. But the clients can only suggest the format they prefer. The server is in charge of serve the representation that he wants. Talking about security, it's perfectly right for me to return a representation based on the security level of the token. Talking about your URL, I always prefer URL parameters instead of query parameters (some engines doesn't cache GET request with query parameters). But it depends on the structure of your data. If *user\_id* is inside *things*, it should be represented in the URL: /things/user\_id/xxxxx. On the other hand, if user\_id is not related to the resource *things*, consider remove this parameter and add it as a header (be careful with GET request and cache times).
383,272
I'm am looking to create a vehicle that can break sand block, although I don't know how. I have the body, the last thing I need is a contraption that can brake sand blocks in Minecraft
2021/03/11
[ "https://gaming.stackexchange.com/questions/383272", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/268517/" ]
Frits34000 and a couple other redditors for a good while worked on 'sand quarry' machines - you can find the assorted designs on [r/redstone](https://www.reddit.com/r/redstone/search?q=sand+quarry&restrict_sr=on&include_over_18=on). The gist of it is to lift the sand block using a sticky piston, and while it is still falling, insert a non-full block like a trapdoor into the space it's trying to land in. Unable to solidify into a regular block, sand drops as item - the machine to do just this is fairly trivial, but there are numerous caveats about making it practical. Frits34000 published a pretty in-depth tutorial on his designs and ways of dealing with the caveats.
So your trying to make a “bulldozer” vehicle. If sand falls on slabs or anything with a height of less than a block. BUT the only one that is pushable is a slab. So you can simply put slabs in front of the vehicle and move it. Note that any sand NOT above the slabs will not break.
58,009,403
What I tried so far is as follow: ![Nifi Flow for the record count](https://i.stack.imgur.com/QOM37.png) kindly describe in details how many ways you can read .csv, what I learned so far you need to provide a schema name for the file and then define a schema in the form of .avro or text. is it necessary to provide schema? thanks in advance.
2019/09/19
[ "https://Stackoverflow.com/questions/58009403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10196724/" ]
Instead of split You could consider using regex to extract a number from string ``` console.log(/\d+/.exec('test1')) --> ["1"] ```
Just replace `Number(test[0].split('test')[1])` with `Number(test[0].split('').filter(x => !isNaN(parseInt(x, 10))))` Try like this: ``` this.data.forEach(test => { this.result.run.data.push([ Number(test[0].split('').filter(x => !isNaN(parseInt(x, 10)))), Number(test[1]) ]); ... }); ``` **See [Working Demo](https://stackblitz.com/edit/angular-qyzhby?embed=1&file=src/app/app.component.ts)**
5,522,432
I have a piece of C# code that validates a textbox field to be positive numeric ``` Regex isPositiveInt = new Regex("[^0-9]"); return !isPositiveInt.IsMatch(textbox1.Text) ``` I found if the regex matches, it gives "false" and when it doesn't match, it gives "true". So I have to add a "!" to the return value. There is no problem with that, but I feel it's counterintuitive. Can someone please explain why it return a opposite result?
2011/04/02
[ "https://Stackoverflow.com/questions/5522432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/529310/" ]
The `^` meta-character has two meanings in regexes - to mark the start of the string when used by itself, and as part of the `[^...]` pattern meaning "don't match any of the characters in the `[...]` block". I think perhaps you intended `^[0-9]` instead, which will match any string that starts with a digit. It won't make sure the whole string is numeric though, as it only checks the first character and anything could come after that. If you want to make sure your string is numeric, just `^\d+$` is the way to go. `\d` is identical to `[0-9]` but easier to read, and `^` and `$` mark the start and end of the string respectively.
The `^` in the regex character class means: is NOT in the set of `0` to `9`. To match positive integers you want: ``` [0-9]+ ``` meaning one or more characters from the set of 0 to 9. Note: this will also match 0 which, strictly speaking, is not a positive integer. The expression actually matches non-negative integers.
6,919,275
Is there any feature in IIS 7 that automatically deletes the logs files older than a specified amt of days? I am aware that this can be accomplished by writing a script(and run it weekly) or a windows service, but i was wondering if there is any inbuilt feature or something that does that. Also, Currently we turned logging off as it is stacking up a large amount of space. Will that be a problem?
2011/08/02
[ "https://Stackoverflow.com/questions/6919275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814352/" ]
You can create a task that runs daily using Administrative Tools > Task Scheduler. Set your task to run the following command: ``` forfiles /p "C:\inetpub\logs\LogFiles" /s /m *.* /c "cmd /c Del @path" /d -7 ``` This command is for IIS7, and it deletes all the log files that are one week or older. You can adjust the number of days by changing the `/d` arg value.
Similar solution but in powershell. I've set a task to run powershell with the following line as an Argument.. ``` dir D:\IISLogs |where { ((get-date)-$_.LastWriteTime).days -gt 15 }| remove-item -force ``` It removes all files in the D:\IISLOgs folder older than 15 days.
151,867
Given: ``` *Main> :t text text :: (Selectable s, StringLike str, Ord str) => s -> Scraper str str ``` I need to perform "second level" `fmap` operation: ``` *Main> let z = fmap (fmap (:[])) text *Main> :t z z :: (Selectable s, StringLike a, Ord a) => s -> Scraper a [a] ``` On one hand `z` follows API structure, but otherwise I find such code hard to read. It feels like programming against stack-based machine.
2017/01/06
[ "https://codereview.stackexchange.com/questions/151867", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/57999/" ]
Sometimes you can wrap the "nested functors" in a newtype which is itself a functor, use a single `fmap` on the newtype, and unwrap. In your case: ``` import Data.Functor.Compose let z = getCompose . fmap (:[]) . Compose $ text ``` We are composing the `((->) s)` and `Scraper a` functors. The problem with this is that it trades `newtype` noise for nested `fmap` noise.
Nested fmaps are very normal in haskell and extremely common, consider: ``` myList = [Just 13, Just 7, Just 33, Nothing, Just 23] exampleFunc :: [Maybe Int] -> [Maybe Int] exampleFunc li = map (\el -> fmap (+1) el) li ``` The prelude map function is a child of the fmap type, so this simple function is using nested fmap's.
17,301,040
I am using Java with Jersey 2.0 client to make a REST call to the paypal REST API. According to the API doc, I should be making a post to: <https://api.sandbox.paypal.com/v1/oauth2/token> with the Accept: application/json and Accept-Language: en\_US. It also indicates that I should pass in the body grant\_type=client\_credentials. I do all this but I keep getting a 406 or 415. What I can't figure out is what the Content-Type of the post call should be? I've tried text/plain, text/html, application/json, form-url-encoded.. nothing seems to get me a token back. Not sure why their API doc writer didn't include the Content-Type and format of the payload in the documentation. Anyone know what the Content-Type should be for the body of the post? I'd like to add that when I do any Content-Type other than form-url-encoded, I get back 415, which means mediatype not accepted, however when I pass in anything using form-url-encoded, I get back the 406, which basically tells me the body is not acceptable. Thanks.
2013/06/25
[ "https://Stackoverflow.com/questions/17301040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2520618/" ]
First, I'll move rewrite the code in a form that's probably easier for you to understand, with the internal function definitions moved outside the main function. Note that I had to add some parameters to `interleave` and `interleave'` so that they could "see" all the same variables they had access to when they were defined within other functions. I also added type signatures for clarity. ``` permutations :: [a] -> [[a]] permutations xs0 = xs0 : perms xs0 [] ``` The function `perms` takes two lists, and creates every possible permutation of the elements in both lists -- but *not* including the original order. For example: ``` λ> perms "ab" "XY" ["aXYb","XaYb","aYXb","YaXb","baXY","abXY","aXbY","bXaY","XbaY","XabY","bYXa","YbXa","YXba","bXYa","XbYa","XYba","bYaX","YbaX","YabX","baYX","abYX","aYbX"] ``` So when we invoke it with an empty second list, as `permutations` does, it gives us all the *other* possible permutations of the input elements. All we have to do is tack on the original sequence, and we have out answer. (If you look at `permutations`, above, you'll see that's exactly what it does.) ``` λ> perms "abc" "" ["bac","cba","bca","cab","acb"] ``` Here's the definition or `perms`. ``` perms :: [a] -> [a] -> [[a]] perms [] _ = [] perms (t:ts) is = foldr (interleave (t:ts)) (perms ts (t:is)) (permutations is) ``` The function `interleave` takes two lists, and generates every possible way to shuffle them together (as you would a pack of cards). It then appends the third list onto the list of possible shuffles. For example: ``` λ> interleave "ab" "XY" ["@", "#"] ["aXYb","XaYb","@","#"] ``` Here's its definition: ``` interleave :: [t] -> [t] -> [[t]] -> [[t]] interleave (t:ts) xs r = let (_,zs) = interleave' (t:ts) id xs r in zs interleave' :: [t] -> ([t] -> a) -> [t] -> [a] -> ([t], [a]) interleave' (_:ts) _ [] r = (ts, r) interleave' (t:ts) f (y:ys) r = let (us,zs) = interleave' (t:ts) (f . (y:)) ys r in (y:us, f (t:y:us) : zs) ```
Try to think of any recursive call as simply a call to the same function but with different parameters (hopefully, otherwise you may have an infinite loop), then try to follow the logic of a very simple example, like `permutations []`, `permutations [1]` or `permutations [1,2]`. Look for when the inner expressions reduce to the base case, which is where no more recursion happens. For example `interleave'` has the base-case `interleave' _ []` and `perms` has `perms [] _ = []`. Although I may get a bit lost myself trying to follow the windings of this function, I'm sure you will find that some expressions will reach the base-case and unfolding from there, you will be able to evaluate the recursive calls that led there.
53,442,231
I have a simple asp.net-core app using version 2.1. The HomeController has a page with the authorized attribute. When I click on the About page that needs authorization I get to the Login page and after typing my username and password the following happens: * the user is successfully logged in * the user is redirected to /Home/About * HomeController.About method is hit in the debugger and the About view is served. * Somehow the user is redirected back to the AccountController.Login * the user is logged in so I can navigate to any page now that needs authorization. I tried this with Chrome and Edge as well. I can reproduce the error with both browser. I created a small repro project that reproduces the issue on my machine and setup. [Portfolio\_Authentication](https://github.com/gyurisc/Portfolio_Authentication) The steps I am using to reproduce the problem are the following: 1. Register a user on the website 2. Log out the user if it is logged in. 3. Click on the About menu link in the header. 4. Type in the username and password 5. Notice the authentication is ok as the user name can be see top right side of the screen but the login does not redirect to the About page. I am wondering why this is happening and how to correct this? Thanks for helping me. All feedback is welcome. HomeController: ``` public class HomeController : Controller { public IActionResult Index() { return View(); } [Authorize] public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } } ``` My Startup.cs looks the following: ``` public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // services.AddAuthentication(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/LogIn"; options.LogoutPath = "/Account/LogOff"; }); // Add application services. services.AddTransient<IEmailSender, EmailSender>(); services.AddMvc() .AddFeatureFolders(); // .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); ; } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } ``` and this is the log I see in my output window in Visual Studio: ```none Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (1ms) [Parameters=[@__normalizedUserName_0='?' (Size = 256)], CommandType='Text', CommandTimeout='30'] SELECT TOP(1) [u].[Id], [u].[AccessFailedCount], [u].[ConcurrencyStamp], [u].[Email], [u].[EmailConfirmed], [u].[LockoutEnabled], [u].[LockoutEnd], [u].[NormalizedEmail], [u].[NormalizedUserName], [u].[PasswordHash], [u].[PhoneNumber], [u].[PhoneNumberConfirmed], [u].[SecurityStamp], [u].[TwoFactorEnabled], [u].[UserName] FROM [AspNetUsers] AS [u] WHERE [u].[NormalizedUserName] = @__normalizedUserName_0 Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (2ms) [Parameters=[@__user_Id_0='?' (Size = 450)], CommandType='Text', CommandTimeout='30'] SELECT [uc].[Id], [uc].[ClaimType], [uc].[ClaimValue], [uc].[UserId] FROM [AspNetUserClaims] AS [uc] WHERE [uc].[UserId] = @__user_Id_0 Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (1ms) [Parameters=[@__userId_0='?' (Size = 450)], CommandType='Text', CommandTimeout='30'] SELECT [role].[Name] FROM [AspNetUserRoles] AS [userRole] INNER JOIN [AspNetRoles] AS [role] ON [userRole].[RoleId] = [role].[Id] WHERE [userRole].[UserId] = @__userId_0 Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: Identity.Application signed in. Portfolio.Features.Account.AccountController:Information: User logged in. Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action method Portfolio.Features.Account.AccountController.Login (Portfolio), returned result Microsoft.AspNetCore.Mvc.RedirectResult in 32.6215ms. Microsoft.AspNetCore.Mvc.Infrastructure.RedirectResultExecutor:Information: Executing RedirectResult, redirecting to /Home/About. Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action Portfolio.Features.Account.AccountController.Login (Portfolio) in 41.5571ms Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 49.3022ms 302 Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44392/Home/About Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "About", controller = "Home"}. Executing action Portfolio.Features.Home.HomeController.About (Portfolio) Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization was successful. Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method Portfolio.Features.Home.HomeController.About (Portfolio) - Validation state: Valid Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action method Portfolio.Features.Home.HomeController.About (Portfolio), returned result Microsoft.AspNetCore.Mvc.ViewResult in 2212.7896ms. Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor:Information: Executing ViewResult, running view About. Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor:Information: Executed ViewResult - view About executed in 3.1424ms. Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action Portfolio.Features.Home.HomeController.About (Portfolio) in 2225.297ms Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 2233.0907ms 200 text/html; charset=utf-8 Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44392/Account/Login?ReturnUrl=%2FHome%2FAbout Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "Login", controller = "Account"}. Executing action Portfolio.Features.Account.AccountController.Login (Portfolio) Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method Portfolio.Features.Account.AccountController.Login (Portfolio) with arguments (/Home/About) - Validation state: Valid Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: Identity.External signed out. Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action method Portfolio.Features.Account.AccountController.Login (Portfolio), returned result Microsoft.AspNetCore.Mvc.ViewResult in 1528.1878ms. Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor:Information: Executing ViewResult, running view Login. Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor:Information: Executed ViewResult - view Login executed in 5.8984ms. Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action Portfolio.Features.Account.AccountController.Login (Portfolio) in 1543.8386ms Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 1553.3133ms 200 text/html; charset=utf-8 Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44392/lib/bootstrap/dist/css/bootstrap.css Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44392/css/site.css Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware:Information: Sending file. Request path: '/css/site.css'. Physical path: 'C:\dev\web\portfolio-variants\Portfolio_Controller_V2\Portfolio\wwwroot\css\site.css' Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware:Information: Sending file. Request path: '/lib/bootstrap/dist/css/bootstrap.css'. Physical path: 'C:\dev\web\portfolio-variants\Portfolio_Controller_V2\Portfolio\wwwroot\lib\bootstrap\dist\css\bootstrap.css' Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 28.4192ms 200 text/css Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 41.4384ms 200 text/css ```
2018/11/23
[ "https://Stackoverflow.com/questions/53442231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260/" ]
You haven't used this middleware in Configure method of startup class. ``` app.UseAuthorization(); ``` Place this middleware after `app.UseAuthentication();`
You should also call `services.AddAuthentication` in the `ConfigureServices` method in you start-up file. The call to `AddAuthentication` should be configured to your application needs. (Cookie, External Logins, etc.) Even though you are not migrating from 1.x to 2.x the following article I find it very useful: [Migrate authentication and Identity to ASP.NET Core 2.0](https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x?view=aspnetcore-2.1).
168,923
In Russia we have something like a tradition: we like to look for lucky tickets. Here's what a regular ticket looks like: [![bus ticket](https://i.stack.imgur.com/0bqM1m.jpg)](https://i.stack.imgur.com/0bqM1m.jpg) As you can see, the ticket has a six-digit number. A six-digit number is considered **lucky** if the sum of the first three digits is equal to the sum of the last three. The number on the photo is not lucky: ``` 038937 038 937 0 + 3 + 8 = 11 9 + 3 + 7 = 19 11 != 19 ``` Challenge --------- Given the limits of a range (inclusive), return the number of lucky ticket numbers contained within it. Parameters ---------- * Input: 2 integers: the first and last integers in the range * The inputs will be between 0 and 999999 inclusive * Output: 1 integer: how many lucky numbers are in the range * You may take the inputs and return the output in [any acceptable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * Assume leading zeros for numbers less than 100000. Examples -------- ``` 0, 1 => 1 100000, 200000 => 5280 123456, 654321 => 31607 0, 999999 => 55252 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes in every language wins. Update: here's the lucky one [![lucky one](https://i.stack.imgur.com/a5RK9.jpg)](https://i.stack.imgur.com/a5RK9.jpg)
2018/07/20
[ "https://codegolf.stackexchange.com/questions/168923", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/72497/" ]
[Husk](https://github.com/barbuz/Husk), 12 bytes ================================================ ``` #ȯ§¤=Σ↓↑3↔d… ``` [Try it online!](https://tio.run/##yygtzv7/X/nE@kPLDy2xPbf4UdvkR20TjR@1TUl51LDs////hgYg8N8ITAEA "Husk – Try It Online") Explanation ----------- ``` #(§¤=Σ↓↑3↔d)… -- example input: 100000 101000 … -- inclusive range: [100000,100001..100999,101000] #( ) -- count elements where (example with 100010) d -- | digits: [1,0,0,0,1,0] ↔ -- | reversed: [0,1,0,0,0,1] § 3 -- | fork elements (3 and [0,1,0,0,0,1]) ↑ -- | | take: [0,1,0] ↓ -- | | drop: [0,0,1] ¤= -- | > compare the results by equality of their Σ -- | | sums 1 == 1 -- | : 1 -- : 3 ```
[Java (OpenJDK 8)](http://openjdk.java.net/), 162 bytes ======================================================= ... borrows from the Kotlin example above. ```java import java.util.stream.IntStream; (a,b)->IntStream.range(a,b+1).mapToObj(i->String.format("%06d",i).getBytes()).filter(c->c[0]+c[1]+c[2]==c[3]+c[4]+c[5]).count(); ``` [Try it online!](https://tio.run/##lVHBasMwDL33K0RhYNPEJGkbGKU97DZYt0N3Czk4rps5dewQOx1h9NszO@1Gd1uFLcl6EnqSK3qioW64qvbHQdSNbi1ULkY6KyQxtuW0Js/K7kZvNZkwSY2BLRXqawIglOXtgTIOLx079q9dXfDWeARAalXCh/7cUtUjlwg08PlQ4JXDz@66Yyy1gv2pBnn7WMOAaFDgcPPLgrRUldxHZzEmNW3e9VtRIRFuHC5USQ66ralF04co3U8DgUnJ7VNvuUEYk4OQjjNi4YZlUT5jWexVkq/XLJt7d@HVMseE6U5ZhFeDGxug6QrpmF4Jn7TYQ@22gC49sxwovsy9643lNdGdJY2DrFTodiLysxKfC1EwmhiPS/l/cRx5CZLR3F2czBfLNEiXi3lyd@cr7cdR8PUvz8M3 "Java (OpenJDK 8) – Try It Online") Comparing the sum of the String's bytes is just as good as summing up the actual digits.
36,483
Is there a free broswer that will hide your IP address when surfing and downloading on the Internet?
2009/09/06
[ "https://superuser.com/questions/36483", "https://superuser.com", "https://superuser.com/users/10625/" ]
Due to the way the internet works, it is impossible to 'disable' your IP address from others seeing it. One possible solution is to use an anonymous proxy, such as TOR, an SSH tunnel, or a PHProxy. The quickest solution would have to a PHProxy. You can find plenty using a quick [Google search](http://www.google.com/search?hl=en&safe=off&client=safari&rls=en&q=phproxy+%2B%22Includes+a+mini+URL-form+on+every+HTML+page%22+%2Bintitle%3A%22PHProxy%22+%2B%22Store+cookies+for+this+session+only%22&aq=f&oq=&aqi=). Here's an [example PHProxy site](http://profile.iiita.ac.in/sranjan1_01/shaktie/). A possibly more 'secure' and anonymous proxy is TOR. Here is what [their website](http://www.torproject.org/) has to say about themselves: > > Tor protects you by bouncing your communications around a distributed network of relays run by volunteers all around the world > > > Checkout this [Lifehacker snippit](http://lifehacker.com/331996/browse-the-internet-anonymously-with-tor) for instructions on setting it up
I find TOR to be very slow. Try [Ultrasurf](http://www.ultrareach.com/). It was designed to get around the [great firewall of china](http://en.wikipedia.org/wiki/Golden_Shield_Project). If you use firefox you should also download the plugin. <http://www.ultrareach.net/download_en.htm>
210,173
I've searched on the internet for a while and asked my question on apples website discussions.apple.com as well, however I haven't found and answer yet and people aren't responding on apple's site so I'd though I'd give it a go here. So, I have an external drive (1TB) that I made journaled encrypted when I first started using it. By now I also have some video files and pictures on them that I'd wish to show on my TV. However, whilst encrypted I could not view the files other than on a Mac (I was trying to view them on a media player connected to the TV). Thus, I opted for decrypting the drive, since I used up almost 900 GB of the 1TB there are quite a lot of files and I understood the process might take a while. **The thing is, every time I plug the hard drive in it starts taking up storage space.** I use a Macbook Pro and don't have a lot of storage space on the macbook itself, hence the external drive and why this is really annoying. To be clear, it is my MacBooks storage space that gets filled up when I plug it in, since this happens every time I can't use the drive on my Macbook anymore either, because every time I can only use it a few minutes before I get warned that "My macbook is almost out of storage space, please remove some files". When I unplug the drive I can literally see the free storage space increasing. So some process is taking up storage space whilst it is working on the drive. I thought this might be spotlight but I'm not sure since it could also be the decrypting process copying files or something. **Is there a way to know why my storage space get filled up, and if its the decrypting, is there a way to stop this process so I can copy my files to another drive?** And if it's spotlight is there a way to disable this because putting the drive in the privacy tab of spotlight is somehow also not doable. I don't mind wiping the drive, but I do mind wiping it without backing up the files on the drive (Yes, in the future I will back up my files better so this won't be an issue again), so a solution to stop the storage filling up is very welcome. Thanks in advance!
2015/10/09
[ "https://apple.stackexchange.com/questions/210173", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/151551/" ]
It might be tricky to pick apart the failure with caches being deleted. One thing that always works for me is to boot to a USB drive with a clean OS and sign in to the App Store. If I get a failure there, I know the problem is on Apple's side or in the network. If not, I have the app and know my system / library are not helping and can take action there once I'm sure the issue is with my customizations and specific install and not a server issue.
Below works from me. Using `Terminal` run below command ``` open $TMPDIR../C/ ``` Above command will open `Finder` window. In this window, find folder `com.apple.appstore` and delete it.
13,294,952
I'm using ggplot and have two graphs that I want to display on top of each other. I used `grid.arrange` from gridExtra to stack them. The problem is I want the left edges of the graphs to align as well as the right edges regardless of axis labels. (the problem arises because the labels of one graph are short while the other is long). **The Question:** How can I do this? I am not married to grid.arrange but the ggplot2 is a must. **What I've tried:** I tried playing with widths and heights as well as ncol and nrow to make a 2 x 2 grid and place the visuals in opposite corners and then play with the widths but I couldn't get the visuals in opposite corners. ``` require(ggplot2);require(gridExtra) A <- ggplot(CO2, aes(x=Plant)) + geom_bar() +coord_flip() B <- ggplot(CO2, aes(x=Type)) + geom_bar() +coord_flip() grid.arrange(A, B, ncol=1) ``` ![enter image description here](https://i.stack.imgur.com/gvnx5.png)
2012/11/08
[ "https://Stackoverflow.com/questions/13294952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1000343/" ]
I know this is an old post, and that it has already been answered, but may I suggest combining @baptiste's approach with `purrr` to make it nicer-looking: ``` library(purrr) list(A, B) %>% map(ggplotGrob) %>% do.call(gridExtra::gtable_rbind, .) %>% grid::grid.draw() ```
At best this is a hack: ``` library(wq) layOut(list(A, 1, 2:16), list(B, 2:3, 1:16)) ``` It feels really wrong though.
48,090,119
I recently installed jupyter notebooks on my macbook pro. When I create a new notebook, I see the following exception coming continuously on the terminal where I started the notebook. ``` Monideeps-MacBook-Pro:PythonNotebooks monideepde$ jupyter-notebook [I 12:18:43.675 NotebookApp] Serving notebooks from local directory: /Users/monideepde/Documents/PythonNotebooks [I 12:18:43.675 NotebookApp] 0 active kernels [I 12:18:43.676 NotebookApp] The Jupyter Notebook is running at: [I 12:18:43.676 NotebookApp] http://localhost:8888/?token=dcb1990694d91ded77f4287a588886ea567b5907ac8aeafa [I 12:18:43.676 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [C 12:18:43.677 NotebookApp] Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://localhost:8888/?token=dcb1990694d91ded77f4287a588886ea567b5907ac8aeafa [I 12:18:43.896 NotebookApp] Accepting one-time-token-authenticated connection from ::1 [W 12:18:44.778 NotebookApp] 404 GET /static/components/moment/locale/en-gb.js?v=20180104121843 (::1) 21.10ms referer=http://localhost:8888/tree [I 12:18:54.840 NotebookApp] Creating new notebook in [W 12:18:55.716 NotebookApp] 404 GET /static/components/moment/locale/en-gb.js?v=20180104121843 (::1) 3.06ms referer=http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2 [I 12:18:55.920 NotebookApp] Kernel started: 5e16fa4b-3e35-4265-89b0-ab36bb0573f5 [W 12:18:55.941 NotebookApp] 404 GET /nbextensions/widgets/notebook/js/extension.js?v=20180104121843 (::1) 5.57ms referer=http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2 [I 12:18:56.998 NotebookApp] Adapting to protocol v5.1 for kernel 5e16fa4b-3e35-4265-89b0-ab36bb0573f5 [E 12:18:57.001 NotebookApp] Uncaught exception in /api/kernels/5e16fa4b-3e35-4265-89b0-ab36bb0573f5/channels Traceback (most recent call last): File "/Library/Python/2.7/site-packages/tornado-5.0a1-py2.7-macosx-10.13-intel.egg/tornado/websocket.py", line 494, in _run_callback result = callback(*args, **kwargs) File "/Library/Python/2.7/site-packages/notebook-5.2.2-py2.7.egg/notebook/services/kernels/handlers.py", line 258, in open super(ZMQChannelsHandler, self).open() File "/Library/Python/2.7/site-packages/notebook-5.2.2-py2.7.egg/notebook/base/zmqhandlers.py", line 168, in open self.send_ping, self.ping_interval, io_loop=loop, TypeError: __init__() got an unexpected keyword argument 'io_loop' [I 12:18:58.021 NotebookApp] Adapting to protocol v5.1 for kernel 5e16fa4b-3e35-4265-89b0-ab36bb0573f5 ``` Python version is 2.7. Any pointers to how I can resolve this?
2018/01/04
[ "https://Stackoverflow.com/questions/48090119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4441239/" ]
Downgrade tornado, this worked for me. `pip install tornado==4.5.3` based on: <https://github.com/liftoff/GateOne/issues/689>
It is a version incompatibility issue. Upgrading Jupyter solves it. Here is what you should try in macOS: ``` pip install --upgrade jupyter ```
1,744,340
I was going over a Perl script written by someone else and I am not too familiar with Perl so could someone let me know what do the first three lines do? ``` my $ref = do($filename); $ref != 0 or die "unable to read/parse $filename\n"; @varLines=@{$ref}; foreach $ord (@varLines) { # code here } ``` This is in the beginning of the program after the `$filename` is set with getting the commandline arguments The format of the file being passed to this script is ``` [ { "Key1" => "val1", "key2" => " "A", }, { "Key3" => "val2", "key4" => " "B", }, ] ```
2009/11/16
[ "https://Stackoverflow.com/questions/1744340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/178437/" ]
It does this: * `my $ref = do($filename)` executes the Perl code in the file whose name is `$filename` ([ref](http://perldoc.perl.org/5.8.8/functions/do.html)) and assignes to `$ref` the value of the last command in the file * `$ref != 0 or die …` is intended to abort if that last command in `$filename` wasn't successful (see comments below for discussion) * `@varLines=@{$ref};` assumes that `$ref` is a reference to an array and initialises `@varLines` to the contents of that array * `foreach $ord (@varLines) { … }` carries out some code for each of the items in the array, calling each of the `$ord` for the duration of the loop Critically, it all depends on what is in the file whose name is in `$filename`.
[perldoc -f do](http://perldoc.perl.org/functions/do.html) > > * **do EXPR** > > > Uses the value of EXPR as a filename and executes the contents of the file as a Perl script. > > > > ``` > do 'stat.pl'; > > ``` > > is just like > > > > ``` > eval `cat stat.pl`; > > ``` > > except that it's more efficient and concise, keeps track of the current filename for error messages, searches the @INC directories, and updates `%INC` if the file is found. See ["Predefined Names" in perlvar](http://perldoc.perl.org/perlvar.html#Predefined-Names) for these variables. It also differs in that code evaluated with `do FILENAME` cannot see lexicals in the enclosing scope; `eval STRING` does. It's the same, however, in that it does reparse the file every time you call it, so you probably don't want to do this inside a loop. > > > In this case, it appears that it is expected that the contents of `$filename` give a result of something like ``` [ "line1", "line2", "line3", ] ``` and the `foreach` loop will then process each item.
52,269,451
i have to validate if given input string is valid cordinate or not ``` string s1 = "78;58|98;52"; ``` This is valid cordinate is "78;58|98;52" => "Width;Height|X,Y"
2018/09/11
[ "https://Stackoverflow.com/questions/52269451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1481713/" ]
Try this pattern: `(\d+(?:\.\d+)?);(?1)\|(?1);(?1)`. `(\d+(?:\.\d+)?)` matches numbers: integers or decimal numbers, where decimal character is `.` (dot). `(?1)` - references above pattern to match it four times. [Demo](https://regex101.com/r/evqZEV/1) Try this code: ``` string[] coords = { "78;58|98;54", "78.1;58.23|98;54.12", "78;58.23|98.13;54" }; Regex regex = new Regex(@"(\d+(?:\.\d+)?;?){2}|(\d+(?:\.\d+)?;?){2}"); foreach (string coord in coords) if (regex.Match(coord).Success) MessageBox.Show($"Success with string {coord}"); ``` It uses `(\d+(?:\.\d+)?;?){2}|(\d+(?:\.\d+)?;?){2}` as pattern, since I couldn't figure out how to backreference pattern in C#. It's just first pattern expanded.
Try this ``` (\d+;\d+)\|(\d+;\d+) ``` [Demo](https://regex101.com/r/rfrUrg/2)
175,664
ISTQB, Wikipedia or other sources classify verification acitivities (reviews etc.) as a static testing, yet other do not. If we can say that peer reviews and inspections are actually a kind of a testing, then a lot of standards do not make sense (consider e.g. ISO which say that validation is done by testing, while verification by checking of work products) - it should at least say dynamic testing for validation, shouldn't it? I am completing master thesis dealing with QA and I must admit that I have never seen worse and more ambiguous and contradicting literature than in this field :/ Do you think (and if so, why) that static testing is a good and justifiable term or should we stick to testing and static checks/analysis? Wikipedia: ***Static testing*** is a form of software testing where the software isn't actually used. This is in contrast to dynamic testing. It is generally not detailed testing, but checks mainly for the sanity of the code, algorithm, or document. It is primarily syntax checking of the code and/or manually **reviewing the code or document** to find errors. This type of testing can be used by the developer who wrote the code, in isolation. Code reviews, inspections and walkthroughs are also used. EDIT: One of the many sources that mentiones static testing to employ reviews etc. (look for "static testing" in Google books): ![enter image description here](https://i.stack.imgur.com/y768h.jpg)
2012/11/13
[ "https://softwareengineering.stackexchange.com/questions/175664", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/60327/" ]
I've never heard of the term "static testing". I have only heard of the term "static analysis", which refers to any time a work product is examined without being used. This includes code reviews as well as using tools such as lint, FindBugs, PMD, and FxCop. Here is some information from sources that I have available: * Section 5 (Software Testing) of the [Guide to the Software Engineering Body of Knowledge](http://swebok.org/) does not reference "static testing". It refers to "static software quality management techniques" described in Section 11 (Software Quality). Section 11 only has a single mention of tools being used to support these activities, stating that the analytic static activities may be conducted "with or without the assistance of tools". * Ian Sommerville's [Software Engineering, 8th Edition](https://rads.stackoverflow.com/amzn/click/com/0321313798)'s glossary specifically mentions static analysis as being a "tool-based analysis of a program's source code to discover errors and anomalies". However, in Chapter 22.3, Sommerville does refer to inspections as "one form of static analysis". There is no reference to "static testing". This book is considered one of the canonical references about the breadth of software engineering and is often cited as recommended reading before both IEEE certification exams. * Roger S. Pressman's [Software Engineering: A Practitioner's Approach, 6th Edition](https://rads.stackoverflow.com/amzn/click/com/0077227808) makes no references to static analysis or static testing that I could find in the index or the chapters on testing. * Steve McConnell's [Code Complete, 2nd Edition](https://rads.stackoverflow.com/amzn/click/com/0735619670) makes no specific references to either static analysis or static testing. However, Chapter 30.2 has a section about analyzing code quality. Tools to automatically check syntax and semantics are called tools that "examine the static source code to assess its quality". A specific example is Lint, which is frequently referred to as a static analysis tool by other sources. Analysis tools can only be used to verify the product. Human reviews of artifacts can be used to perform both verification and validation. Testing that involves the software's execution can be verification, validation, or both, depending on the context. The key difference is that verification is concerned with finding mistakes and defects. In contrast, validation is concerned with ensuring the requirements adequately describe the customer/user's needs, and the work artifacts (design, implementation, and tests) correspond to the requirements (and the products that they are derived from).
Code reviews nowadays may, on occasion, pick up bugs. But they are more about reviewing the quality of the code rather than the quality of the product. But there was a time when static testing -- stepping through the code with an eye to catching bugs -- was a justifiable technique. That time was when compilation was something you put in a VMS queue and waited four hours for it to run. Then you'd set up a test run and put it at the back of the same queue. Or, earlier, you'd print the code out on cards and carry them over to an operations room, expecting to be able to test it in a couple of days. Spending an hour running through the code before (or, often, while) waiting for that was a very good idea. Now you can compile in seconds and run instantly, so the benefits of static testing have long gone. But those days were less than 20 years ago, for some of us, and that might be why you're still seeing reference to code reviews as an application QA activity.
9,971,506
I've got this in my XAML: ``` <Grid.Resources> <Storyboard x:Name="Storyboard_Animation"> <DoubleAnimation Storyboard.TargetName="button_Submit" Storyboard.TargetProperty="Angle" From="0" To="360" Duration="0:0:1"></DoubleAnimation> </Storyboard> </Grid.Resources> ``` I have the button in the same Grid: ``` <Button Grid.Row="0" Grid.Column="1" Content="Submit" Margin="0" Name="button_Submit" Click="button_Submit_Click"> <Button.Template> <ControlTemplate> <Image Source="Images/buttonImage.png"></Image> </ControlTemplate> </Button.Template> <Button.RenderTransform> <RotateTransform></RotateTransform> </Button.RenderTransform> </Button> ``` I have this in my click method: ``` private void button_Submit_Click(object sender, RoutedEventArgs e) { Storyboard_Animation.Begin(); } ``` When I click on my button I get the error: Cannot resolve TargetProperty Angle on specified object. But, I have no idea what I'm supposed to use other than Angle. I have this other piece of code that works fine: ``` private void RotateStar() { button_Submit.RenderTransformOrigin = new Point(0.5, 0.5); button_Submit.RenderTransform = new RotateTransform(); DoubleAnimation da = new DoubleAnimation { From = 0, To = 360, Duration = TimeSpan.FromSeconds(0.3) }; Storyboard.SetTarget(da, button_Submit.RenderTransform); Storyboard.SetTargetProperty(da, new PropertyPath(RotateTransform.AngleProperty)); Storyboard sb = new Storyboard(); sb.Children.Add(da); sb.Begin(); } ``` I'd like to put the storyboard in the XAML instead of in code. What do I need to add/change in my XAML version so that it works like the code version?
2012/04/02
[ "https://Stackoverflow.com/questions/9971506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32892/" ]
You can try with Z-index: just google it about Z-index: You can get online example in W3schools See here: **<http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_zindex>**
@user1307242 try this ``` <div> <div style="position:absolute; z-index:-1"> <img url='image path'/> </div> <div style="z-index:2"> <Text box> </div> </div> ```
4,345
I picked up one of those cheap canvas garages from Costco, to keep a few things out of the weather. It's 10' wide, 20' long, and maybe 11' high at the peak. Our area is a bit prone to windstorms. I'm in the woods, so it's largely protected from the wind, but I still want to make sure it stays put. It comes with tent stakes, but the ground is too soft for that to be reliable. I thought about trying to attach it to concrete pier blocks, since they are heavy, cheap, and aren't permanent if we want to move the garage later. I'd put one under each leg, and fasten the leg to the block. ![pier block](https://i.stack.imgur.com/0G9yh.jpg) The blocks are formed with a hole in the top, about 5/8" diameter. The garage comes with some concrete anchors, presumably for use if you put it on a concrete driveway - you'd drill holes and secure it there. The anchors are way too small for these holes, though. Even the biggest anchors at the local hardware store seem too small. I could try to buy larger anchors online. I could epoxy in some inverted screws. I could try to find some old railroad ties and screw in to those, instead. I'm not sure where to find those around here, however. I could pour small concrete footings, although then I'm locked in to an exact setup. What should I do?
2011/02/01
[ "https://diy.stackexchange.com/questions/4345", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/80/" ]
> > I'm in the woods, so it's largely protected from the wind, but I still want to make sure it stays put. > > > Tie it to the trees. If you're willing to dig a little find a root, rope under the root, and tie the tarp to that. For a no-cement job try something like a 'snow anchor'. Tie your tarp down to a metal stake or a brick then bury that. The thing you tie to doesn't need to be heavy. The soil holds it down. Steel cable would be better than rope for this.
I purchased two very similar shelters with similar site features but decided the shelters would be permanently located. One site had the added benefit of asphalt which made anchoring very easy. The second site was a clearing in woods much the same as the other writer, which we further cleared of all weak/sickly trees in the immediate area. Throwing northern winters into the recipe, we decided on sunken concrete footings. After laser squaring the building footprint we chose to pour three 6" by 48" Sonotube footings per side. Then using four inch galvanized steel deck post mounts, we tied each set of three footings together with beams created by stacking and screwing together two pressure treated 2 X 4 for each side. This gave a flat surface for the building frames feet to bolt down to. Next for support, drainage, elevation and a dry floor, we covered the footprint with three inches of compressed class five and another three inches of driveway rock flush up to the top of the beams. After assembling the structure we ran eight lengths of stainless steel cable under the beams and up over the first row frame cross bracing as added wind protection.
2,743,758
For example, i downloaded [Gecko 1.9.1](http://releases.mozilla.org/pub/mozilla.org/xulrunner/releases/1.9.1.7/sdk/xulrunner-1.9.1.7.en-US.win32.sdk.zip) SDK. It contains js3250.dll. How i can be sure that this dll is thread-safe? Advance Thanks -Parimal Das
2010/04/30
[ "https://Stackoverflow.com/questions/2743758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/255865/" ]
You'll have to read the documentation of the particular library.
If there was such a tool then we would all be using it on our threaded code. Such a tool is impossible to write. You can flag questionable features, so you can say that a particular piece of code is *not* thread safe, but cannot guarantee that it is. Working at the object code level in a dll would make the problem even more difficult.
10,232,766
I need to implement a template tag that will return a string with a collection of items from an object. I had created the following structure: ``` produtos/ templatetags/ __init__.py produto_tags.py ``` produto\_tags.py: ``` # -*- coding: utf-8 -*- from django import template from django.template import Node from produto.models import Produto from django.template.loader import render_to_string register = template.Library() @register.tag def get_all_tags(parser, token): args = token.split_contents() return ProdutoTemplateNode(args[1]) class ProdutoTemplateNode(Node): def __init__(self, produto): self.produto = produto def render(self, context): list = [] produto = template.Variable(self.produto).resolve(context) tags = produto.tags.all() if tags: for tag in tags: list.append(tag.name) return ", ".join(list) else: return u'Não existem tags para este produto' ``` Template: ``` {% load produto_tags %} ... {% for produto in produtos %} <li id="{{ produto.ordenacao }}" data-tags="{% get_all_tags produto %}"> ... </li> {% endfor %} </ul> {% else %} <p>Não existem produtos cadastrados no sistema</p> {% endif %} ``` I am receiving this error: ``` TemplateSyntaxError at /concrete/nossos-sites.html Invalid block tag: 'get_all_tags', expected 'empty' or 'endfor' ``` I read other threads where people said this error occurs if the Tag does not exist and it seems to be the case. I've been looking on the djangoproject.com documentation as well and I could not find any clue about what might be happening. Thanks!
2012/04/19
[ "https://Stackoverflow.com/questions/10232766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1245255/" ]
That was tricky, even though simple: First, there was another 'produto\_tags.py' in another folder elsewhere in the project: ``` project/ common/ templatetags/ produtos_tags.py produtos/ templatetags/ produtos_tags.py ``` So, at first I have moved all code from produtos/templatetags/ to common/templatetags/. But when I did it Django started whining about not finding the produtos\_tags from produtos. Afterwards I got the code back to produtos/templatetags/ and renamed the file to tags\_produtos.py, what had worked to show the easy part that is my wrong import below: Wrong: ``` from produto.models import Produto ``` Correct: ``` from produtos.models import Produto ```
Follow Daniel and Ignacio's suggestions first. Also, its weird that you have `{% load produto_tags %}` in the top of the template but got an invalid block error: if `produto_tags` cannot be loaded, the error should be something like 'produto\_tags is not a valid tag' blahblah. Could you please check the code and path structure you posted, again?
33,293
Может ли шок быть позитивным,иметь положительный характер? Мой учитель по русскому языку,при разборе одного из заданий пробного ЕГЭ, объяснил мне,что шок может носить только негативный характер.Т.е. нельзя быть шокированным из-за чего то приятного,позитивного.Так ли это? (к слову,вот тот самый вариант из задания ЕГЭ. В предложении "Меня шокировало прекрасное выступление детей,..." нарушена лексическая норма)
2014/05/12
[ "https://rus.stackexchange.com/questions/33293", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/3793/" ]
Честно говоря, терпеть не могу модное выражение, особо любимое блондинками (не по цвету волос, а по IQ), по любому поводу "я в шоке". Шок - это тяжелое состояние, наступающее от сильнейшего психологического или физического потрясения. Поэтому, думаю, в данном случае уместнее сказать "приятно удивлены" или, если необходимо усилить, "приятно поражены".
Ближайшим синонимом "шокировать" будет "эпатировать". В отличии от "потрясения",которое может произойти самопроизвольно, независимо от воли "потрясающего", шокируют вполне осознано выходя за рамки принятых в обществе норм. Как правило красивые и тем более прекрасные вещи в рамки общества вписываются и поэтому даже если они удивительны, то они способны потрясти, но не шокировать: > > *Меня потрясли прекрасные вокальные данные Сьюзан Бойл, столь контрастирующие с её внешностью и поведением*. > > > Замени в данном примере и получится бессмысленность, так как тогда выйдет, что я считаю подобное прекрасное пение на сцене неприемлемым в обществе, но если так, то почему оно прекрасно? Так что значит прекрасное не может шокировать? Отнюдь. Если по каким-то причинам что-либо прекрасное в обществе непринято выставлять напоказ, а показали: > > Меня шокировала прекрасная обнажённая девушка стоящая на улице. > > > Также прекрасное может шокировать, если услышишь его в обществе, где нормы о прекрасном, сильно расходятся с твоими. Скажем прекрасное исполнение русской песни от русскоязычного в России не удивит, а услышав тоже самое от представителя племени Тумба-юмба в глухой Амазонии лёгкий шок испытать можно, хотя это не отменяет прекрасность исполнения. Что касается конкретного примера: > > Меня шокировало прекрасное выступление детей > > > То мне сложно представить такую ситуацию, когда это может шокировать. Хотя если эти дети выступают в стриптиз-клубе клубе или эту сцену этого представления режиссёр вставил в конец фильма наподобие "Трудно быть Богом" Германа-ст., то прекрасное выступление детей может и шокировать, хотя в 99% случаев шокировать прекрасным действительно невозможно.
64,015,175
I know there is a lot of answers for this already but it just doesn't work. I am trying to make my php script to create a folder on my ubuntu apache server. ``` if (!@mkdir($url, 0700, true)) { $error = error_get_last(); echo $error['message']; } ``` Now I have changed the permission for `www-data` to `777` and `www-data` owns the folder `var/www/html` and all of the subdirectories. Now what to do? The `$url` I pass is `/files/test3` I have tested with `/files/test3/` as well but that doesn't work. Edit: This is how my files are sorted atm using `tree` [![This is how my files are sorted atm using tree](https://i.stack.imgur.com/Q3yVX.png)](https://i.stack.imgur.com/Q3yVX.png)
2020/09/22
[ "https://Stackoverflow.com/questions/64015175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Just don't use `svn2git`, because * even mentioned `git-svn` allow more flexibility in initial SVN-tree * *if* core `git-svn` will not be able to handle your tree correctly (but I don't think so) your can use SubGit, which cover (with [properly configured options](https://subgit.com/documentation/import-book.html)) even **extremely exotic** cases
> > with corresponding subdirectories as svn2git expect > > > I don't know about [`svn2git`](https://stackoverflow.com/questions/43843107/how-to-use-svn2git-on-repository) (never used it even once), but **[`git-svn`](https://git-scm.com/docs/git-svn)** itself is very flexible and accepts many sorts of weird nonstandard svn directory structures. With `git-svn`, you don't have to `svn mv` anything. You just have to call `git svn init` with properly configured options: > > > ``` > -T<trunk_subdir> > --trunk=<trunk_subdir> > -t<tags_subdir> > --tags=<tags_subdir> > -b<branches_subdir> > --branches=<branches_subdir> > -s > --stdlayout > > ``` > > After `git svn init` and before `git svn fetch`, you may review and fixup the trunk/branches/tags matching patterns in `.git/config`. There, you can remap svn paths using glob patterns, and you can also ignore svn paths by glob patterns. So if I understand correctly what you're trying to do, you'll have 2 git repos, `Project_1` and `Project_2`. To obtain `Project_1`, you'd do steps roughly along the lines: ``` SVNBASEURL=svn+ssh://user@subversion-server.example/top mkdir Project_1; cd Project_1 git init git svn init \ --trunk=trunk/Project_1 \ --branches='branches/*/Project_1' \ --tags='tags/*/Project_1' \ "$SVNBASEURL"/ # review/edit/fix/tune .git/config into shape git svn fetch ``` And similarly for `Project_2`. Good luck!
8,290,396
I have a text like: Sentence one. Sentence two. Sentence three. I want it to be: * Sentence one. * Sentence two. * Sentence three. I assume I can replace `'.'` with `'.' + char(10) + char(13)`, but how can I go about bullets? '•' character works fine if printed manually I just do not know how to bullet every sentence including the first.
2011/11/28
[ "https://Stackoverflow.com/questions/8290396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194076/" ]
``` -- Initial string declare @text varchar(100) set @text = 'Sentence one. Sentence two. Sentence three.' -- Setting up replacement text - new lines (assuming this works) and bullets ( char(149) ) declare @replacement varchar(100) set @replacement = '.' + char(10) + char(13) + char(149) -- Adding a bullet at the beginning and doing the replacement, but this will also add a trailing bullet declare @processedText varchar(100) set @processedText = char(149) + ' ' + replace(@text, '.', @replacement) -- Figure out length of substring to select in the next step declare @substringLength int set @substringLength = LEN(@processedText) - CHARINDEX(char(149), REVERSE(@processedText)) -- Removes trailing bullet select substring(@processedText, 0, @substringLength) ``` I've tested here - <https://data.stackexchange.com/stackoverflow/qt/119364/> I should point out that doing this in T-SQL doesn't seem correct. T-SQL is meant to process data; any presentation-specific work should be done in the code that calls this T-SQL (C# or whatever you're using).
select '• On '+ cast(getdate() as varchar)+' I discovered how to do this ' [Sample](https://i.stack.imgur.com/qx6hA.png)
3,691,061
what is wrong with this? I really don't understand some important parts for UIImagePickerController.... here's the source: ``` UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto; imagePickerController.delegate = self; [self presentModalViewController:imagePickerController animated:YES]; [imagePickerController release]; ``` Can't I open the photo library? Any help appreciated!
2010/09/11
[ "https://Stackoverflow.com/questions/3691061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232798/" ]
If you're using the photo library, do you need to set `cameraCaptureMode`?
I had this exact same exception, however I wasn't using an instance of UIImagePickerController control, instead I was showing a web page inside of a UIWebView that had an input w/ HTML Media Access attributes to enable camera access. The problem is that it seems the UIWebView does not handle the HTML Media Access attributes properly. I noticed that the spec on these attributes changed a few times over time, so while it seemed like valid html and works on safari on the device, it doesn't work on pages rendered using UIWebView. Bad: ``` <input type="file" accept="image/*" capture="camera" /> ``` Good: ``` <input type="file" accept="image/*;capture=camera" /> ``` The exception immediately went away and taking a picture works. This seems to be new to iOS 10 or 11 as it was existing code and didn't blow up in the past.
5,924,734
I am aware that a CALayer's shadowPath is only animatable using explicit animations, however I still cannot get this to work. I suspect that I am not passing the `toValue` properly - as I understand this has to be an `id`, yet the property takes a CGPathRef. Storing this in a `UIBezierPath` does not seem to work. I am using the following code to test: ``` CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:@"shadowPath"]; theAnimation.duration = 3.0; theAnimation.toValue = [UIBezierPath bezierPathWithRect:CGRectMake(-10.0, -10.0, 50.0, 50.0)]; [self.view.layer addAnimation:theAnimation forKey:@"animateShadowPath"]; ``` (I am using minus values so as to ensure the shadow extends beyond a view that lies on top of it... the layer's `masksToBounds` property is set to `NO`). How is animation of the shadowPath achieved? **UPDATE** Problem *nearly* solved. Unfortunately, the main problem was a somewhat careless error... The mistake I made was to add the animation to the root layer of the view controller, rather than the layer I had dedicated to the shadow. Also, @pe8ter was correct in that the `toValue` needs to be a `CGPathRef` cast to `id` (obviously when I had tried this before I still had no animation due to the wrong layer mistake). The animation works with the following code: ``` CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:@"shadowPath"]; theAnimation.duration = 3.0; theAnimation.toValue = (id)[UIBezierPath bezierPathWithRect:myRect].CGPath; [controller.shadowLayer addAnimation:theAnimation forKey:@"shadowPath"]; ``` I appreciate this was difficult to spot from the sample code I provided. Hopefully it can still be of use to people in a similar situation though. However, when I try and add the line ``` controller.shadowLayer.shadowPath = [UIBezierPath bezierPathWithRect:myRect].CGPath; ``` the animation stops working, and the shadow just jumps to the final position instantly. Docs say to add the animation with the same key as the property being changed so as to override the implicit animation created when setting the value of the property, however shadowPath can't generate implicit animations... so how do I get the new property to stay *after* the animation?
2011/05/07
[ "https://Stackoverflow.com/questions/5924734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/429427/" ]
``` let cornerRadious = 10.0 // let shadowPathFrom = UIBezierPath(roundedRect: rect1, cornerRadius: cornerRadious) let shadowPathTo = UIBezierPath(roundedRect: rect2, cornerRadius: cornerRadious) // layer.masksToBounds = false layer.shadowColor = UIColor.yellowColor().CGColor layer.shadowOpacity = 0.6 // let shadowAnimation = CABasicAnimation(keyPath: "shadowPath") shadowAnimation.fromValue = shadowPathFrom.CGPath shadowAnimation.toValue = shadowPathTo.CGPath shadowAnimation.duration = 0.4 shadowAnimation.autoreverses = true shadowAnimation.removedOnCompletion = true shadowAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) layer.addAnimation(shadowAnimation, forKey: "shadowAnimation") ```
Although not directly answer this question, if you just needs a view can drop shadow, you can use my class directly. ```swift /* Shadow.swift Copyright © 2018, 2020-2021 BB9z https://github.com/BB9z/iOS-Project-Template The MIT License https://opensource.org/licenses/MIT */ /** A view drops shadow. */ @IBDesignable class ShadowView: UIView { @IBInspectable var shadowOffset: CGPoint = CGPoint(x: 0, y: 8) { didSet { needsUpdateStyle = true } } @IBInspectable var shadowBlur: CGFloat = 10 { didSet { needsUpdateStyle = true } } @IBInspectable var shadowSpread: CGFloat = 0 { didSet { needsUpdateStyle = true } } /// Set nil can disable shadow @IBInspectable var shadowColor: UIColor? = UIColor.black.withAlphaComponent(0.3) { didSet { needsUpdateStyle = true } } @IBInspectable var cornerRadius: CGFloat { get { layer.cornerRadius } set { layer.cornerRadius = newValue } } private var needsUpdateStyle = false { didSet { guard needsUpdateStyle, !oldValue else { return } DispatchQueue.main.async { [self] in if needsUpdateStyle { updateLayerStyle() } } } } private func updateLayerStyle() { needsUpdateStyle = false if let color = shadowColor { Shadow(view: self, offset: shadowOffset, blur: shadowBlur, spread: shadowSpread, color: color, cornerRadius: cornerRadius) } else { layer.shadowColor = nil layer.shadowPath = nil layer.shadowOpacity = 0 } } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() updateLayerStyle() } override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) lastLayerSize = layer.bounds.size if shadowColor != nil, layer.shadowOpacity == 0 { updateLayerStyle() } } private var lastLayerSize = CGSize.zero { didSet { if oldValue == lastLayerSize { return } guard shadowColor != nil else { return } updateShadowPathWithAnimationFixes(bonuds: layer.bounds) } } // We needs some additional step to achieve smooth result when view resizing private func updateShadowPathWithAnimationFixes(bonuds: CGRect) { let rect = bonuds.insetBy(dx: shadowSpread, dy: shadowSpread) let newShadowPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath if let resizeAnimation = layer.animation(forKey: "bounds.size") { let key = #keyPath(CALayer.shadowPath) let shadowAnimation = CABasicAnimation(keyPath: key) shadowAnimation.duration = resizeAnimation.duration shadowAnimation.timingFunction = resizeAnimation.timingFunction shadowAnimation.fromValue = layer.shadowPath shadowAnimation.toValue = newShadowPath layer.add(shadowAnimation, forKey: key) } layer.shadowPath = newShadowPath } } /** Make shadow with the same effect as Sketch app. */ func Shadow(view: UIView?, offset: CGPoint, blur: CGFloat, spread: CGFloat, color: UIColor, cornerRadius: CGFloat = 0) { // swiftlint:disable:this identifier_name guard let layer = view?.layer else { return } layer.shadowColor = color.cgColor layer.shadowOffset = CGSize(width: offset.x, height: offset.y) layer.shadowRadius = blur layer.shadowOpacity = 1 layer.cornerRadius = cornerRadius let rect = layer.bounds.insetBy(dx: spread, dy: spread) layer.shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath } ``` via <https://github.com/BB9z/iOS-Project-Template/blob/master/App/General/Effect/Shadow.swift>
21,488,501
I came across too strange behaviour of pointer arithmetic. I am developing a program to develop SD card from LPC2148 using ARM GNU toolchain (on Linux). My SD card a sector contains data (in hex) like (checked from linux "xxd" command): fe 2a 01 34 21 45 aa 35 90 75 52 78 While printing individual byte, it is printing perfectly. ``` char *ch = buffer; /* char buffer[512]; */ for(i=0; i<12; i++) debug("%x ", *ch++); ``` Here debug function sending output on UART. However pointer arithmetic specially adding a number which is not multiple of 4 giving too strange results. uint32\_t \*p; // uint32\_t is typedef to unsigned long. ``` p = (uint32_t*)((char*)buffer + 0); debug("%x ", *p); // prints 34012afe // correct p = (uint32_t*)((char*)buffer + 4); debug("%x ", *p); // prints 35aa4521 // correct p = (uint32_t*)((char*)buffer + 2); debug("%x ", *p); // prints 0134fe2a // TOO STRANGE?? ``` Am I choosing any wrong compiler option? Pls help. I tried optimization options -0 and -s; but no change. I could think of little/big endian, but here i am getting unexpected data (of previous bytes) and no order reversing.
2014/01/31
[ "https://Stackoverflow.com/questions/21488501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3258584/" ]
Your CPU architecture must support unaligned load and store operations. To the best of my knowledge, it doesn't (and I've been using STM32, which is an ARM-based cortex). If you try to read a `uint32_t` value from an address which is not divisible by the size of `uint32_t` (i.e. not divisible by 4), then in the "good" case you will just get the wrong output. I'm not sure what's the address of your `buffer`, but at least one of the three `uint32_t` read attempts that you describe in your question, requires the processor to perform an unaligned load operation. On STM32, you would get a memory-access violation (resulting in a hard-fault exception). The data-sheet should provide a description of your processor's expected behavior. UPDATE: ------- Even if your processor **does** support unaligned load and store operations, you should try to avoid using them, as it might affect the overall running time (in comparison with "normal" load and store operations). So in either case, you should make sure that whenever you perform a memory access (read or write) operation of size N, the target address is divisible by N. For example: ``` uint08_t x = *(uint08_t*)y; // 'y' must point to a memory address divisible by 1 uint16_t x = *(uint16_t*)y; // 'y' must point to a memory address divisible by 2 uint32_t x = *(uint32_t*)y; // 'y' must point to a memory address divisible by 4 uint64_t x = *(uint64_t*)y; // 'y' must point to a memory address divisible by 8 ``` In order to ensure this with your data structures, always define them so that every field `x` is located at an offset which is divisible by `sizeof(x)`. For example: ``` struct { uint16_t a; // offset 0, divisible by sizeof(uint16_t), which is 2 uint08_t b; // offset 2, divisible by sizeof(uint08_t), which is 1 uint08_t a; // offset 3, divisible by sizeof(uint08_t), which is 1 uint32_t c; // offset 4, divisible by sizeof(uint32_t), which is 4 uint64_t d; // offset 8, divisible by sizeof(uint64_t), which is 8 } ``` Please note, that this **does not** guarantee that your data-structure is "safe", and you still have to make sure that every `myStruct_t*` variable that you are using, is pointing to a memory address divisible by the size of the largest field (in the example above, 8). SUMMARY: -------- There are two basic rules that you need to follow: 1. Every instance of your structure must be located at a memory address which is divisible by the size of the largest field in the structure. 2. Each field in your structure must be located at an offset (within the structure) which is divisible by the size of that field itself. Exceptions: 1. Rule #1 may be violated if the CPU architecture supports unaligned load and store operations. Nevertheless, such operations are usually less efficient (requiring the compiler to add NOPs "in between"). Ideally, one should strive to follow rule #1 **even if the compiler does support** unaligned operations, and let the compiler know that the data is well aligned (using a dedicated `#pragma`), in order to allow the compiler to use aligned operations where possible. 2. Rule #2 may be violated if the compiler automatically generates the required padding. This, of course, changes the size of each instance of the structure. It is advisable to always use explicit padding (instead of relying on the current compiler, which may be replaced at some later point in time).
`LDR` is the ARM instruction to load data. You have lied to the compiler that the pointer is a 32bit value. It is not aligned properly. You pay the price. Here is the `LDR` documentation, > > If the address is not word-aligned, the loaded value is rotated right by 8 times the value of bits [1:0]. > > > See: [**4.2.1. LDR and STR, words and unsigned bytes**](http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0068b/Bcfihdhj.html), especially the section **Address alignment for word transfers**. Basically your code is like, ``` p = (uint32_t*)((char*)buffer + 0); p = (p>>16)|(p<<16); debug("%x ", *p); // prints 0134fe2a ``` but has encoded to one instruction on the ARM. This behavior is dependent on the ARM CPU type and possibly co-processor values. It is also highly non-portable code.
29,803,253
Is it only me who have the problem with extracting coordinates of a polygon from `SpatialPolygonsDataFrame` object? I am able to extract other slots of the object (`ID`,`plotOrder`) but not coordinates (`coords`). I don't know what I am doing wrong. Please find below my R session where `bdryData` being the `SpatialPolygonsDataFrame` object with two polygons. ``` > bdryData An object of class "SpatialPolygonsDataFrame" Slot "data": ID GRIDCODE 0 1 0 1 2 0 Slot "polygons": [[1]] An object of class "Polygons" Slot "Polygons": [[1]] An object of class "Polygon" Slot "labpt": [1] 415499.1 432781.7 Slot "area": [1] 0.6846572 Slot "hole": [1] FALSE Slot "ringDir": [1] 1 Slot "coords": [,1] [,2] [1,] 415499.6 432781.2 [2,] 415498.4 432781.5 [3,] 415499.3 432782.4 [4,] 415499.6 432781.2 Slot "plotOrder": [1] 1 Slot "labpt": [1] 415499.1 432781.7 Slot "ID": [1] "0" Slot "area": [1] 0.6846572 [[2]] An object of class "Polygons" Slot "Polygons": [[1]] An object of class "Polygon" Slot "labpt": [1] 415587.3 432779.4 Slot "area": [1] 20712.98 Slot "hole": [1] FALSE Slot "ringDir": [1] 1 Slot "coords": [,1] [,2] [1,] 415499.6 432781.2 [2,] 415505.0 432781.8 [3,] 415506.5 432792.6 [4,] 415508.9 432792.8 [5,] 415515.0 432791.5 [6,] 415517.7 432795.6 [7,] 415528.6 432797.7 [8,] 415538.8 432804.2 [9,] 415543.2 432805.8 [10,] 415545.1 432803.6 [11,] 415547.1 432804.7 [12,] 415551.7 432805.8 [13,] 415557.5 432812.3 [14,] 415564.2 432817.1 [15,] 415568.5 432823.9 [16,] 415571.0 432826.8 [17,] 415573.2 432828.7 [18,] 415574.1 432829.7 [19,] 415576.2 432830.7 [20,] 415580.2 432833.8 [21,] 415589.6 432836.0 [22,] 415593.1 432841.0 [23,] 415592.2 432843.7 [24,] 415590.6 432846.6 [25,] 415589.0 432853.3 [26,] 415584.8 432855.3 [27,] 415579.7 432859.8 [28,] 415577.7 432866.2 [29,] 415575.6 432868.1 [30,] 415566.7 432880.7 [31,] 415562.7 432887.5 [32,] 415559.2 432889.1 [33,] 415561.5 432890.7 [34,] 415586.2 432889.7 [35,] 415587.1 432888.6 [36,] 415588.5 432890.2 [37,] 415598.2 432888.7 [38,] 415599.1 432887.7 [39,] 415601.2 432886.7 [40,] 415603.1 432885.7 [41,] 415605.2 432884.7 [42,] 415606.1 432882.7 [43,] 415607.2 432880.7 [44,] 415608.3 432878.3 [45,] 415612.2 432874.8 [46,] 415614.7 432871.9 [47,] 415617.1 432870.7 [48,] 415622.4 432868.2 [49,] 415622.0 432862.4 [50,] 415624.2 432855.4 [51,] 415633.2 432845.3 [52,] 415639.0 432841.1 [53,] 415642.8 432832.9 [54,] 415647.5 432828.7 [55,] 415654.3 432820.3 [56,] 415654.1 432816.5 [57,] 415658.2 432812.8 [58,] 415661.9 432808.6 [59,] 415663.5 432808.7 [60,] 415668.1 432803.5 [61,] 415676.5 432801.3 [62,] 415679.1 432802.7 [63,] 415680.1 432802.7 [64,] 415681.1 432802.7 [65,] 415682.2 432802.7 [66,] 415685.8 432804.7 [67,] 415691.8 432802.2 [68,] 415693.6 432798.9 [69,] 415696.2 432777.0 [70,] 415689.8 432773.5 [71,] 415683.7 432771.6 [72,] 415680.2 432766.7 [73,] 415679.0 432765.6 [74,] 415676.8 432753.7 [75,] 415671.4 432747.7 [76,] 415662.7 432747.2 [77,] 415658.7 432750.0 [78,] 415657.0 432746.3 [79,] 415654.1 432743.7 [80,] 415652.3 432739.8 [81,] 415649.6 432739.6 [82,] 415648.0 432739.7 [83,] 415641.9 432736.4 [84,] 415633.4 432736.9 [85,] 415630.2 432734.7 [86,] 415622.3 432733.6 [87,] 415614.4 432726.5 [88,] 415617.1 432719.1 [89,] 415612.5 432718.1 [90,] 415610.0 432720.9 [91,] 415606.2 432716.6 [92,] 415603.2 432713.9 [93,] 415601.4 432710.0 [94,] 415580.3 432708.7 [95,] 415545.1 432709.7 [96,] 415543.5 432711.5 [97,] 415534.0 432715.7 [98,] 415527.1 432713.7 [99,] 415521.1 432711.6 [100,] 415505.6 432710.6 [101,] 415501.3 432710.9 [102,] 415499.3 432708.7 [103,] 415495.6 432711.6 [104,] 415482.6 432726.2 [105,] 415477.2 432734.0 [106,] 415478.1 432737.7 [107,] 415479.2 432739.7 [108,] 415480.9 432743.4 [109,] 415486.5 432751.2 [110,] 415493.2 432760.7 [111,] 415494.1 432762.7 [112,] 415498.1 432767.9 [113,] 415497.2 432770.7 [114,] 415490.6 432773.2 [115,] 415493.2 432775.6 [116,] 415496.0 432778.7 [117,] 415499.2 432779.7 [118,] 415499.6 432781.2 Slot "plotOrder": [1] 1 Slot "labpt": [1] 415587.3 432779.4 Slot "ID": [1] "1" Slot "area": [1] 20712.98 Slot "plotOrder": [1] 2 1 Slot "bbox": min max x 415477.2 415696.2 y 432708.7 432890.7 Slot "proj4string": CRS arguments: +proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +datum=OSGB36 +units=m +no_defs +ellps=airy +towgs84=446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894 ``` Subsetting second polygon from `bdryData` ``` > bdryData@polygons[[2]] An object of class "Polygons" Slot "Polygons": [[1]] An object of class "Polygon" Slot "labpt": [1] 415587.3 432779.4 Slot "area": [1] 20712.98 Slot "hole": [1] FALSE Slot "ringDir": [1] 1 Slot "coords": [,1] [,2] [1,] 415499.6 432781.2 [2,] 415505.0 432781.8 [3,] 415506.5 432792.6 [4,] 415508.9 432792.8 [5,] 415515.0 432791.5 [6,] 415517.7 432795.6 [7,] 415528.6 432797.7 [8,] 415538.8 432804.2 [9,] 415543.2 432805.8 [10,] 415545.1 432803.6 [11,] 415547.1 432804.7 [12,] 415551.7 432805.8 [13,] 415557.5 432812.3 [14,] 415564.2 432817.1 [15,] 415568.5 432823.9 [16,] 415571.0 432826.8 [17,] 415573.2 432828.7 [18,] 415574.1 432829.7 [19,] 415576.2 432830.7 [20,] 415580.2 432833.8 [21,] 415589.6 432836.0 [22,] 415593.1 432841.0 [23,] 415592.2 432843.7 [24,] 415590.6 432846.6 [25,] 415589.0 432853.3 [26,] 415584.8 432855.3 [27,] 415579.7 432859.8 [28,] 415577.7 432866.2 [29,] 415575.6 432868.1 [30,] 415566.7 432880.7 [31,] 415562.7 432887.5 [32,] 415559.2 432889.1 [33,] 415561.5 432890.7 [34,] 415586.2 432889.7 [35,] 415587.1 432888.6 [36,] 415588.5 432890.2 [37,] 415598.2 432888.7 [38,] 415599.1 432887.7 [39,] 415601.2 432886.7 [40,] 415603.1 432885.7 [41,] 415605.2 432884.7 [42,] 415606.1 432882.7 [43,] 415607.2 432880.7 [44,] 415608.3 432878.3 [45,] 415612.2 432874.8 [46,] 415614.7 432871.9 [47,] 415617.1 432870.7 [48,] 415622.4 432868.2 [49,] 415622.0 432862.4 [50,] 415624.2 432855.4 [51,] 415633.2 432845.3 [52,] 415639.0 432841.1 [53,] 415642.8 432832.9 [54,] 415647.5 432828.7 [55,] 415654.3 432820.3 [56,] 415654.1 432816.5 [57,] 415658.2 432812.8 [58,] 415661.9 432808.6 [59,] 415663.5 432808.7 [60,] 415668.1 432803.5 [61,] 415676.5 432801.3 [62,] 415679.1 432802.7 [63,] 415680.1 432802.7 [64,] 415681.1 432802.7 [65,] 415682.2 432802.7 [66,] 415685.8 432804.7 [67,] 415691.8 432802.2 [68,] 415693.6 432798.9 [69,] 415696.2 432777.0 [70,] 415689.8 432773.5 [71,] 415683.7 432771.6 [72,] 415680.2 432766.7 [73,] 415679.0 432765.6 [74,] 415676.8 432753.7 [75,] 415671.4 432747.7 [76,] 415662.7 432747.2 [77,] 415658.7 432750.0 [78,] 415657.0 432746.3 [79,] 415654.1 432743.7 [80,] 415652.3 432739.8 [81,] 415649.6 432739.6 [82,] 415648.0 432739.7 [83,] 415641.9 432736.4 [84,] 415633.4 432736.9 [85,] 415630.2 432734.7 [86,] 415622.3 432733.6 [87,] 415614.4 432726.5 [88,] 415617.1 432719.1 [89,] 415612.5 432718.1 [90,] 415610.0 432720.9 [91,] 415606.2 432716.6 [92,] 415603.2 432713.9 [93,] 415601.4 432710.0 [94,] 415580.3 432708.7 [95,] 415545.1 432709.7 [96,] 415543.5 432711.5 [97,] 415534.0 432715.7 [98,] 415527.1 432713.7 [99,] 415521.1 432711.6 [100,] 415505.6 432710.6 [101,] 415501.3 432710.9 [102,] 415499.3 432708.7 [103,] 415495.6 432711.6 [104,] 415482.6 432726.2 [105,] 415477.2 432734.0 [106,] 415478.1 432737.7 [107,] 415479.2 432739.7 [108,] 415480.9 432743.4 [109,] 415486.5 432751.2 [110,] 415493.2 432760.7 [111,] 415494.1 432762.7 [112,] 415498.1 432767.9 [113,] 415497.2 432770.7 [114,] 415490.6 432773.2 [115,] 415493.2 432775.6 [116,] 415496.0 432778.7 [117,] 415499.2 432779.7 [118,] 415499.6 432781.2 Slot "plotOrder": [1] 1 Slot "labpt": [1] 415587.3 432779.4 Slot "ID": [1] "1" Slot "area": [1] 20712.98 ``` Extracting slots ``` > bdryData@polygons[[2]]@ID [1] "1" > bdryData@polygons[[2]]@plotOrder [1] 1 ``` But problem with coordinates ``` > bdryData@polygons[[2]]@coords Error: no slot of name "coords" for this object of class "Polygons" ``` Any help is really appreciated. Thanks.
2015/04/22
[ "https://Stackoverflow.com/questions/29803253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3420448/" ]
Finally, I figured out that I didn't parse the output correctly. The correct way to do is `bdryData@polygons[[2]]@Polygons[[1]]@coords`. Mind the difference in command `polygons`(`Polygons` and `polygons`) and it took me ages to find out.
The only valid answer on this posting was provided by the author "repres\_package" above. See that author's recommended solutions if you want to get the right answer. If you want to obtain the geometry of a polygon dataset, you are seeking the long and lat for every single vertex in the polygon feature class. The author's suggestion of using raster::geom() or ggplot2::fortify(), for example, will give you the total number of vertices that are contained in the spatialpolygonsdataframe. That's what you want. The other author's fail to do so. For example, in my spatialpolygonsdataframe of North Carolina counties (from US Census), I have a total of 1259547 vertices. By using raster::geom(NC\_counties), I am given a dataframe that contains a long and lat for each of those 1259547 vertices. I could also use gglot2::fortify(NC\_counties) to obtain coordinates for those 1259547 vertices. All of the valid options are given in the answer by "repres\_package". When I ran the recommended codes in the other answers on this posting, I obtained long and lat coordinates for only 672 vertices, 1041 vertices, or 1721 vertices, which is off by over one million vertices. I'm supposed to get long and lat coordiates for 1259547 vertices. I suspect that those codes are interpolating centroids for the polygons, which is not the geometry of the polygons.
35,258,180
I am using pjax with Yii2 and I have faced a problem with pjax. All scripts are working correctly and fine only the first time and after sending a pjax request and updating the table content, scripts and pjax not working. If I remove the line `$.pjax.reload({container:'#products-table'});` all scripts are working. And also I found this solution ( [Yii2 Pjax and ActiveForm beforeSubmit not working after reload?](https://stackoverflow.com/questions/29524980/yii2-pjax-and-activeform-beforesubmit-not-working-after-reload) ): " `$(document).on('ready pjax:success', function(){ // to do });` " and with it working fine BUT after adding more jquery code it stopped working again. Please if someone has the same issue please share with solution. Thanks! ``` $(document).on('ready pjax:success', function(){ $(".product-edit-submit").on('click', function(){ $.ajax({ type : "POST", url : editUrl, data: { id: this.id, productName: productName, productCost: productCost, _csrf: csfr }, success : function(response) { $.pjax.reload({container:'#products-table'}); }, error : function(response){ console.log(response); } }); return false; }); }); ``` VIEW : ====== ``` <?php Pjax::begin(['id' => 'products-table']); ?> <table class="table table-hover table-striped"> ....... </table> <?php Pjax::end(); ?> ```
2016/02/07
[ "https://Stackoverflow.com/questions/35258180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1134320/" ]
Just Change this line `$(".product-edit-submit").on('click', function(){` **to :** ``` $(document).on('click', '.product-edit-submit', function () { ``` Then It will work
if your code stops after adding extra libraries try registering it in view to make sure it will execute after all libraries included: ``` <?php $js = <<< 'JAVASCRIPT' $(document).on('ready pjax:success', function(){ $(".product-edit-submit").on('click', function(){ $.ajax({ type : "POST", url : editUrl, data: { id: this.id, productName: productName, productCost: productCost, _csrf: csfr }, success : function(response) { $.pjax.reload({container:'#products-table'}); }, error : function(response){ console.log(response); } }); return false; }); }); JAVASCRIPT; $this->registerJs($js,\yii\web\View::POS_READY); ```
9,063,344
What happens if the first file this code encounters is a dir. Why does it not ignore all other files in that dir (therefore obscuring the results)? This is taken from [How do I iterate through the files in a directory in Java?](https://stackoverflow.com/questions/3154488/best-way-to-iterate-through-a-directory-in-java) I'm not trying to dispute that this code works but how does it account for above scenario ? ``` public static void main(String... args) { File[] files = new File("C:/").listFiles(); showFiles(files); } public static void showFiles(File[] files) { for (File file : files) { if (file.isDirectory()) { System.out.println("Directory: " + file.getName()); showFiles(file.listFiles()); // Calls same method again. } else { System.out.println("File: " + file.getName()); } } } ```
2012/01/30
[ "https://Stackoverflow.com/questions/9063344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470184/" ]
When the first entry it encounters is a directory, it **recursively** calls `showFiles()` to work through the contents of that directory. When this call returns, the loop continues on with the entries from the first call to `showFiles()`.
It works because the variable `files` is a local variable, i.e. there is one instance for each invocation of the method `showFiles`. This way all method executions are independent from one another and do not clobber their `files` variables.
13,402,847
There is large python project where one attribute of one class just have wrong value in some place. It should be sqlalchemy.orm.attributes.InstrumentedAttribute, but when I run tests it is constant value, let's say string. There is some way to run python program in debug mode, and run some check (if variable changed type) after each step throught line of code automatically? P.S. I know how to log changes of attribute of class instance with help of inspect and property decorator. Possibly here I can use this method with metaclasses... But sometimes I need more general and powerfull solution... Thank you. P.P.S. I need something like there: <https://stackoverflow.com/a/7669165/816449>, but may be with more explanation of what is going on in that code.
2012/11/15
[ "https://Stackoverflow.com/questions/13402847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/816449/" ]
Well, here is a sort of *slow* approach. It can be modified for watching for local variable change (just by name). Here is how it works: we do sys.settrace and analyse the value of obj.attr each step. The tricky part is that we receive `'line'` events (that some line was executed) before line is executed. So, when we notice that obj.attr has changed, we are already on the next line and we can't get the previous line frame (because frames aren't copied for each line, they are modified ). So on each line event I save `traceback.format_stack` to `watcher.prev_st` and if on the next call of `trace_command` value has changed, we print the saved stack trace to file. Saving traceback on each line is quite an expensive operation, so you'd have to set `include` keyword to a list of your projects directories (or just the root of your project) in order not to watch how other libraries are doing their stuff and waste cpu. **watcher.py** ``` import traceback class Watcher(object): def __init__(self, obj=None, attr=None, log_file='log.txt', include=[], enabled=False): """ Debugger that watches for changes in object attributes obj - object to be watched attr - string, name of attribute log_file - string, where to write output include - list of strings, debug files only in these directories. Set it to path of your project otherwise it will take long time to run on big libraries import and usage. """ self.log_file=log_file with open(self.log_file, 'wb'): pass self.prev_st = None self.include = [incl.replace('\\','/') for incl in include] if obj: self.value = getattr(obj, attr) self.obj = obj self.attr = attr self.enabled = enabled # Important, must be last line on __init__. def __call__(self, *args, **kwargs): kwargs['enabled'] = True self.__init__(*args, **kwargs) def check_condition(self): tmp = getattr(self.obj, self.attr) result = tmp != self.value self.value = tmp return result def trace_command(self, frame, event, arg): if event!='line' or not self.enabled: return self.trace_command if self.check_condition(): if self.prev_st: with open(self.log_file, 'ab') as f: print >>f, "Value of",self.obj,".",self.attr,"changed!" print >>f,"###### Line:" print >>f,''.join(self.prev_st) if self.include: fname = frame.f_code.co_filename.replace('\\','/') to_include = False for incl in self.include: if fname.startswith(incl): to_include = True break if not to_include: return self.trace_command self.prev_st = traceback.format_stack(frame) return self.trace_command import sys watcher = Watcher() sys.settrace(watcher.trace_command) ``` **testwatcher.py** ``` from watcher import watcher import numpy as np import urllib2 class X(object): def __init__(self, foo): self.foo = foo class Y(object): def __init__(self, x): self.xoo = x def boom(self): self.xoo.foo = "xoo foo!" def main(): x = X(50) watcher(x, 'foo', log_file='log.txt', include =['C:/Users/j/PycharmProjects/hello']) x.foo = 500 x.goo = 300 y = Y(x) y.boom() arr = np.arange(0,100,0.1) arr = arr**2 for i in xrange(3): print 'a' x.foo = i for i in xrange(1): i = i+1 main() ```
A simpler way to watch for an object's attribute change (which can also be a module-level variable or anything accessible with `getattr`) would be to leverage [`hunter`](https://pypi.org/project/hunter/) library, *a flexible code tracing toolkit*. To detect state changes we need a predicate which can look like the following: ``` import traceback class MutationWatcher: def __init__(self, target, attrs): self.target = target self.state = {k: getattr(target, k) for k in attrs} def __call__(self, event): result = False for k, v in self.state.items(): current_value = getattr(self.target, k) if v != current_value: result = True self.state[k] = current_value print('Value of attribute {} has chaned from {!r} to {!r}'.format( k, v, current_value)) if result: traceback.print_stack(event.frame) return result ``` Then given a sample code: ``` class TargetThatChangesWeirdly: attr_name = 1 def some_nested_function_that_does_the_nasty_mutation(obj): obj.attr_name = 2 def some_public_api(obj): some_nested_function_that_does_the_nasty_mutation(obj) ``` We can instrument it with `hunter` like: ``` # or any other entry point that calls the public API of interest if __name__ == '__main__': obj = TargetThatChangesWeirdly() import hunter watcher = MutationWatcher(obj, ['attr_name']) hunter.trace(watcher, stdlib=False, action=hunter.CodePrinter) some_public_api(obj) ``` Running the module produces: ``` Value of attribute attr_name has chaned from 1 to 2 File "test.py", line 44, in <module> some_public_api(obj) File "test.py", line 10, in some_public_api some_nested_function_that_does_the_nasty_mutation(obj) File "test.py", line 6, in some_nested_function_that_does_the_nasty_mutation obj.attr_name = 2 test.py:6 return obj.attr_name = 2 ... return value: None ``` You can also use other `action`s that `hunter` supports. For instance, [`Debugger`](https://python-hunter.readthedocs.io/en/latest/reference.html#hunter.Debugger) which breaks into `pdb` (debugger on an attribute change).