{"text": "Q: How to modify non-configurable, non-writable properties in Javascript? I'm writing a simple EventEmitter is ES5.\nThe objective is to ensure that all properties on EventEmitter instances are\nnon-writable and non-configurable.\"\nAfter 6 hours of racking my brain I still can't figure out how to, increase the listenerCount, for example if the configurable descriptor is set to false.\nHere's an example of what I have:\nvar eventEmitter = function(){\n var listeners = listeners || 0;\n var events = events || {};\n\n Object.defineProperties(this, {\n listeners: {\n value : 0,\n configurable: false,\n writable: false\n },\n events: {\n value: {},\n configurable : false,\n writable: false\n }\n });\n return this;\n};\n\n\neventEmmitter.prototype.on = function(ev, cb) {\n if (typeof ev !== 'string') throw new TypeError(\"Event should be type string\", \"index.js\", 6);\n if (typeof cb !== 'function' || cb === null || cb === undefined) throw new TypeError(\"callback should be type function\", \"index.js\", 7);\n\n if (this.events[ev]){\n this.events[ev].push(cb);\n } else {\n this.events[ev] = [cb];\n }\n\n this.listeners ++;\n return this;\n};\n\n\nA: I would recommend the use of an IIFE (immediatly invoked function expression):\nvar coolObj=(function(){\nvar public={};\nvar nonpublic={};\nnonpublic.a=0;\npublic.getA=function(){nonpublic.a++;return nonpublic.a;};\n\nreturn public;\n})();\n\nNow you can do:\ncoolObj.getA();//1\ncoolObj.getA();//2\ncoolObj.a;//undefined\ncoolObj.nonpublic;//undefined\ncoolObj.nonpublic.a;//undefined\n\nI know this is not the answer youve expected, but i think its the easiest way of doing sth like that.\n\nA: You can use a proxy which requires a key in order to define properties:\n\n\nfunction createObject() {\r\n var key = {configurable: true};\r\n return [new Proxy({}, {\r\n defineProperty(target, prop, desc) {\r\n if (desc.value === key) {\r\n return Reflect.defineProperty(target, prop, key);\r\n }\r\n }\r\n }), key];\r\n}\r\nfunction func() {\r\n var [obj, key] = createObject();\r\n key.value = 0;\r\n Reflect.defineProperty(obj, \"value\", {value: key});\r\n key.value = function() {\r\n key.value = obj.value + 1;\r\n Reflect.defineProperty(obj, \"value\", {value: key});\r\n };\r\n Reflect.defineProperty(obj, \"increase\", {value: key});\r\n return obj;\r\n}\r\nvar obj = func();\r\nconsole.log(obj.value); // 0\r\ntry { obj.value = 123; } catch(err) {}\r\ntry { Object.defineProperty(obj, \"value\", {value: 123}); } catch(err) {}\r\nconsole.log(obj.value); // 0\r\nobj.increase();\r\nconsole.log(obj.value); // 1\n\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/41069927", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: Image hiding under button android Image view is hiding under the button what changes I can do so that the image view can be above the button view pager also have bottom padding so that button can properly accommodate. The image is showing on the other parts but not above the button.\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\nA: layout_constraintBottom_toBottomOf and other layout_constraint... won't work inside RelativeLayout, these are desired to work with ConstraintLayout as strict parent. if you want to align two Views next to/below/above inside RelativeLayoyut you have to use other attributes, e.g.\nandroid:layout_below=\"@+id/starFirst\"\nandroid:layout_above=\"@+id/starFirst\"\nandroid:layout_toRightOf=\"@id/starFirst\"\nandroid:layout_toLeftOf=\"@id/starFirst\"\n\nnote that every attr which starts with layout_ is desired to be read by strict parent, not by View which have such attrs set. every ViewGroup have own set of such\nedit: turned out that this is an elevation case/issue (Z axis), so useful attributes are\nandroid:translationZ=\"100dp\"\nandroid:elevation=\"100dp\"\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/70017985", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Handling multiple exceptions I have written a class which loads configuration objects of my application and keeps track of them so that I can easily write out changes or reload the whole configuration at once with a single method call. However, each configuration object might potentially throw an exception when doing IO, yet I do not want those errors to cancel the overall process in order to give the other objects still a chance to reload/write. Therefore I collect all exceptions which are thrown while iterating over the objects and store them in a super-exception, which is thrown after the loop, since each exception must still be handled and someone has to be notified of what exactly went wrong. However, that approach looks a bit odd to me. Someone out there with a cleaner solution? \nHere is some code of the mentioned class:\npublic synchronized void store() throws MultipleCauseException\n {\n MultipleCauseException me = new MultipleCauseException(\"unable to store some resources\");\n for(Resource resource : this.resources.values())\n {\n try\n {\n resource.store();\n }\n catch(StoreException e)\n {\n me.addCause(e);\n }\n }\n if(me.hasCauses())\n throw me;\n }\n\n\nA: If you want to keep the results of the operations, which it seems you do as you purposely carry on, then throwing an exception is the wrong thing to do. Generally you should aim not to disturb anything if you throw an exception.\nWhat I suggest is passing the exceptions, or data derived from them, to an error handling callback as you go along.\npublic interface StoreExceptionHandler {\n void handle(StoreException exc);\n}\n\npublic synchronized void store(StoreExceptionHandler excHandler) {\n for (Resource resource : this.resources.values()) {\n try {\n resource.store();\n } catch (StoreException exc) {\n excHandler.handle(exc);\n }\n }\n /* ... return normally ... */\n]\n\n\nA: There are guiding principles in designing what and when exceptions should be thrown, and the two relevant ones for this scenario are:\n\n\n*\n\n*Throw exceptions appropriate to the abstraction (i.e. the exception translation paradigm)\n\n*Throw exceptions early if possible\n\n\nThe way you translate StoreException to MultipleCauseException seems reasonable to me, although lumping different types of exception into one may not be the best idea. Unfortunately Java doesn't support generic Throwables, so perhaps the only alternative is to create a separate MultipleStoreException subclass instead.\nWith regards to throwing exceptions as early as possible (which you're NOT doing), I will say that it's okay to bend the rule in certain cases. I feel like the danger of delaying a throw is when exceptional situations nest into a chain reaction unnecessarily. Whenever possible, you want to avoid this and localize the exception to the smallest scope possible.\nIn your case, if it makes sense to conceptually think of storing of resources as multiple independent tasks, then it may be okay to \"batch process\" the exception the way you did. In other situations where the tasks has more complicated interdependency relationship, however, lumping it all together will make the task of analyzing the exceptions harder.\nIn a more abstract sense, in graph theory terms, I think it's okay to merge a node with multiple childless children into one. It's probably not okay to merge a whole big subtree, or even worse, a cyclic graph, into one node.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/2444580", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "8"}}
{"text": "Q: What is the meaning of Duration in Amazon RDS Backup window What does Duration specify?\nDoes it mean that the backup will start between 01:00 to 01:30 and keep running until it has completed? Or does it have a different meaning?\n\n\nA: The duration window indicates the time in which the backup will start. I can start anywhere between the time specified and could last longer than the window.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/58445170", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}}
{"text": "Q: Uncontrolled input of type text to be controlled warning I'm trying to create a multi step registration form using React and Redux.\nThe main component is as follows : \nimport React, {PropTypes} from 'react';\nimport {connect} from 'react-redux';\nimport {bindActionCreators} from 'redux';\nimport * as actionCreators from '../../actions/actionCreators';\nimport countries from '../../data/countries';\n\nimport RegistrationFormStepOne from './registrationFormStepOne';\nimport RegistrationFormStepTwo from './registrationFormStepTwo';\nimport RegistrationFormStepThree from './registrationFormStepThree';\nimport RegistrationFormStepFour from './registrationFormStepFour';\n\nclass RegistrationPage extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n user: Object.assign({}, this.props.userData),\n fileNames: {},\n selectedFile: {},\n icons: {\n idCard: 'upload',\n statuten: 'upload',\n blankLetterhead: 'upload',\n companyPhoto: 'upload'\n },\n step: 1,\n errors: {}\n };\n\n this.setUser = this.setUser.bind(this);\n this.onButtonClick = this.onButtonClick.bind(this);\n this.onButtonPreviousClick = this.onButtonPreviousClick.bind(this);\n this.changeCheckboxState = this.changeCheckboxState.bind(this);\n this.onFileChange = this.onFileChange.bind(this);\n this.routerWillLeave = this.routerWillLeave.bind(this);\n }\n\n componentDidMount() {\n this.context.router.setRouteLeaveHook(this.props.route, this.routerWillLeave);\n }\n\n routerWillLeave(nextLocation) {\n if (this.state.step > 1) {\n this.setState({step: this.state.step - 1});\n return false;\n }\n }\n\n getCountries(){\n return countries;\n }\n\n\n setUser(event) {\n const field = event.target.name;\n const value = event.target.value;\n\n let user = this.state.user;\n user[field] = value;\n this.setState({user: user});\n\n }\n\n validation(){\n const user = this.state.user;\n const languageReg = this.props.currentLanguage.default.registrationPage;\n let formIsValid = true;\n let errors = {};\n\n if(!user.companyName){\n formIsValid = false;\n errors.companyName = languageReg.companyNameEmpty;\n }\n\n if(!user.btwNumber){\n formIsValid = false;\n errors.btwNumber = languageReg.btwNumberEmpty;\n }\n\n if(!user.address){\n formIsValid = false;\n errors.address = languageReg.addressEmpty;\n }\n\n if(!user.country){\n formIsValid = false;\n errors.country = languageReg.countryEmpty;\n }\n\n if(!user.zipcode){\n formIsValid = false;\n errors.zipcode = languageReg.zipcodeEmpty;\n }\n\n if(!user.place){\n formIsValid = false;\n errors.place = languageReg.placeEmpty;\n }\n\n\n if(!user.firstName){\n formIsValid = false;\n errors.firstName = languageReg.firstnameEmpty;\n }\n\n\n\n this.setState({errors: errors});\n return formIsValid;\n }\n\n onFileChange(name, event) {\n event.preventDefault();\n let file = event.target.value;\n\n let filename = file.split('\\\\').pop(); //We get only the name of the file\n let filenameWithoutExtension = filename.replace(/\\.[^/.]+$/, \"\"); //We get the name of the file without extension\n\n let user = this.state.user;\n let fileNames = this.state.fileNames;\n let selectedFile = this.state.selectedFile;\n let icons = this.state.icons;\n\n switch (name.btnName) {\n case \"idCard\" :\n fileNames[name.btnName] = filenameWithoutExtension;\n //Check if file is selected\n if(file){\n selectedFile[name.btnName] = \"fileSelected\";\n user[\"idCardFile\"] = true;\n icons[\"idCard\"] = \"check\";\n }else{\n selectedFile[name.btnName] = \"\";\n user[\"idCardFile\"] = false;\n icons[\"idCard\"] = \"upload\";\n }\n break;\n case \"statuten\" :\n fileNames[name.btnName] = filenameWithoutExtension;\n\n //Check if file is selected\n if(file){\n selectedFile[name.btnName] = \"fileSelected\";\n user[\"statutenFile\"] = true;\n icons[\"statuten\"] = \"check\";\n }else{\n selectedFile[name.btnName] = \"\";\n user[\"statutenFile\"] = false;\n icons[\"statuten\"] = \"upload\";\n }\n break;\n case \"blankLetterhead\" :\n fileNames[name.btnName] = filenameWithoutExtension;\n\n //Check if file is selected\n if(file){\n selectedFile[name.btnName] = \"fileSelected\";\n user[\"blankLetterheadFile\"] = true;\n icons[\"blankLetterhead\"] = \"check\";\n }else{\n selectedFile[name.btnName] = \"\";\n user[\"blankLetterheadFile\"] = false;\n icons[\"blankLetterhead\"] = \"upload\";\n }\n break;\n default:\n fileNames[name.btnName] = filenameWithoutExtension;\n //Check if file is selected\n if(file){\n selectedFile[name.btnName] = \"fileSelected\";\n user[\"companyPhotoFile\"] = true;\n icons[\"companyPhoto\"] = \"check\";\n }else{\n selectedFile[name.btnName] = \"\";\n user[\"companyPhotoFile\"] = false;\n icons[\"companyPhoto\"] = \"upload\";\n }\n }\n\n this.setState({user: user, fileNames: fileNames, selectedFile: selectedFile, icons: icons});\n }\n\n changeCheckboxState(event) {\n let chcName = event.target.name;\n let user = this.state.user;\n\n switch (chcName) {\n case \"chcEmailNotificationsYes\":\n user[\"emailNotifications\"] = event.target.checked;\n break;\n case \"chcEmailNotificationsNo\":\n user[\"emailNotifications\"] = !event.target.checked;\n break;\n case \"chcTerms\":\n if(typeof this.state.user.terms === \"undefined\"){\n user[\"terms\"] = false;\n }else{\n user[\"terms\"] = !this.state.user.terms;\n }\n\n break;\n case \"chcSmsYes\":\n user[\"smsNotifications\"] = event.target.checked;\n break;\n default:\n user[\"smsNotifications\"] = !event.target.checked;\n }\n this.setState({user: user});\n this.props.actions.userRegistration(this.state.user);\n }\n\n onButtonClick(name, event) {\n event.preventDefault();\n this.props.actions.userRegistration(this.state.user);\n switch (name) {\n case \"stepFourConfirmation\":\n this.setState({step: 1});\n break;\n case \"stepTwoNext\":\n this.setState({step: 3});\n break;\n case \"stepThreeFinish\":\n this.setState({step: 4});\n break;\n default:\n if(this.validation()) {\n this.setState({step: 2});\n }\n }\n }\n\n\n onButtonPreviousClick(){\n this.setState({step: this.state.step - 1});\n }\n\n render() {\n const languageReg = this.props.currentLanguage.default.registrationPage;\n\n console.log(this.state.user);\n let formStep = '';\n let step = this.state.step;\n switch (step) {\n case 1:\n formStep = ();\n break;\n case 2:\n formStep = ();\n break;\n case 3:\n formStep = ();\n break;\n\n default:\n formStep = ();\n }\n\n return (\n
\n );\n }\n}\n\nRegistrationPage.contextTypes = {\n router: PropTypes.object\n};\n\nfunction mapStateToProps(state, ownProps) {\n return {\n userData: state.userRegistrationReducer\n };\n}\n\nfunction mapDispatchToProps(dispatch) {\n return {\n actions: bindActionCreators(actionCreators, dispatch)\n };\n}\n\nexport default connect(mapStateToProps, mapDispatchToProps)(RegistrationPage);\n\nThe first step component is as follows\n import React from 'react';\nimport Button from '../../common/formElements/button';\nimport RegistrationFormHeader from './registrationFormHeader';\nimport TextInput from '../../common/formElements/textInput';\nimport SelectInput from '../../common/formElements/selectInput';\n\nconst RegistrationFormStepOne = ({user, onChange, onButtonClick, errors, currentLanguage, countries}) => {\n\n const language = currentLanguage;\n\n return (\n
\n \n
\n );\n};\n\nexport default RegistrationFormStepOne;\n\nI try to add some simple validation and I've added validation function in my main component and then I check on button click if the returned value true or false is. If it's true, than I set step state to a appropriate value. And it works if I validate only the form fields of the first step, but when I try to also validate one or more form fields of the next step (now I'm trying to validate also the first field of the second step)\nif(!user.firstName){\n formIsValid = false;\n errors.firstName = languageReg.firstnameEmpty;\n }\n\nI get than \nWarning: TextInput is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.\nWithout the validation function works everything perfect.\nAny advice?\nEDIT\n import React, {propTypes} from 'react';\nimport _ from 'lodash';\n\nconst TextInput = ({errors, style, name, labelClass, label, className, placeholder, id, value, onChange, type}) => {\n let wrapperClass = \"form-group\";\n\n if (errors) {\n wrapperClass += \" \" + \"inputHasError\";\n }\n\n return (\n
\n \n \n
{errors}
\n
\n );\n};\n\nTextInput.propTypes = {\n name: React.PropTypes.string.isRequired,\n label: React.PropTypes.string,\n onChange: React.PropTypes.func.isRequired,\n type: React.PropTypes.string.isRequired,\n id: React.PropTypes.string,\n style: React.PropTypes.object,\n placeholder: React.PropTypes.string,\n className: React.PropTypes.string,\n labelClass: React.PropTypes.string,\n value: React.PropTypes.string,\n errors: React.PropTypes.string\n};\n\nexport default TextInput;\n\nThis is second step component : \nimport React from 'react';\nimport Button from '../../common/formElements/button';\nimport RegistrationFormHeader from './registrationFormHeader';\nimport TextInput from '../../common/formElements/textInput';\n\n\nconst RegistrationFormStepTwo = ({user, onChange, onButtonClick, onButtonPreviousClick, errors, currentLanguage}) => {\n const language = currentLanguage;\n\n return (\n
\n \n
\n\n );\n};\n\nexport default RegistrationFormStepTwo;\n\n\nA: This is why the warning exists: When the value is specified as undefined, React has no way of knowing if you intended to render a component with an empty value or if you intended for the component to be uncontrolled. It is a source of bugs. \nYou could do a null/undefined check, before passing the value to the input.\na source\n\nA: @Kokovin Vladislav is right. To put this in code, you can do this in all your input values:\n\n\nThat is, if you don't find the value of first name, then give it an empty value.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/38014397", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "6"}}
{"text": "Q: Interleaving the rows of two different SQL tables, group by one row My Sql query is like this\n$view = mysql_query (\"SELECT domain,count(distinct session_id) as \n views FROM `statistik` left join statistik_strippeddomains on \n statistik_strippeddomains.id = statistik.strippeddomain WHERE\n `angebote_id` = '\".(int)$_GET['id'].\"' and strippeddomain!=1 \n group by domain having count (distinct session_id) >\n \".(int)($film_daten['angebote_views']/100).\" order \n count(distinct session_id$vladd) desc limit 25\");\n\nHow can I write its Codeigniter Model I appreciate any Help\n\nA: try this\n$this->db->select('statistik.domain,statistik.count(DISTINCT(session_id)) as views');\n$this->db->from('statistik');\n$this->db->join('statistik_strippeddomains', 'statistik_strippeddomains.id = statistik.strippeddomain', 'left'); \n$this->db->where('angebote_id',$_GET['id']);\n$this->db->where('strippeddomain !=',1);\n$this->db->group_by('domain');\n$this->db->having('count > '.$film_daten['angebote_views']/100, NULL, FALSE);\n$this->db->order_by('count','desc');\n$this->db->limit('25');\n$query = $this->db->get();\n\nComment me If you have any query.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/39852573", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Query conditions to insert data from a form What I'm trying to do is: \nIf the age input in my form = 28, 30, 25 or 21 then I want to auto insert value 8 in the column (VE), else keep it empty. Is this the right way to do that?\nif($form_data->action == 'Insert')\n {\n\n $age=array(28, 30, 25, 21);\n $age_str=implode(\"','\", $age);\n\n if($form_data->age == $age_str){\n\n $query=\"INSERT INTO tbl\n (VE) VALUE ('8') WHERE id= '\".$form_data->id.\"'\n \";\n $statement = $connect->prepare($query);\n $statement->execute();\n }\n $data = array(\n ':date' => $date,\n ':first_name' => $first_name,\n ':last_name' => $last_name,\n ':age' => $age\n );\n $query = \"\n INSERT INTO tbl\n (date, first_name, last_name, age) VALUES \n (:date, :first_name, :last_name, :age)\n \";\n $statement = $connect->prepare($query);\n\n\n if($statement->execute($data))\n {\n $message = 'Data Inserted';\n }\n }\n\n\n\nAlso, how do I insert the new row with the row id from the other form data going into tbl?\n\nA: Use php's in_array instead of trying to compare a string. To get the id of the query where you insert the form data, you can return the id of the insert row from your prepared statement.\nif ($form_data->action == 'Insert') {\n\n // assuming $age, $date, $first_name, $last_name\n // already declared prior to this block\n $data = array(\n ':date' => $date,\n ':first_name' => $first_name,\n ':last_name' => $last_name,\n ':age' => $age\n );\n\n $query = \"\n INSERT INTO tbl\n (date, first_name, last_name, age) VALUES \n (:date, :first_name, :last_name, :age)\n \";\n $statement = $connect->prepare($query);\n\n if ($statement->execute($data)) {\n $message = 'Data Inserted';\n\n // $id is the last inserted id for (tbl)\n $id = $connect->lastInsertID();\n\n // NOW you can insert your child row in the other table\n $ages_to_insert = array(28, 30, 25, 21);\n\n // in_array uses your array...so you don't need\n // if($form_data->age == $age_str){\n\n if (in_array($form_data->age, $ages_to_insert)) {\n\n $query=\"UPDATE tbl SER VE = '8' WHERE id= '\".$id.\"'\";\n $statement2 = $connect->prepare($query);\n $statement2->execute();\n }\n }\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/58903757", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Is the function $\\ln(ax + b)$ increasing/decreasing, concave/convex? $h(x) = \\ln(ax + b)$ \nNB. Examine your results acccording to values of $(a,b)$\nI've differentiated twice in order to get the following:\n$$\nh''(x) = -\\frac{a^2}{(ax+b)^2}\n$$\nI think this proves that $h(x)$ is concave for all value of $a$ and $b$ since $h''(x)\\le0$. Is this correct?\nI don't know how to prove whether it's increasing/decreasing or what the NB really means so any help with that would be great.\n\nA: we now that the domain of the function is:\n$$ax+b\\gt 0\\Rightarrow x\\gt\\frac{-b}{a}\\text{so the domain is:}(\\frac{-b}{a},+\\infty)$$\n$$f'(x)=\\frac{a}{ax+b}$$\nin the domain of the function since we have $x\\gt\\frac{-b}{a}\\Rightarrow ax+b>0 $ the sign of $f'(x)=\\frac{a}{ax+b}$ will be dependent to the sign of $a$ so:\nif $a\\gt 0\\Rightarrow f'(x)\\gt 0$ and $f(x)$ will be increasing in its domain\nif $a\\lt 0\\Rightarrow f'(x)\\lt 0$ and $f(x)$ will be decreasing in its domain\nNote the phrases in its domain in the above expression, we always study the behaviors of functions in their domain\n$$f''(x)=\\frac{-a^2}{(ax+b)^2}$$\nas you said without we always have $f''(x)<0$ so without considering the sign of $a$, $f(x)$ will be a convex function\nThe value of $b$ doesnot influence the first and second derivation and so will not affect concavity, convexity, increase or decrease of the function \nhere is the diagram for $f(x)=\\ln(2x+1)$ as you see $a=2\\gt 0$ and $f(x)$ is increasing and convex\n \nhere is the diagram for $f(x)=\\ln(-2x+1)$ as you see $a=-2\\lt 0$ and $f(x)$ is decreasing and convex\n\n\nA: $$h^{ \\prime }\\left( x \\right) =\\frac { a }{ ax+b } >0$$\n$1$.if $a>0$ $ax+b>0$ $\\Rightarrow $ $ax>-b$ $\\Rightarrow $ $x>-\\frac { b }{ a } $ function is increasing\n$2$.if $a<0 $ $x<-\\frac { b }{ a } $ function is decreasing\nAnd about concavity you are right,find second derivative and check intervals\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/1400530", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Accessing array value is null Hello I have decoded a json string that I sent to my server and Im trying to get the values from him.\nMy problem is that I cant get the values from the inner arrays.\nThis is my code:\n\n\nWhen I get the answer from my $response I get this values:\n{\"exercise\":null,\"array\":[{\"exercise\":\"foo\",\"reps\":\"foo\"}]}\n\nWhy is $array['exercise'] null if I can see that is not null in the array\nThanks.\n\nA: Because of the [{...}] you are getting an array in an array when you decode your array key.\nSo:\n$exercise = $array['exercise'];\n\nShould be:\n$exercise = $array[0]['exercise'];\n\nSee the example here.\n\nA: From looking at the result of $response['array'], it looks like $array is actually this\n[['exercise' => 'foo', 'reps' => 'foo']]\n\nthat is, an associative array nested within a numeric one. You should probably do some value checking before blindly assigning values but in the interest of brevity...\n$exercise = $array[0]['exercise'];\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/21893968", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Composer update show this error: VirtualAlloc() failed: [0x00000008] Composer worked find yesterday, but today after I trying install:\ncomposer require --prefer-dist \"himiklab/yii2-recaptcha-widget\" \"*\"\nWhile run composer update command it show me error:\n\nVirtualAlloc() failed: [0x00000008] VirtualAlloc() failed:\n[0x00000008] PHP Fatal error: Out of memory (allocated 956301312)\n(tried to allocate 201326600 bytes) in\nphar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/DependencyResolver/RuleSet.php\non line 84\nFatal error: Out of memory (allocated 956301312) (tried to allocate\n201326600 bytes) in\nphar://C:/ProgramData/ComposerSetup/bin/composer.phar/src/Composer/DependencyResolver/RuleSet.php\non line 84\n\nI try update composer on my other projects, it is worked fine. After some researching I increased memory_limit: 4096M(also -1) in php.ini file. Then I tried to increase virtual memory in Computer->Properties, but still show error.\nI try to run next command:\ncomposer update -vvv --profile, result in attached image\nComposer error\nAny help would be greatly appreciated.\n\nA: You are probably using 32bit PHP. This version cannot allocate enough memory for composer even if you change the memory_limit to -1 (unlimited).\nPlease use 64 bit PHP with the Composer to get rid of these memory problems.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/49994946", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: How do I get the original values of in an Update SQL Trigger I'm not very familiar with triggers so thank you for your patience.\nI have a database table with four columns for user text input and just four date columns showing when the user text input was last changed. What I want the trigger to do is to compare the original and new values of the user text input columns and if they are different update the date column with getdate(). I don't know how to do this. The code I wrote can't get the pre-update value of the field so it can't be compared to the post-update value. Does anyone know how to do it?\n(Normally I would do this in a stored procedure. However this database table can also be directly edited by an Access database and we can't convert those changes to use the stored procedure. This only leaves us with using a trigger.)\n\nA: In sql server there are two special tables availble in the trigger called inserted and deleted. Same structure as the table on which the trigger is implemented. \ninserted has the new versions, deleted the old.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/10453001", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}}
{"text": "Q: Create Executable progeam of addition in C on linux I am new to Linux. Sorry I am asking very basic question. On windows I have Main.cpp file having code for addition of two number. In Visual studio gives me .exe. But how to do it on Linux. On my Linux machine have gcc compiler no IDE.\nWhat I write in Make file and how to run. \nMain.cpp has code like\n#include \n#include \n// Static library file included\n//#include \"Add.h\"\nint main()\n{\n int a,b,c;\n\n a = 10;\n b = 20;\n\n c= a+b;\n //Add function in static lib (.a in case of linux)\n //c= Add(a,b);\n printf(\"Addition is :%d\",c);\n\n\n return 0;\n}\n\nAfter that I want use Add function which is in Addition. How to use with above program removing commented in code?\n\nA: For c++ code, the command is usually something like:\ng++ Main.cpp -o FileNameToWriteTo\n\nAlternatively, if you just run\ng++ Main.cpp\n\nit will output to a default file called a.out.\nEither way, you can then run whichever file you created by doing:\n./FileNameToWriteTo.out\n\nSee this for more details: http://pages.cs.wisc.edu/~beechung/ref/gcc-intro.html\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/39793206", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-3"}}
{"text": "Q: QProgressBar updates as function progress How to initializa the operation of QProgressBar, I already declare her maximum, minimum, range and values.\nI want to assimilate the progress of QProgressBar with the \"sleep_for\" function.\nCurrent code:\nvoid MainPrograma::on_pushCorre_clicked()\n{\n QPlainTextEdit *printNaTela = ui->plainTextEdit;\n printNaTela->moveCursor(QTextCursor::End);\n printNaTela->insertPlainText(\"corrida iniciada\\n\");\n\n QProgressBar *progresso = ui->progressBar;\n progresso->setMaximum(100);\n progresso->setMinimum(0);\n progresso->setRange(0, 100);\n progresso->setValue(0);\n progresso->show();\n\n WORD wEndereco = 53606;\n WORD wValor = 01;\n WORD ifValor = 0;\n EscreveVariavel(wEndereco, wValor);\n\n\n//How to assimilate QProgressBar to this function:\nstd::this_thread::sleep_for(std::chrono::milliseconds(15000));\n//StackOverFlow help me please\n\n\n EscreveVariavel(wEndereco, ifValor);\n\n\nA: use a QTimer\nand in the slot update the value of the progressbar\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n t = new QTimer(this);\n t->setSingleShot(false);\n c = 0;\n connect(t, &QTimer::timeout, [this]()\n { c++;\n if (c==100) {\n c=0;\n }\n qDebug() << \"T...\";\n ui->progressBar->setValue(c);\n });\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::on_pushButton_clicked()\n{\n t->start(100);\n}\n\n\nA: I'm not sure about your intentions with such sleep: are you simulating long wait? do you have feedback about progress during such process? Is it a blocking task (as in the example) or it will be asynchronous?\nAs a direct answer (fixed waiting time, blocking) I think it is enough to make a loop with smaller sleeps, like:\nEscreveVariavel(wEndereco, wValor);\nfor (int ii = 0; ii < 100; ++ii) {\n progresso->setValue(ii);\n qApp->processEvents(); // necessary to update the UI\n std::this_thread::sleep_for(std::chrono::milliseconds(150));\n}\nEscreveVariavel(wEndereco, ifValor);\n\nNote that you may end waiting a bit more time due to thread scheduling and UI refresh.\nFor an async task you should pass the progress bar to be updated, or some kind of callback that does such update. Keep in mind that UI can only be refreshed from main thread.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/64987457", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Preallocation and Vectorization Speedup I am trying to improve the speed of script I am trying to run.\nHere is the code: (my machine = 4 core win 7)\nclear y;\nn=100;\nx=linspace(0,1,n);\n% no y pre-allocation using zeros\nstart_time=tic;\n\nfor k=1:n,\n y(k) = (1-(3/5)*x(k)+(3/20)*x(k)^2 -(x(k)^3/60)) / (1+(2/5)*x(k)-(1/20)*x(k)^2);\nend\n\nelapsed_time1 = toc(start_time);\nfprintf('Computational time for serialized solution: %f\\n',elapsed_time1);\n\nAbove code gives 0.013654 elapsed time.\nOn the other hand, I was tried to use pre-allocation by adding y = zeros(1,n); in the above code where the comment is but the running time is similar around ~0.01. Any ideas why? I was told it would improve by a factor of 2. Am I missing something?\nLastly is there any type of vectorization in Matlab that will allow me to forget about the for loop in the above code?\nThanks,\n\nA: In your code: try with n=10000 and you'll see more of a difference (a factor of almost 10 on my machine).\nThese things related with allocation are most noticeable when the size of your variable is large. In that case it's more difficult for Matlab to dynamically allocate memory for that variable.\n\nTo reduce the number of operations: do it vectorized, and reuse intermediate results to avoid powers:\ny = (1 + x.*(-3/5 + x.*(3/20 - x/60))) ./ (1 + x.*(2/5 - x/20));\n\nBenchmarking:\nWith n=100:\nParag's / venergiac's solution:\n>> tic\nfor count = 1:100\ny=(1-(3/5)*x+(3/20)*x.^2 -(x.^3/60))./(1+(2/5)*x-(1/20)*x.^2);\nend\ntoc\nElapsed time is 0.010769 seconds.\n\nMy solution:\n>> tic\nfor count = 1:100\ny = (1 + x.*(-3/5 + x.*(3/20 - x/60))) ./ (1 + x.*(2/5 - x/20));\nend\ntoc\nElapsed time is 0.006186 seconds.\n\n\nA: You don't need a for loop. Replace the for loop with the following and MATLAB will handle it.\ny=(1-(3/5)*x+(3/20)*x.^2 -(x.^3/60))./(1+(2/5)*x-(1/20)*x.^2);\n\nThis may give a computational advantage when vectors become larger in size. Smaller size is the reason why you cannot see the effect of pre-allocation. Read this page for additional tips on how to improve the performance.\nEdit: I observed that at larger sizes, n>=10^6, I am getting a constant performance improvement when I try the following:\nx=0:1/n:1;\n\ninstead of using linspace. At n=10^7, I gain 0.05 seconds (0.03 vs 0.08) by NOT using linspace. \n\nA: try operation element per element (.*, .^)\nclear y;\nn=50000;\nx=linspace(0,1,n);\n% no y pre-allocation using zeros\nstart_time=tic;\n\nfor k=1:n,\n y(k) = (1-(3/5)*x(k)+(3/20)*x(k)^2 -(x(k)^3/60)) / (1+(2/5)*x(k)-(1/20)*x(k)^2);\nend\n\nelapsed_time1 = toc(start_time);\nfprintf('Computational time for serialized solution: %f\\n',elapsed_time1);\n\nstart_time=tic;\ny = (1-(3/5)*x+(3/20)*x.^2 -(x.^3/60)) / (1+(2/5)*x-(1/20)*x.^2);\n\nelapsed_time1 = toc(start_time);\nfprintf('Computational time for product solution: %f\\n',elapsed_time1);\n\nmy data\n\nComputational time for serialized solution: 2.578290\nComputational time for serialized solution: 0.010060\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/21564052", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: Scala and Akka HTTP: Request inside a request & issue with threads I am new to learning Scala, Akka Streams and Akka HTTP, so apologies beforehand if the question is too basic.\nI want to do an HTTP request inside an HTTP request, just like in the following piece of code:\n implicit val system = ActorSystem(\"ActorSystem\")\n implicit val materializer = ActorMaterializer\n import system.dispatcher\n\n val requestHandler: Flow[HttpRequest, HttpResponse, _] = Flow[HttpRequest].map {\n case HttpRequest(HttpMethods.GET, Uri.Path(\"/api\"), _, _, _) =>\n val responseFuture = Http().singleRequest(HttpRequest(uri = \"http://www.google.com\"))\n responseFuture.onComplete {\n case Success(response) =>\n response.discardEntityBytes()\n println(s\"The request was successful\")\n case Failure(ex) =>\n println(s\"The request failed with: $ex\")\n }\n //Await.result(responseFuture, 10 seconds)\n println(\"Reached HttpResponse\")\n HttpResponse(\n StatusCodes.OK\n )\n }\n\n Http().bindAndHandle(requestHandler, \"localhost\", 8080) \n\nBut in the above case the result looks like this, meaning that Reached HttpResponse is reached first before completing the request:\nReached HttpResponse\nThe request was successful\n\nI tried using Await.result(responseFuture, 10 seconds) (currently commented out) but it made no difference.\nWhat am I missing here? Any help will be greatly appreciated!\nMany thanks in advance!\n\nA: map is a function that takes request and produces a response:\nHttpRequest => HttpResponse\n\nThe challenge is that response is a type of Future. Therefore, you need a function that deals with it. The function that takes HttpRequest and returns Future of HttpResponse.\nHttpRequest => Future[HttpResponse]\n\nAnd voila, mapAsync is exactly what you need:\nval requestHandler: Flow[HttpRequest, HttpResponse, _] = Flow[HttpRequest].mapAsync(2) {\n case HttpRequest(HttpMethods.GET, Uri.Path(\"/api\"), _, _, _) =>\n Http().singleRequest(HttpRequest(uri = \"http://www.google.com\")).map (resp => {\n resp.discardEntityBytes()\n println(s\"The request was successful\")\n HttpResponse(StatusCodes.OK)\n })\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/61038711", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "5"}}
{"text": "Q: Initial Boundary Value Problem for a Wave Equation $u_{tt}=4u_{xx}$ Solve the initial boundary value problem:\n\\begin{equation} \\begin{aligned} \nu_{tt} &= 4u_{xx} \\quad x > 0, \\, t > 0 \\\\\nu(x, 0) &= x^2/8, \\\\ \nu_t(x, 0) &= x \\quad x \u2265 0 \\\\\nu(0,t) &= t^2, \\quad t \u2265 0.\\end{aligned} \\end{equation}\nThis question is from here. Seeing that that question is not active, how would we approach this?\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/4581378", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Dealing with four digits: memcache sorts 1000 before 150 from least to greatest In app engine I retrieve a list of items stored in memcache:\nitems = memcache.get(\"ITEMS\")\n\nand sort them by amount and price:\nitems.sort(key = lambda x:(x.price, x.amount))\n\nWhich works most of the time, when the amount is three digits. However, when I have 2 items with 150 and 1000 amounts for the same price, the entry with 1000 goes before other one. How can I fix this?\n\nA: fixed it: \nitems.sort(key = lambda x:((float)(x.price), (int)(x.amount)))\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/21960862", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Do codigniter 3.1.7 support hmvc? I tried but no luck From the very first answer of this \nHow to implement HMVC in codeigniter 3.0? I tried all steps with codigniter 3.7.1 but no luck. I am still getting 404.\n$config['modules_locations'] = array(\n APPPATH.'modules/' => '../modules/',\n);\n\nThen I tried putting the above code in application/config/config.php but still 404\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/48606954", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Saving time - Compiling c++ and plotting at the same time gnuplot Hi in order to save time whene I execute the code I command this line :\ng++ name.cpp && ./a.out \n\nwhere nome,cpp is the name of the file that contains the code. If I succesively I need to plot some data generated by the exucatable with Gnuplot there is a way to add in the previous line instead of writing:\ngnuplot\nplot \"name2.dat\" \n\n?\n\nA: you can:\ng++ name.cpp && ./a.out && gnuplot -e \"plot 'name2.dat'; pause -1\"\n\ngnuplot exits when you hit return (see help pause for more options)\nif you want to start an interactive gnuplot session there is a dirty way I implemented.\ng++ name.cpp && ./a.out && gnuplot -e \"plot 'name2.dat' -\n\n(pay attention to the final minus sign)\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/50157509", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}}
{"text": "Q: How to put a Hyphen in column Total Cost Value in power bi I have a table with blank value, but i want a hyphen \"-\" to appear when the value is null.\nUsing an expression similar to this:\nvar VLGROUP =\n(Expression\u2026\u2026\nRETURN\nIF(\nISBLANK(VLGROUP),\nBLANK(),\nVLGROUP)\nSomeone know if is possible?\nThanks!!\nenter image description here\ngur.com/C0u8s.png\n\n\n\nA: Try this below option-\nSales for the Group = \n\nvar sales =\n CALCULATE( \n SUM(Financialcostcenter[amount]), \n Financialcostcenter[partnercompany]= \"BRE\", \n Financialcostcenter[2 digits]=71, \n DATESYTD('Datas'[Date])\n ) \n + \n CALCULATE( \n SUM(Financialcostcenter[amount]), \n Financialcostcenter[partnercompany]= \"GRM\", \n Financialcostcenter[2 digits]=71, \n DATESYTD('Datas'[Date])\n ) \n\n\nRETURN IF(sales = BLANK(),\"-\", -(sales))\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/63953889", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Part time job at the vegetable/fruits shop. You recently applied for a job at the vegetable/fruits store and the shop owner called you for a small quiz.so you went there and everything was going apparently well\u2026 but then he asked you that since his favourite number is 10 and his favourite fruit is orange so he wants to make a pyramid of oranges where the triangle on the base is an equilateral triangle made having 10 oranges on each side, then the total number of oranges in the complete pyramid will be??\nNote-this is a homework question from sequences and series and not something I picked from a puzzle book\u2026 I tried solving it but I am not able to visualise it properly so I am not able to get the correct answer.\n\nA: Triangle on base will have (1 + 2 + 3 + 4+ ... +10)\nNext one will have as above but only to 9 - and so on until you only have 1 at the top\nI have deliberately not done the entire calculation for you - if you are still confused after this attempt to help you visualize it, add a comment and I will clarify more\n\nA: Here is how I visualise it. Triangle on base will have ( 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 ) oranges and the next one will have ( 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 ). \nSo the total amount will be : 10*1 + 9*2 + 8*3 + 7*4 + 6*5 + 5*6 + 4*7 + 3*8 + 2*9 + 1*10\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/1509492", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}}
{"text": "Q: Constraints on an embedded subclass - Grails, GORM, Mongo I've been pulling my hair out with this issue for a couple of days.\nI have an embedded subclass with several specified constraints. My issue is that these constraints are never enforced,\nI'm using grails 2.3.11 and the mongodb plugin 3.0.2.\nHere is my setup (Simplified slightly).\nMedia class\nclass Media{\nObjectId id;\nString name;\nFilm film;\n\nstatic mapWith = \"mongo\"\nstatic embedded = [\"film\"]\n}\n\nFilm Class \nclass Film{\nObjectId id;\nString name;\n\nstatic mapWith = \"mongo\"\nstatic belongsTo = [media : Media]\nstatic mapping = {\n lazy:false\n}\nstatic constraints = {\nname(nullable:false) //works as expected. Save fails if name is set to null\n}\n}\n\nActionFilm Class\nclass ActionFilm extends Film{\nint score;\nString director;\n\n//These constraints are never enforeced. No matter what value I set the fields to the save is always successful\nstatic constraints = {\nscore(min:50) \ndirector(nullable:true)\n}\n}\n\nIs this an issue with Mongo and Gorm? Is it possible to have contraints in bth a parent and subclass? \nExample code when saving\npublic boolean saveMedia(){\nActionFilm film = new ActionFilm()\nfilm.setName(\"TRON\");\nfilm.setScore(2)\nfilm.setDirector(\"Ted\")\n\nMedia media = new Media()\nmedia.setName(\"myMedia\")\nmedia.setFilm(film)\nmedia.save(flush:true, failOnError:false) //Saves successfully when it shouldn't as the score is below the minimum constrains\n\n}\nEdit\nI've played aroubd some more and the issue only persits when I'm saving the Media object with ActionFilm as an embedded object. If I save the ActionFilm object the validation is applied.\n ActionFilm film = new ActionFilm()\n film.setName(\"TRON\");\n film.setScore(2)\n film.setDirector(\"Ted\")\n film.save(flush:true, failOnError:false) //Doesn't save as the diameter is wrong. Expected behaviour.\n\nSo the constraints are applied as expected when I save the ActionFilm object but aren't applied if its an embedded object. \n\nA: I've solved my issue in case anyone else comes across this. It may not be the optimal solution but I haven't found an alternative.\nI've added a custom validator to the Media class that calls validate() on the embedded Film class and adds any errors that arise to the Media objects errors\nclass Media{\nObjectId id;\nString name;\nFilm film;\n\nstatic mapWith = \"mongo\"\nstatic embedded = [\"film\"]\n\n static constraints = {\n film(validator : {Film film, def obj, def errors ->\n boolean valid = film.validate()\n if(!valid){\n film.errors.allErrors.each {FieldError error ->\n final String field = \"film\"\n final String code = \"$error.code\"\n errors.rejectValue(field,code,error.arguments,error.defaultMessage )\n }\n }\n return valid\n }\n )\n }\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/26994126", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: MySQL -> PHP Array -> Json need output in array plus object format i am trying to fetch data from MySQL and show it in JSON format\nThis is the partial PHP code\n$sql = \"SELECT item, cost, veg, spicy_level FROM food1\";\n$result = $conn->query($sql);\n\n while($row = $result->fetch_assoc()) {\n\n echo json_encode($row),\" \";}\n\n?>\ni am getting output as \n{\"item\":\"dosa\",\"cost\":\"20\",\"veg\":\"0\",\"spicy_level\":\"1\"}\n{\"item\":\"idli\",\"cost\":\"20\",\"veg\":\"0\",\"spicy_level\":\"2\"}\n\nbut i need it as\nfood1:[\n{\"item\":\"dosa\",\"cost\":\"20\",\"veg\":\"0\",\"spicy_level\":\"1\"},\n{\"item\":\"idli\",\"cost\":\"20\",\"veg\":\"0\",\"spicy_level\":\"2\"}\n]\n\ncan anyone please guide me?\ni think what i am getting is in object format and i need output in array format i.e. with [ & ].\nvery new to this json and php.\n\nA: You can incapsulate query results in array and after print it;\n$sql = \"SELECT item, cost, veg, spicy_level FROM food1\";\n$result = $conn->query($sql);\n$a = array();\nwhile($row = $result->fetch_assoc()) {\n if($a['food1'] ==null)\n $a['food1'] = array():\n array_push($a['food1'],$row);}\n\n\n echo json_encode($a);\n?>\n\n\nA: Your code should be :\n$sql = \"SELECT item, cost, veg, spicy_level FROM food1\";\n$result = $conn->query($sql);\n\n$food['food1'] = array();\n\nwhile($row = $result->fetch_assoc()) {\n $food['food1'][] = $row; \n}\n\necho json_encode($food);\n\n\nA: Don't call json_encode each time through the loop. Put all the rows into an array, and then encode that.\n$food = array();\nwhile ($row = $result->fetch_assoc()) {\n $food[] = $row;\n}\necho json_encode(array('food1' => $food));\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/28872111", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Find a relation between a,b and c $ a,b,c\\in \\Bbb R$\n$2x_1+2x_2+3x_3=a$\n$3x_1-x_2+5x_3=b$\n$x_1-3x_2+2x_3=c$\nif a,b and c is a solution of this linear equation system find the relation between a,b and c\nI dont understand the question. without knowing a,b and c is a solution of eq.syst. I found\n$$\n \\begin{matrix}\n 2 & 2 & 3 &a \\\\\n 3 & -1 & 5&b \\\\\n 0 & 0 & 0 &a+c-b\\\\\n \\end{matrix}\n$$\nand therefore $b=a+c$\nwhen I use a,b and c as a solution\n$2a+2b+3c=a$\n$3a-b+5c=b$\n$a-3b+2c=c$\nreduced row echolon form is \n$$\n \\begin{matrix}\n 1 & 0 & 0 \\\\\n 0 & 1 & 0 \\\\\n 0 & 0 & 1 \\\\\n \\end{matrix}\n$$\nit gives a=0 b=0 c=0\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/1410531", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Firebase hosting randomly shows \"Site Not Found\" at custom domain We recently launched our firebase application at https://tnb-widgets.firebaseapp.com/ and https://thenextbid.com/ (the last one being our custom domain). It all works smoothly except for some seemingly random moments in which it shows a page stating \"Site Not Found\". This already happened multiple times and after a couple of minutes the site seems to be back again.\nThe last time this happened was at 2:37AM GMT-5 and the last time I deployed a new release to this same firebase hosting project was at 3:45PM the day before. This release also contained 80 files in total, so it cannot possibly be \"an empty directory\".\nOur firebase.json file looks like this:\n{\n \"firestore\": {\n \"rules\": \"firestore.rules\",\n \"indexes\": \"firestore.indexes.json\"\n },\n \"hosting\": {\n \"public\": \"build\",\n \"ignore\": [\n \"firebase.json\",\n \"**/.*\",\n \"**/node_modules/**\"\n ],\n \"rewrites\": [\n {\n \"source\": \"/api/**\",\n \"function\": \"app\"\n },\n {\n \"source\": \"**\",\n \"destination\": \"/index.html\"\n }\n ]\n },\n \"storage\": {\n \"rules\": \"storage.rules\"\n }\n}\n\nThere's no service workers registered. The \"build\" folder contains 80 files and most importantly it contains the \"index.html\" at its root.\nDoes anyone have similar issues? I would appreciate any idea to solve this! Thanks.\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/52877497", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}}
{"text": "Q: Reduce Time for Checking Out Code in Visual Studio Online I'm trying out VSO and it's taking over 2 minutes to sync with a GitHub repository. It appears that it's checking out the whole thing on every build. I made sure that the \"clean\" box is unchecked but it had no effect. \nAny ideas on how to get it to cache the source or is this even possible in VSO?\n\nA: Each build in VSO uses a new VM that is spun up just for your build. Short \nof hosting your own Build Server connected your VSO, I don't think it can be avoided.\nUnless there are ways to speed up a the process of downloading the code from a git repo, I think you're stuck.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/31390786", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-2"}}
{"text": "Q: How to skip a line when reading from a file I am reading stuff from a file and this is the format : c stands for circle and the double is the radius, r for rectangle and the double is width and height respectively and t for triangle and the double represents side length:\nc 12\nc 2\nr 3 4\nc 2.4\nt 2.9\n3 c // wrong format \nt 2.9\n10 r // wrong format \n\nI run this code:\nifstream infile(names);\nwhile(infile >> names) {\n if(names.at(0) == 'c') { \n double r; \n infile >> r;\n cout << \"radius = \" << r << endl;\n } else if(names.at(0) == 'r') { \n double w; \n double h; \n infile >> w;\n infile >> h;\n cout << \"width = \" << w << \", height = \" << h << endl;\n } else if(names.at(0) == 't') { \n double s; \n infile >> s;\n cout << \"side = \" << s << endl;\n } else {\n continue;\n }\n}\n\ninfile.close()\n\nAnd this is the output: \nradius = 12\nradius = 2\nwidth = 3, height = 4\nradius = 2.4\nside = 2.9\nradius = 0\n\nI was wondering how I can skip the wrong format line. I have tried using geline but still no luck\nEDIT: radius, height, width and side have to be > 0\n\nA: The biggest potential problems you are running up against is the fact that you assume a line is valid if it begins with a c, t or r without first validating the remainder of the line matches the format for a circle, triangle or rectangle. While not fatal to this data set, what happens if one of the lines was 'cat' or 'turtle'?\nBy failing to validate all parts of the line fit the \"mold\" so to speak, you risk attempting to output values of r, h & w or s that were not read from the file. A simple conditional check of the read to catch the potential failbit or badbit will let you validate you have read what you think you read.\nThe remainder is basically semantics of whether you use the niceties of C++ like a vector of struct for rectangles and whether you use a string instead of char*, etc. However, there are certain benefits of using a string to read/validate the remainder of each line (or you could check the stream state and use .clear() and .ignore())\nPutting those pieces together, you can do something like the following. Note, there are many, many different approaches you can take, this is just one approach,\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\ntypedef struct { /* simple typedef for vect of rectangles */\n int width, height;\n} rect_t;\n\nint main (int argc, char **argv) {\n\n vector cir; /* vector of double for circle radius */\n vector tri; /* vector of double for triangle side */\n vector rect; /* vector of rect_t for rectangles */\n string line; /* string to use a line buffer */\n\n if (argc < 2) { /* validate at least one argument given */\n cerr << \"error: insufficient input.\\n\"\n \"usage: \" << argv[0] << \" filename\\n\";\n return 1;\n }\n\n ifstream f (argv[1]); /* open file given by first argument */\n if (!f.is_open()) { /* validate file open for reading */\n cerr << \"error: file open failed '\" << argv[1] << \"'.\\n\";\n return 1;\n }\n\n while (getline (f, line)) { /* read each line into 'line' */\n string shape; /* string for shape */\n istringstream s (line); /* stringstream to parse line */\n if (s >> shape) { /* if shape read */\n if (shape == \"c\") { /* is it a \"c\"? */\n double r; /* radius */\n string rest; /* string to read rest of line */\n if (s >> r && !getline (s, rest)) /* radius & nothing else */\n cir.push_back(r); /* add radius to cir vector */\n else /* invalid line for circle, handle error */\n cerr << \"error: invalid radius or unexpected chars.\\n\";\n }\n else if (shape == \"t\") {\n double l; /* side length */\n string rest; /* string to read rest of line */\n if (s >> l && !getline (s, rest)) /* length & nothing else */\n tri.push_back(l); /* add length to tri vector */\n else /* invalid line for triangle, handle error */\n cerr << \"error: invalid triangle or unexpected chars.\\n\";\n }\n else if (shape == \"r\") { /* is it a rect? */\n rect_t tmp; /* tmp rect_t */\n if (s >> tmp.width && s >> tmp.height) /* tmp & nohtin else */\n rect.push_back(tmp); /* add to rect vector */\n else /* invalid line for rect, handle error */\n cerr << \"error: invalid width & height.\\n\";\n }\n else /* line neither cir or rect, handle error */\n cerr << \"error: unrecognized shape '\" << shape << \"'.\\n\";\n }\n }\n\n cout << \"\\nthe circles are:\\n\"; /* output valid circles */\n for (auto& i : cir)\n cout << \" c: \" << i << \"\\n\";\n\n cout << \"\\nthe triangles are:\\n\"; /* output valid triangles */\n for (auto& i : tri)\n cout << \" t: \" << i << \"\\n\";\n\n cout << \"\\nthe rectangles are:\\n\"; /* output valid rectangles */\n for (auto& i : rect)\n cout << \" r: \" << i.width << \" x \" << i.height << \"\\n\";\n}\n\nBy storing values for your circles, triangles and rectangles independent of each other, you then have the ability to handle each type of shape as its own collection, e.g.\nExample Use/Output\n$ ./bin/read_shapes dat/shapes.txt\nerror: unrecognized shape '3'.\nerror: unrecognized shape '10'.\n\nthe circles are:\n c: 12\n c: 2\n c: 2.4\n\nthe triangles are:\n t: 2.9\n t: 2.9\n\nthe rectangles are:\n r: 3 x 4\n\nLook things over and let me know if you have further questions. The main takeaway is to insure you validate down to the point you can insure what you have read is either a round-peg to fit in the circle hole, a square-peg to fit in a square hole, etc..\n\nA: The only thing I added was a getline where I put a comment at the \"else\" of the loop.\nwhile(infile >> names) {\n if(names.at(0) == 'c') { \n double r; \n infile >> r;\n cout << \"radius = \" << r << endl;\n } else if(names.at(0) == 'r') { \n double w; \n double h; \n infile >> w;\n infile >> h;\n cout << \"width = \" << w << \", height = \" << h << endl;\n } else if(names.at(0) == 't') { \n double s; \n infile >> s;\n cout << \"side = \" << s << endl;\n } else {\n // discard of the rest of the line using getline()\n getline(infile, names);\n //cout << \"discard: \" << names << endl;\n\n }\n}\n\nOutput:\nradius = 12\nradius = 2\nwidth = 3, height = 4\nradius = 2.4\nside = 2.9\nside = 2.9\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/49227626", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: How to filter post by join condition? I have a table called wpps_posts which have this structure:\nID | post_title | post_type\n 1 foo zoacres-property\n 2 foo2 zoacres-property\n 3 foo3 post\n\nI would like to return all the posts with type zoacres-property and also I want filter them by price. Each price is stored inside the table wp_postmeta:\nmeta_id | post_id | meta_key | meta_value\n 100 2 price 5000 \n 100 1 price 0\n\nHow can I order all the posts by price ASC?\nI'm stuck with the following query:\nSELECT * FROM wpps_posts p\nINNER JOIN wpps_posts wp ON wp.ID = p.ID\nWHERE p.post_type = 'zoacres-property'\nORDER BY wp.meta??\n\nEXPECTED RESULT:\nID | post_title | post_type\n 1 foo zoacres-property\n 2 foo2 zoacres-propertY\n\n\nA: SELECT * FROM wpps_posts p\nINNER JOIN wp_postmeta wp ON wp.post_ID = p.ID\nAND wp.meta_key='price'\nWHERE p.post_type = 'zoacres-property'\nORDER BY wp.meta_value asc\n\n\nA: You could do something like this, depends what other type of meta type records you have.\nSELECT * FROM wpps_posts\nLEFT JOIN wp_postmeta ON wp_postmeta.post_id = wpps_posts.ID AND wp_postmeta.meta_key = 'price'\nWHERE wpps_posts.post_type = 'zoacres-property'\nORDER BY wp_postmeta.meta_value\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/63576155", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Convert the existing nested dictionary output in string to a list to iterate over it I have a rest api which provides a list of key value pair's and we need to fetch all the id's from this json output file.\nContents of the json file\n{\n \"count\": 6,\n \"results\": [\n {\n \"key\": \"roles\",\n \"id\": \"1586230\"\n },\n {\n \"key\": \"roles\",\n \"id\": \"1586951\"\n },\n {\n \"key\": \"roles\",\n \"id\": \"1586932\"\n },\n ],\n \"roles\": {\n \"1586230\": {\n \"name\": \"Systems Engineer\",\n \"deleted_at\": null,\n \"created_at\": \"2022-04-22T03:22:24-07:00\",\n \"updated_at\": \"2022-04-22T03:22:24-07:00\",\n \"id\": \"1586230\"\n },\n \"1586951\": {\n \"name\": \"Engineer- Software\",\n \"deleted_at\": null,\n \"created_at\": \"2022-05-05T01:51:29-07:00\",\n \"updated_at\": \"2022-05-05T01:51:29-07:00\",\n \"id\": \"1586951\"\n },\n \"1586932\": {\n \"name\": \"Engineer- SW\",\n \"deleted_at\": null,\n \"created_at\": \"2022-05-05T01:38:37-07:00\",\n \"updated_at\": \"2022-05-05T01:38:37-07:00\",\n \"id\": \"1586932\"\n },\n },\n \"meta\": {\n \"count\": 6,\n \"page_count\": 5,\n \"page_number\": 1,\n \"page_size\": 20\n }\n}\n\nThe rest call saves the contents to a file called p1234.json Opened the file in python:\nwith open ('p1234.json') as file:\n data2 = json.load(file)\n\nfor ids in data2['results']:\n res= ids['id']\n print(res)\n\nSimilarly\nwith open ('p1234.json') as file:\n data2 = json.load(file)\n\nfor role in data2['roles']:\n res= roles['name']\n print(res)\n\nfails with errors.\nHow to iterate over a nested array do I can only get the values of names listed in roles array\nroles --> 1586230 --> name --> System Engineer\n\nThank you\n\nA: You have to loop over the items of the dictionary.\nfor key, value in data2['roles'].items():\n res= value['name']\n print(res)\n\n\nA: There is nothing wrong with your code, I run it and I didn't get any error.\nThe problem that I see though is your Json file, some commas shouldn't be there:\n{\n\"count\": 6,\n\"results\": [\n {\n \"key\": \"roles\",\n \"id\": \"1586230\"\n },\n {\n \"key\": \"roles\",\n \"id\": \"1586951\"\n },\n {\n \"key\": \"roles\",\n \"id\": \"1586932\"\n } \\\\ here\n],\n\"roles\": {\n \"1586230\": {\n \"name\": \"Systems Engineer\",\n \"deleted_at\": null,\n \"created_at\": \"2022-04-22T03:22:24-07:00\",\n \"updated_at\": \"2022-04-22T03:22:24-07:00\",\n \"id\": \"1586230\"\n },\n \"1586951\": {\n \"name\": \"Engineer- Software\",\n \"deleted_at\": null,\n \"created_at\": \"2022-05-05T01:51:29-07:00\",\n \"updated_at\": \"2022-05-05T01:51:29-07:00\",\n \"id\": \"1586951\"\n },\n \"1586932\": {\n \"name\": \"Engineer- SW\",\n \"deleted_at\": null,\n \"created_at\": \"2022-05-05T01:38:37-07:00\",\n \"updated_at\": \"2022-05-05T01:38:37-07:00\",\n \"id\": \"1586932\"\n } \\\\ here \n},\n\"meta\": {\n \"count\": 6,\n \"page_count\": 5,\n \"page_number\": 1,\n \"page_size\": 20\n}\n\nafter that any parsing function will do the job.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/72434671", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}}
{"text": "Q: how to store Image profile(jpg file) and PDF documents in AWS DynamoDB? I am migrating my Spring MVC services to the AWS API Gateway using Python Lambda with Dynamo Db , I have endpoint where i can store or retrieve the people image and also the reports which is PDF file , can you please suggest me which is the best practice to store the images and pdf files in AWS .\nYour help is really appreciated!!\n\nA: Keep in mind, DynamoDB has a 400KB limit on each item.\nI would recommend using S3 for images and PDF documents. It also allows you to set up a CDN much more easily, rather than using something like DynamoDB.\nYou can always link your S3 link to an item in DynamoDB if you need to store data related to the file.\n\nA: AWS DynamoDB has a limit on the row size to be max of 400KB. So, it is not advisable to store the binary content of image/PDF document in a column directly. Instead, you should store the image/PDF in S3 and have the link stored in a column in DynamoDB.\nIf you were using Java, you could have leveraged the S3Link abstraction that takes care of storing the content in S3 and maintaining the link in DynamoDB column.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/47903547", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: Split a column after specific characters I have a field data in mysql db. For example\nquot_number\n====================\nUMAC/ARC/161299/801\nUMAC/LAK/151542/1051\nUMAC/LAK/150958/00050\n\nIam expecting an output as below:\n801\n1051\n00050\n\nActually the last numbers or characters after the last '/' has to be shown in my sql query. Any ways to achieve it?\nI tried to add something like this, but not getting expected result:\nLEFT(quotation.quot_number, 16) as quot_number4\n\nright(quot_number,((CHAR_LENGTH(quot_number))-(InStr(quot_number,',')))) as quot_number5\n\n\nA: Use function substring_index.\nselect\n substring_index(quot_number, '/', -1)\nfrom yourtable\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/41219251", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}}
{"text": "Q: HTTPS connection using PEM Certificate I'm trying to POST HTTPS requests using a PEM certificate like following: \nimport httplib \nCERT_FILE = '/path/certif.pem'\nconn = httplib.HTTPSConnection('10.10.10.10','443', cert_file =CERT_FILE) \nconn.request(\"POST\", \"/\") \nresponse = conn.getresponse() \nprint response.status, response.reason\nconn.close()\n\nI have the following error:\nTraceback (most recent call last):\nFile \"\", line 1, in \nFile \"/usr/lib/python2.6/httplib.py\", line 914, in request\nself._send_request(method, url, body, headers)\nFile \"/usr/lib/python2.6/httplib.py\", line 951, in _send_request\nself.endheaders()\nFile \"/usr/lib/python2.6/httplib.py\", line 908, in endheaders\nself._send_output()\nFile \"/usr/lib/python2.6/httplib.py\", line 780, in _send_output\nself.send(msg)\nFile \"/usr/lib/python2.6/httplib.py\", line 739, in send\nself.connect()\nFile \"/usr/lib/python2.6/httplib.py\", line 1116, in connect\nself.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)\nFile \"/usr/lib/python2.6/ssl.py\", line 338, in wrap_socket\nsuppress_ragged_eofs=suppress_ragged_eofs)\nFile \"/usr/lib/python2.6/ssl.py\", line 118, in __init__\ncert_reqs, ssl_version, ca_certs)\nssl.SSLError: [Errno 336265225] _ssl.c:339: error:140B0009:SSL \nroutines:**SSL_CTX_use_PrivateKey_file**:PEM lib\n\nWhen I remove the cert_file from httplib, I've the following response:\n200 ok\n\nWhen I add the Authentication header (like advised by MattH) with empty post payload, it works also.\nHowever, when I put the good request with the Path, the Body and the Header, like following (I simplified them...)\nbody = 'blablabla'\nURLprov = \"/syncaxis2/services/XXXsyncService\"\nauth_header = 'Basic %s' % (\":\".join([\"xxx\",\"xxxxx\"]).encode('Base64').strip('\\r\\n'))\nconn.request(\"POST\",URLprov,body,{'Authenticate':auth_header})\n\nI have 401 Unauthorized response !\nAs you can see, first, I'm asked to provide the PrivateKey ! why did I need the PrivateKey if I'm a client ? then, when I remove the PrivateKey and the certificate, and put the Path/Body/headers I have 401 Unauthorized error with the message WWW-Authenticate: Basic realm=\"SYNCNB Server Realm\".\nCould any one explain this issue? Is there another way to send HTTPS request using a certificate in Python?\n\nA: It sounds like you need something similar to an answer I have provided before to perform simple client certificate authentication. Here is the code for convenience modified slightly for your question:\nimport httplib\nimport urllib2\n\nPEM_FILE = '/path/certif.pem' # Renamed from PEM_FILE to avoid confusion\nCLIENT_CERT_FILE = '/path/clientcert.p12' # This is your client cert!\n\n# HTTPS Client Auth solution for urllib2, inspired by\n# http://bugs.python.org/issue3466\n# and improved by David Norton of Three Pillar Software. In this\n# implementation, we use properties passed in rather than static module\n# fields.\nclass HTTPSClientAuthHandler(urllib2.HTTPSHandler):\n def __init__(self, key, cert):\n urllib2.HTTPSHandler.__init__(self)\n self.key = key\n self.cert = cert\n def https_open(self, req):\n #Rather than pass in a reference to a connection class, we pass in\n # a reference to a function which, for all intents and purposes,\n # will behave as a constructor\n return self.do_open(self.getConnection, req)\n def getConnection(self, host):\n return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)\n\n\ncert_handler = HTTPSClientAuthHandler(PEM_FILE, CLIENT_CERT_FILE)\nopener = urllib2.build_opener(cert_handler)\nurllib2.install_opener(opener)\n\nf = urllib2.urlopen(\"https://10.10.10.10\")\nprint f.code\n\n\nA: See http://docs.python.org/library/httplib.html\nhttplib.HTTPSConnection does not do any verification of the server\u2019s certificate.\nThe option to include your private certificate is when the server is doing certificate based authentication of clients. I.e. the server is checking the client has a certificate signed by a CA that it trusts and is allowed to access it's resources.\n\nIf you don't specify the cert optional argument, you should be able to connect to the HTTPS server, but not validate the server certificate.\n\nUpdate\nFollowing your comment that you've tried basic auth, it looks like the server still wants you to authenticate using basic auth. Either your credentials are invalid (have you independently verified them?) or your Authenticate header isn't formatted correctly. Modifying your example code to include a basic auth header and an empty post payload:\nimport httplib \nconn = httplib.HTTPSConnection('10.10.10.10','443') \nauth_header = 'Basic %s' % (\":\".join([\"myusername\",\"mypassword\"]).encode('Base64').strip('\\r\\n'))\nconn.request(\"POST\", \"/\",\"\",{'Authorization':auth_header}) \nresponse = conn.getresponse() \nprint response.status, response.reason\nconn.close()\n\n\nA: What you're doing is trying to connect to a Web service that requires authentication based on client certificate.\nAre you sure you have a PEM file and not a PKCS#12 file? A PEM file looks like this (yes, I know I included a private key...this is just a dummy that I generated for this example):\n-----BEGIN RSA PRIVATE KEY----- \nMIICXQIBAAKBgQDDOKpQZexZtGMqb7F1OMwdcFpcQ/pqtCoOVCGIAUxT3uP0hOw8 \nCZNjLT2LoG4Tdl7Cl6t66SNzMVyUeFUrk5rkfnCJ+W9RIPkht3mv5A8yespeH27x \nFjGVbyQ/3DvDOp9Hc2AOPbYDUMRmVa1amawxwqAFPBp9UZ3/vfU8nxwExwIDAQAB \nAoGBAMCvt3svfr9zysViBTf8XYtZD/ctqYeUWEZYR9hj36CQyVLZuAnyMaWcS7j7 \nGmrfVNygs0LXxoO2Xvi0ZOxj/mZ6EcZd8n37LxTo0GcWvAE4JjPr7I4MR2OvGYa/ \n1696e82xwEnUdpyBv9z3ebleowQ1UWP88iq40oZYukUeignRAkEA9c7MABi5OJUq \nhf9gwm/IBie63wHQbB2wVgB3UuCYEa4Zd5zcvJIKz7NfhsZKKcZJ6CBVxwUd84aQ \nAue2DRwYQwJBAMtQ5yBA8howP2FDqcl9sovYR0jw7Etb9mwsRNzJwQRYYnqCC5yS \nnOaNn8uHKzBcjvkNiSOEZFGKhKtSrlc9qy0CQQDfNMzMHac7uUAm85JynTyeUj9/ \nt88CDieMwNmZuXZ9P4HCuv86gMcueex5nt/DdVqxXYNmuL/M3lkxOiV3XBavAkAA \nxow7KURDKU/0lQd+x0X5FpgfBRxBpVYpT3nrxbFAzP2DLh/RNxX2IzAq3JcjlhbN \niGmvgv/G99pNtQEJQCj5AkAJcOvGM8+Qhg2xM0yXK0M79gxgPh2KEjppwhUmKEv9 \no9agBLWNU3EH9a6oOfsZZcapvUbWIw+OCx5MlxSFDamg \n-----END RSA PRIVATE KEY----- \n-----BEGIN CERTIFICATE----- \nMIIDfjCCAuegAwIBAgIJAOYJ/e6lsjrUMA0GCSqGSIb3DQEBBQUAMIGHMQswCQYD \nVQQGEwJVUzELMAkGA1UECBMCRkwxDjAMBgNVBAcTBVRhbXBhMRQwEgYDVQQKEwtG \nb29iYXIgSW5jLjEQMA4GA1UECxMHTnV0IEh1dDEXMBUGA1UEAxMOd3d3LmZvb2Jh \nci5jb20xGjAYBgkqhkiG9w0BCQEWC2Zvb0BiYXIuY29tMB4XDTExMDUwNTE0MDk0 \nN1oXDTEyMDUwNDE0MDk0N1owgYcxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJGTDEO \nMAwGA1UEBxMFVGFtcGExFDASBgNVBAoTC0Zvb2JhciBJbmMuMRAwDgYDVQQLEwdO \ndXQgSHV0MRcwFQYDVQQDEw53d3cuZm9vYmFyLmNvbTEaMBgGCSqGSIb3DQEJARYL \nZm9vQGJhci5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMM4qlBl7Fm0 \nYypvsXU4zB1wWlxD+mq0Kg5UIYgBTFPe4/SE7DwJk2MtPYugbhN2XsKXq3rpI3Mx \nXJR4VSuTmuR+cIn5b1Eg+SG3ea/kDzJ6yl4fbvEWMZVvJD/cO8M6n0dzYA49tgNQ \nxGZVrVqZrDHCoAU8Gn1Rnf+99TyfHATHAgMBAAGjge8wgewwHQYDVR0OBBYEFHZ+ \nCPLqn8jlT9Fmq7wy/kDSN8STMIG8BgNVHSMEgbQwgbGAFHZ+CPLqn8jlT9Fmq7wy \n/kDSN8SToYGNpIGKMIGHMQswCQYDVQQGEwJVUzELMAkGA1UECBMCRkwxDjAMBgNV \nBAcTBVRhbXBhMRQwEgYDVQQKEwtGb29iYXIgSW5jLjEQMA4GA1UECxMHTnV0IEh1 \ndDEXMBUGA1UEAxMOd3d3LmZvb2Jhci5jb20xGjAYBgkqhkiG9w0BCQEWC2Zvb0Bi \nYXIuY29tggkA5gn97qWyOtQwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOB \ngQAv13ewjgrIsm3Yo8tyqTUHCr/lLekWcucClaDgcHlCAH+WU8+fGY8cyLrFFRdk \n4U5sD+P313Adg4VDyoocTO6enA9Vf1Ar5XMZ3l6k5yARjZNIbGO50IZfC/iblIZD \nUpR2T7J/ggfq830ACfpOQF/+7K+LgFLekJ5dIRuD1KKyFg== \n-----END CERTIFICATE-----\n\nRead this question.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/5896380", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "8"}}
{"text": "Q: Flutter: Mensagem de erro Could not update files on device: HttpException Ol\u00e1, estou estudando Flutter e recentemente tive um problema, quando tentei executar meu projeto com Flutter run recebi a mensagem de erro:\nCould not update files on device: HttpException: Connection closed before full header was received, uri = http://127.0.0.1:50365/h3iViYQmEC4=/\nTentei com emulador e com meu pr\u00f3prio celular por\u00e9m recebo o mesmo erro.\nO estranho \u00e9 que quando eu crio um App em Flutter novo ele funciona, consigo fazer todas as modifica\u00e7\u00f5es porem se eu parar e tentar executar novamente o erro aparece e o App n\u00e3o roda.\nJ\u00e1 tentei reiniciar os dispositivos. Flutter clean Flutter doctor [Exibe que est\u00e1 tudo certo]\nAt\u00e9 meus app antigos que tinha feito pra estudar acontece a mesma coisa, sendo que estavam funcionando.\nMensagem completa com Flutter run:\n\n\n\n\n*\n\n*Estou usando Android.\n\n*Mensagem que aparece no celular \u00e9 a padr\u00e3o 'O app parou de funcionar, deseja encerrar?'\n\n\nA: [RESOLVIDO] - O problema era uma fonte externa que eu estava importando que aparentemente se corrompeu, percebi que aparece uma mensagem :\nEu retirei todo lugar que eu usava ela e voltou ao normal.\n", "meta": {"language": "pt", "url": "https://pt.stackoverflow.com/questions/448434", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: TFS configure variables on Release definition instantiation I have a release definition setup with several tasks. When a developer wants to create a release from this definition, i'd like to give them the option of selecting which features they'd like to release (turn on/off tasks). Ideally this would be via the Create Release dialog using a variable or similar.\nCan this be done? Or is the only way to achieve this to create a draft release and enable/disable the tasks on each environment? Believe this is prone to error (toggle task on one environment but forget to on another) and this is not an option as administrator has locked editing of definitions (prevent incorrect setup of production releases).\nUnderstand I can create separate release definitions to cover the options but it seems like a lot of duplication.\n\nA: Unfortunately, this is not supported in TFS currently. The workarounds are just like you mentioned above, to disable and enable those steps or use draft release.\nThis is a user voice about your request you could vote:\n https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/19165690-select-steps-when-create-release\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/43777906", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: AWS S3 Internal Server Error: Tyring to upload pdf file on after another I'm trying to generate PDF file using FPDF and PHP and later upload to AWS-s3 and generate the url. When I executed the below code in my local-machine Using XAMPP it's generating files and uploading it to S3.\nBut When I deployed in AWS server as an API it's uploading only first file and for other its giving 500 server error\nBelow is my code that I used in Local Machine\n require '../fpdf/fpdf.php';\n require 'start.php';\n\n use Aws\\Exception\\AwsException;\n\n $location = \"bangalore\";\n $db = getConnection();\n $query = \"SELECT first_name FROM customer_info where location = '$location'\";\n $execute = $db->query($query);\n $result = $execute->fetchAll(PDO::FETCH_ASSOC);\n\n for($i = 0; $i < $len; $i++) {\n $pdf = new FPDF();\n $pdf->AddPage();\n\n$pdf->SetFont('Arial', 'B', 14);\n$txt = \"Legal Document of \".$result[$i]['first_name'];\n$pdf->Cell(180, 0, $txt, 0, 1, 'C');\n$pdf->Line(5, 20, 200, 20);\n\n$docname = $result[$i]['first_name'] . \".pdf\";\n$filepath = \"../file/{$docname}\";\n$pdf->Output($filepath, 'F');\n\n//s3 client\ntry {\n $res = $S3->putObject([\n 'Bucket' => $config['S3']['bucket'],\n 'Key' => \"PATH_TO_THE_DOCUMENT/{$docname}\",\n 'Body' => fopen($filepath, 'rb'),\n 'ACL' => 'public-read'\n ]);\n\n var_dump($res[\"ObjectURL\"]);\n} catch (S3Exception $e) {\n echo $e->getMessage() . \"\\n\";\n}\n\n}\nOutput:\n Array ( [0] => Array ( [first_name] => Mohan ) [1] => Array ( [first_name] => Prem ) [2] => Array ( [first_name] => vikash ) [3] => Array ( [first_name] => kaushik ) )\n\n string(70) \"https://streetsmartb2.s3.amazonaws.com/PATH_TO_THE FILE/Mohan.pdf\" \n\n string(72) \"https://streetsmartb2.s3.amazonaws.com/PATH_TO_THE FILE/Prem%20.pdf\" \n\nAPI CODE\n //pdf generation another api\n $app->post('/pdfmail', function() use($app){\n\n //post parameters\n $location = $app->request->post('loc');\n $id = $app->request->post('id');\n\n\n\n $db = getConnection();\n $query = \"SELECT * FROM customer_info where location = '$location'\";\n $execute = $db->query($query);\n $result = $execute->fetchAll(PDO::FETCH_ASSOC);\n $len = sizeof($result);\n\n //request array\n $request = array();\n\n if($result != Null) {\n for($i = 0; $i < $len; $i++) {\n $pdf = new FPDF();\n $pdf->AddPage();\n\n $pdf->SetFont('Arial', 'B', 14);\n $txt = \"Document of Mr.\" . $result[$i]['first_name'];\n $pdf->Cell(180, 0, $txt, 0, 1, 'C');\n $pdf->Line(5, 20, 200, 20);\n\n $docname = $result[$i]['first_name'] . \".pdf\";\n var_dump($docname);\n $filepath = \"../file/{$docname}\";\n var_dump($filepath);\n $pdf->Output($filepath, 'F');\n\n\n //s3 client\n require '../aws/aws-autoloader.php';\n\n $config = require('config.php');\n\n\n //create s3 instance\n $S3 = S3Client::factory([\n 'version' => 'latest',\n 'region' => 'REGION',\n 'credentials' => array(\n 'key' => $config['S3']['key'],\n 'secret' => $config['S3']['secret']\n )\n ]);\n\n\n\n try {\n $res = $S3->putObject([\n 'Bucket' => $config['S3']['bucket'],\n 'Key' => \"PATH_TO_FILE{$docname}\",\n 'Body' => fopen($filepath, 'rb'),\n 'ACL' => 'public-read'\n ]);\n var_dump($res[\"ObjectURL\"]);\n } catch (S3Exception $e) {\n echo $e->getMessage() . \"\\n\";\n }\n\n }\n }\n\nOUTPUT WHEN TESTED IN POSTMAN\n string(10) \"vikash.pdf\"\n string(18) \"../file/vikash.pdf\"\n string(71) \"https://streetsmartb2.s3.amazonaws.com/PATH_TO_FILE/vikash.pdf\"\n string(13) \"pradeepan.pdf\"\n string(21) \"../file/pradeepan.pdf\"\n\nAfter this I'm getting internal server error.\n\nA: Instead of using require_once I've use require...So as the code traversed it was creating AWS Class again and again. \nCode\n //s3 client\n require '../aws/aws-autoloader.php'; //use require_once\n\n $config = require('config.php');\n\n\n //create s3 instance\n $S3 = S3Client::factory([\n 'version' => 'latest',\n 'region' => 'REGION',\n 'credentials' => array(\n 'key' => $config['S3']['key'],\n 'secret' => $config['S3']['secret']\n )\n ]);\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/48921630", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Auto-generate @version value in javadoc For the @version tag in javadoc, I use the same value as in BuildConfig.VERSION_NAME. I would like to inject that value, instead of changing every file for each release.\nI tried:\n* @version {@value BuildConfig#VERSION_NAME}\nand\n* @version @versionName (and add -tag versionName:a:\"2.2.2\")\nbut none of these works.\nI could run sed just before the doc gets generated, but I would rather prefer something 'officially' supported.\nAny ideas how to solve this?\n\nA: For the second form, you can put your custom tag at the beginning of a javadoc line.\n/**\n * This is a class of Foo \n *\n * @version\n *\n * @configVersion.\n */\n\nThen use command javadoc -version -tag configVersion.:a:\"2.2.2\" to generate your javadoc, the custom tag should be handled in this way. Note the last dot(.) character in custom tag name, as the command javadoc suggests\n\nNote: Custom tags that could override future standard tags: @configVersion. To avoid potential overrides, use at least one period character (.) in custom tag names.\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/58002547", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: How to retrieve data from MongoDb Atlas and display in an ejs file using mongoose and Nodejs Thanks for the help in advance.\nI am trying to retrieve data from my database- myFirstDatabase and collection named as 'shipment' in mongondb. This is a nested schema but I am only interested in the parent data for now. I have this code which retrieves data to the console log. But how can I display or access the data in my orders.ejs file?\n\n\nShipment.find({}, function (err, data) {\n if (err) throw err\n\n console.log(data)\n})\n\n\nMongoDB connected...\n[\n {\n _id: new ObjectId(\"61353311261da54811ee0ca5\"),\n name: 'Micky Mouse',\n phone: '5557770000',\n email: 'g@gmail.com',\n address: {\n address: '10 Merrybrook Drive',\n city: 'Herndon',\n state: 'Virginia',\n zip: '21171',\n country: 'United States',\n _id: new ObjectId(\"61353311261da54811ee0ca6\")\n },\n items: {\n car: 'Honda Pilot 2018',\n boxItem: '3 uHaul boxes',\n furniture: 'None',\n electronics: '1 50\" Samsung TV',\n bags: '2 black suites cases',\n _id: new ObjectId(\"61353311261da54811ee0ca7\")\n },\n date: 2021-09-05T21:13:53.484Z,\n __v: 0\n }\n]\n\n\nThis is the ejs file, a table I am trying to populate the data i get from my mongodb\n\n\n
\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/69067410", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: node.js app running using forever inaccessible after a while I have a node.js server and a java client communicating using socket.io. I use this api https://github.com/Gottox/socket.io-java-client for the java client. I am using forever module\nto run my server.\nEverything works well but after some time , my server becomes inaccessible and I need to restart it, Also, most of the times i need to update/edit my node.js server file in order to make my server work again (restarted). Its been two weeks already and im still keep restarting my server :(.\nHas anyone run into the same problem ? and solution or advice please. \nThanks\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/17628274", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Populating Fields in Table with GUIDs from Feature Class? Is there a way to add GUIDs from a feature class to a table based on specific attributes? I have a large maintenance record table that is tied to specific points through the GUID of that point. I have added new records but they are not tied to a point yet. Instead of going through and copy/pasting each pole GUID to the appropriate maintenance record manually, I was hoping to use model builder or python to populate the fields in the table automatically. The data that overlaps between the two is the name of the line and the pole number.\nI think this is a relationship (many to many), but both the line name and the pole number need to match. I'm also new to using model builder and python.\n\nA: ModelBuilder does not provide a solution where you can create an editable join based on multiple fields. Your question is virtually the same as Auto populating field in attribute table, using several fields of record information from another table? and the answers are the same. You must either concatenate the fields into a single new field, run my Multi-field Key to Single-field Key tool to create a new numeric field that represents the multi-field key or use the Make Query Table tool. I do not consider the Make Query Table option workable, since it cannot be edited, it drops unmatched records, and it requires that you constantly recreate your entire feature class each time to update it.\nA Python script could do it using a cursor and dictionary. See my Blog on Turbo Charging Data Manipulation with Python Cursors and Dictionaries. In particular look at the example of Creating a Multi-Field Python Dictionary Key to Replace a Concatenated Join Field. Once a working script has been writen, this is actually the fastest of the methods and since once it completed you would have a single field key through your GUID, it is probably the best for your particular data. The concatenated field or single field key would be redundant once your GUID was transferred.\nThe python script underlying the Multi-field key to Single field key tool has a more sophisticated method of doing the multi-field matching, since it preserves the sort order native to each field type rather than using the sorting that occurs when values are converted to strings. So if you want a single key that sorts the same way that the separate fields would sort, this tool is the best.\n", "meta": {"language": "en", "url": "https://gis.stackexchange.com/questions/193524", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: No 'Access-Control-Allow-Origin' header is present on the requested resource. Laravel 5.4 with cors package Hi I was following this tutorial regarding Laravel and VueJs communication. \nhttps://www.youtube.com/watch?v=5hOMkFMxY90&list=PL3ZhWMazGi9IommUd5zQmjyNeF7s1sP7Y&index=8\nI have done exactly like it was said in the tutorial. It uses a CORS package https://github.com/barryvdh/laravel-cors/\nI have added the service provider middlewares everything as it was told in the tutorial but it just doesnt seem to work.\nI have tried it in Laravel 5.4 and Laravel 5.3 as well.\nThis is my RouetServiceProvider: \n\n namespace App\\Providers;\n\n use Illuminate\\Support\\Facades\\Route;\n use Illuminate\\Foundation\\Support\\Providers\\RouteServiceProvider as ServiceProvider;\n\n class RouteServiceProvider extends ServiceProvider\n {\n /**\n * This namespace is applied to your controller routes.\n *\n * In addition, it is set as the URL generator's root namespace.\n *\n * @var string\n */\n protected $namespace = 'App\\Http\\Controllers';\n\n /**\n * Define your route model bindings, pattern filters, etc.\n *\n * @return void\n */\n public function boot()\n {\n //\n\n parent::boot();\n }\n\n /**\n * Define the routes for the application.\n *\n * @return void\n */\n public function map()\n {\n $this->mapApiRoutes();\n\n $this->mapWebRoutes();\n\n //\n }\n\n /**\n * Define the \"web\" routes for the application.\n *\n * These routes all receive session state, CSRF protection, etc.\n *\n * @return void\n */\n protected function mapWebRoutes()\n {\n Route::group([\n 'middleware' => 'web',\n 'namespace' => $this->namespace,\n ], function ($router) {\n require base_path('routes/web.php');\n });\n }\n\n /**\n * Define the \"api\" routes for the application.\n *\n * These routes are typically stateless.\n *\n * @return void\n */\n protected function mapApiRoutes()\n {\n Route::group([\n 'middleware' => ['api' , 'cors'],\n 'namespace' => $this->namespace,\n 'prefix' => 'api',\n ], function ($router) {\n require base_path('routes/api.php');\n });\n }\n }\n\nThis is my middleware code in kernel \n protected $middleware = [\n \\Barryvdh\\Cors\\HandleCors::class,\n \\Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode::class,\n \\Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize::class,\n \\App\\Http\\Middleware\\TrimStrings::class,\n \\Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull::class,\n];\n\nI have added its service provider too.\nI have seen all the solutions here on stackoverflow but none of them seems to work. I do not need theoretical answer but a practical solution \nThanks \n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/43503718", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: no partition after installing ubuntu I cannot boot back my windows 8 disk after Ubuntu install.\nI installed Ubuntu. Probably I selected my main disk (I wanted to used the diskonkey disk). After about 3-4 screens (selecting time zone) I noticed that is using the wrong partition and I powered down the laptop.\nNow I don\u2019t have a partition table with windows 8. It cannot boot. I think I have to recover my MBR and partition table.\nI used the boot repair - this is what it showed: http://paste.ubuntu.com/9659707/\n\nA: Powering down in the middle of an installation because you've taken the wrong choice is always the worst decision you can take. That is like powering down your car in the middle of a busy cross-road because you took a wrong turn. (Just believe me: don't try this!)\nThe easiest way to solve this situation is to:\n\n\n*\n\n*Enable UEFI in the BIOS and reboot.\n\n*If that didn't work, take the recovery DVD that came with your machine and boot with that to get your system back. Warning this will destroy all of your data still remaining on the drive. (You did make a back-up before starting the install didn't you?)\n\n\nThe more difficult way:\n\n\n*\n\n*Attach your back-up drive to the computer\n\n*Boot with the Ubuntu LiveCD\n\n*Press Ctrl+Alt+T and type:\nsudo apt-get install testdisk\ntestdisk\n\n\n*Follow testdisk step-by-step instructions to save as much of your data as possible.\n\n*Recover using the Recovery DVD\n\n*Follow these instructions on how to efficiently partition a Windows-Ubuntu dual-boot and how to install Ubuntu on a pre-installed Windows 8 machine.\n\n", "meta": {"language": "en", "url": "https://askubuntu.com/questions/585361", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: How to pass outside function to WP_REST_Request Learning with WP REST I'm unsure how to properly pass what is typically at the beginning of a PHP page form to WP_REST_Response. For example:\nAt the beginning of page-foobar.php if I have:\n// IP ADDRESS\nfunction ipAddress() {\n if (isset($_SERVER['REMOTE_ADDR'])) :\n $ip_address = $_SERVER['REMOTE_ADDR'];\n else :\n $ip_address = \"undefined\";\n endif;\n return $ip_address;\n}\n/*\n Template Name: Foobar\n*/\n\nand need to use $ip_address in:\nfunction foobar(\\WP_REST_Request $request) {\n if ($ip_address == \"undefined\") :\n return new WP_Error( 'bad_ip', 'No IP found', array( 'status' => 404 ) );\n endif;\n}\n\nhow would I go about doing that? When I searched I ran across:\nPass a Variable from one file to another in WordPress but I dont think it would be a good idea to pass as a global. Further researching Passing variables between files in WordPress or PHP but I've already called the template in functions.php. How can I pass a function from the template to the function request if it's stored in a different file?\n\nA: My approach would be, to declare the function in functions.php and then call it whenever you need.\nSince you are trying to use superglobals, you can access them anywhere. Move the code from your page-foobar.php to your theme's functions.php, and use this whenever you need to access it:\nipAddress();\n\nSo, in your REST function you can have:\nfunction foobar(\\WP_REST_Request $request) {\n $ip_address = ipAddress();\n if ($ip_address == \"undefined\") :\n return new WP_Error( 'bad_ip', 'No IP found', array( 'status' => 404 ) );\n endif;\n}\n\n", "meta": {"language": "en", "url": "https://wordpress.stackexchange.com/questions/277095", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Swift: How to not load AppDelegate during Tests I have an OS X application which on startup loads some data from a server and pushes notifications to the NSUserNotificationCenter.\nNow I have the problem that this also happens during my unit tests. I found no way yet to prevent this. Of course I could stub the HTTP loads. But in some cases I want to test the loading and then the notifications get sent anyway. \nWhat I'm trying to do is to make the test runs not load the AppDelegate but a fake one that I'm only using for tests. I found several examples [1] on how to do that with UIApplicationMain, where you can pass a specific AppDelegate class name. The same is not possible with NSApplicationMain [2].\nWhat I've tried is the following:\nRemoved @NSApplicationMain from AppDelegate.swift, then added a main.swift with the following content:\nclass FakeAppDelegate: NSObject, NSApplicationDelegate {\n}\n\nNSApplication.sharedApplication()\nNSApp.delegate = FakeAppDelegate()\nNSApplicationMain(Process.argc, Process.unsafeArgv)\n\nThis code runs before tests but has no effect at all.\nI might have to say: My AppDelegate is almost empty. To handle the MainMenu.xib stuff I made a separate view controller which does the actual loading and notification stuff in awakeFromNib. \n[1] http://www.mokacoding.com/blog/prevent-unit-tests-from-loading-app-delegate-in-swift/\n[2] https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Miscellaneous/AppKit_Functions/#//apple_ref/c/func/NSApplicationMain\n\nA: Just an update on the previous accept answer, this is my main.swift:\nprivate func isTestRun() -> Bool {\n return NSClassFromString(\"XCTestCase\") != nil\n}\n\nif isTestRun() {\n // This skips setting up the app delegate\n NSApplication.shared.run()\n} else {\n // For some magical reason, the AppDelegate is setup when\n // initialized this way\n _ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)\n}\n\nA bit more compact! I'm using Swift 4.1 and XCode 9.4.1\n\nA: After days of trying and failing I found an answer on the Apple forums:\n\nThe problem was that my main.swift file was initializing my AppDelegate before NSApplication had been initialized. The Apple documentation makes it clear that lots of other Cocoa classes rely on NSApplication to be up and running when they are initialized. Apparently, NSObject and NSWindow are two of them.\n\nSo my final and working code in main.swift looks like this:\nprivate func isTestRun() -> Bool {\n return NSClassFromString(\"XCTest\") != nil\n}\n\nprivate func runApplication(\n application: NSApplication = NSApplication.sharedApplication(),\n delegate: NSObject.Type? = nil,\n bundle: NSBundle? = nil,\n nibName: String = \"MainMenu\") {\n\n var topLevelObjects: NSArray?\n\n // Actual initialization of the delegate is deferred until here:\n application.delegate = delegate?.init() as? NSApplicationDelegate\n\n guard bundle != nil else {\n application.run()\n return\n }\n\n if bundle!.loadNibNamed(nibName, owner: application, topLevelObjects: &topLevelObjects ) {\n application.run()\n } else {\n print(\"An error was encountered while starting the application.\")\n }\n}\n\nif isTestRun() {\n let mockDelegateClass = NSClassFromString(\"MockAppDelegate\") as? NSObject.Type\n runApplication(delegate: mockDelegateClass)\n} else {\n runApplication(delegate: AppDelegate.self, bundle: NSBundle.mainBundle())\n}\n\nSo the actual problem before was that the Nib was being loaded during tests. This solution prevents this. It just loads the application with a mocked application delegate whenever it detects a test run (By looking for the XCTest class).\nI'm sure I will have to tweak this a bit more. Especially when a start with UI Testing. But for the moment it works.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/39116318", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "7"}}
{"text": "Q: How to use std::transform with a lambda function that takes additional parameters In C++ 11 (or higher) can I use std::transform and a lambda function to transform a vector that also takes other parameters? For example, how do I pass param to the lambda function below?\nstd::vector a{ 10.0, 11.0, 12.0 };\nstd::vector b{ 20.0, 30.0, 40.0 };\nstd::vector c;\ndouble param = 1.5;\n//The desired function is c = (a-b)/param \ntransform(a.begin(), a.end(), b.begin(), std::back_inserter(c),\n [](double x1, double x2) {return(x1 - x2)/param; });\n\nstd::transform wants a function with two input parameters. Do I need to use std::bind?\n\nA: You just need to capture param in your capture list:\ntransform(a.begin(), a.end(), b.begin(), std::back_inserter(c),\n [param](double x1, double x2) {return(x1 - x2)/param; });\n\nCapturing it by reference also works - and would be correct if param was a big class. But for a double param is fine.\n\nA: This is what the lambda capture is for. You need to specify & or = or param in the capture block ([]) of the lambda. \nstd::vector a{ 10.0, 11.0, 12.0 };\nstd::vector b{ 20.0, 30.0, 40.0 };\nstd::vector c;\ndouble param = 1.5;\n//The desired function is c = (a-b)/param \ntransform(a.begin(), a.end(), b.begin(), std::back_inserter(c),\n [=](double x1, double x2) {return(x1 - x2)/param; });\n// ^ capture all external variables used in the lambda by value\n\nIn the above code we just capture by value since copying a double and having a reference is pretty much the same thing performance wise and we don't need reference semantics.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/53011875", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: How can I add an intranet-only endpoint to my IIS hosted WCF service? I have a WCF service hosted in IIS that uses basicHttpBindings. I'm adding a new method to the ServiceContract that will be called from a console app to perform an administrative task. I got to thinking, well wouldn't it be nice if I gave this method its own endpoint. Then I thought and what if that endpoint wasn't even publicly accessible. It would be much better if only a computer on our LAN could access it. It might even be cool if only an AD administrator was authorized to use it, but I don't want to get too elaborate. So I added a new ServiceContract interface that includes my new method. How can I restrict it to LAN access only? Do I need a NetTcpBinding? Networking is not my strong suit and I'm a little confused, conceptually, on how a TCP endpoint could be hosted from IIS. Additionally, when hosting multiple endpoints, does each have to have its own address or can they be at the same address?\n\nA: I am gonna answer some of your questions\n\n\n*\n\n*there is no binding that would limit access to LAN network though you can use windows authentication to allow users from your network to use the service \n\n*the nettcpbinding is only a tcp connection and you can host it on IIS pof course\ncheck this link for more information hosting nettcp on IIS\n\n*you can have one base address for multiple endpoints , example:\nhttps://localhost:8080/calculator.svc\nnet.tccp://localhost:8080/calculator.svc\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/29483797", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: A Quickselect C Algorithm faster than C Qsort I have tried to implement a C QuickSelect algorithm as described in this post (3 way quicksort (C implementation)).\nHowever, all I get are performances 5 to 10 times less than the default qsort (even with an initial shuffling).\nI tried to dig into the original qsort source code as provide here (https://github.com/lattera/glibc/blob/master/stdlib/qsort.c), but it's too complex.\nDoes anybody have a simpler, and better algorithm?\nAny idea is welcomed.\nThanks,\nNB: my original problem is to try to get the Kth smallest values of an array to the first Kth indices. So I planned to call quickselect K times\nEDIT 1: Here is the Cython Code as copied and adapted from the link above\ncdef void qswap(void* a, void* b, const size_t size) nogil:\n cdef char temp[size]# C99, use malloc otherwise\n #char serves as the type for \"generic\" byte arrays\n\n memcpy(temp, b, size)\n memcpy(b, a, size)\n memcpy(a, temp, size)\n\ncdef void qshuffle(void* base, size_t num, size_t size) nogil: #implementation of Fisher\n cdef int i, j, tmp# create local variables to hold values for shuffle\n\n for i in range(num - 1, 0, -1): # for loop to shuffle\n j = c_rand() % (i + 1)#randomise j for shuffle with Fisher Yates\n qswap(base + i*size, base + j*size, size)\n\ncdef void partition3(void* base,\n size_t *low, size_t *high, size_t size,\n QComparator compar) nogil: \n # Modified median-of-three and pivot selection. \n cdef void *ptr = base\n cdef size_t lt = low[0]\n cdef size_t gt = high[0] # lt is the pivot\n cdef size_t i = lt + 1# (+1 !) we don't compare pivot with itself\n cdef int c = 0\n\n while (i <= gt):\n c = compar(ptr + i * size, ptr + lt * size)\n if (c < 0):# base[i] < base[lt] => swap(i++,lt++)\n qswap(ptr + lt * size, ptr + i * size, size)\n i += 1\n lt += 1\n elif (c > 0):#base[i] > base[gt] => swap(i, gt--)\n qswap(ptr + i * size, ptr + gt* size, size)\n gt -= 1\n else:#base[i] == base[gt]\n i += 1\n #base := [<<<<>>>>>]\n low[0] = lt \n high[0] = gt \n\n\ncdef void qselectk3(void* base, size_t lo, size_t hi, \n size_t size, size_t k, \n QComparator compar) nogil: \n cdef size_t low = lo \n cdef size_t high = hi \n\n partition3(base, &low, &high, size, compar) \n\n if ((k - 1) < low): #k lies in the less-than-pivot partition \n high = low - 1\n low = lo \n elif ((k - 1) >= low and (k - 1) <= high): #k lies in the equals-to-pivot partition\n qswap(base, base + size*low, size)\n return \n else: # k > high => k lies in the greater-than-pivot partition \n low = high + 1\n high = hi \n qselectk3(base, low, high, size, k, compar)\n\n\"\"\"\n A selection algorithm to find the nth smallest elements in an unordered list. \n these elements ARE placed at the nth positions of the input array \n\"\"\"\ncdef void qselect(void* base, size_t num, size_t size,\n size_t n,\n QComparator compar) nogil:\n cdef int k\n qshuffle(base, num, size)\n for k in range(n):\n qselectk3(base + size*k, 0, num - k - 1, size, 1, compar)\n\nI use python timeit to get the performance of both method pyselect(with N=50) and pysort.\nLike this\ndef testPySelect():\n A = np.random.randint(16, size=(10000), dtype=np.int32)\n pyselect(A, 50)\ntimeit.timeit(testPySelect, number=1)\n\ndef testPySort():\n A = np.random.randint(16, size=(10000), dtype=np.int32)\n pysort(A)\ntimeit.timeit(testPySort, number=1)\n\n\nA: The answer by @chqrlie is the good and final answer, yet to complete the post, I am posting the Cython version along with the benchmarking results.\nIn short, the proposed solution is 2 times faster than qsort on long vectors!\n\n\n cdef void qswap2(void *aptr, void *bptr, size_t size) nogil:\n cdef uint8_t* ac = aptr\n cdef uint8_t* bc = bptr\n cdef uint8_t t\n while (size > 0): t = ac[0]; ac[0] = bc[0]; bc[0] = t; ac += 1; bc += 1; size -= 1\n\n cdef struct qselect2_stack:\n uint8_t *base\n uint8_t *last\n\n cdef void qselect2(void *base, size_t nmemb, size_t size,\n size_t k, QComparator compar) nogil:\n cdef qselect2_stack stack[64]\n cdef qselect2_stack *sp = &stack[0]\n\n cdef uint8_t *lb\n cdef uint8_t*ub\n cdef uint8_t *p\n cdef uint8_t *i\n cdef uint8_t *j\n cdef uint8_t *top\n\n if (nmemb < 2 or size <= 0):\n return\n\n top = base\n if(k < nmemb): \n top += k*size \n else: \n top += nmemb*size\n\n sp.base = base\n sp.last = base + (nmemb - 1) * size\n sp += 1\n\n cdef size_t offset\n\n while (sp > stack):\n sp -= 1\n lb = sp.base\n ub = sp.last\n\n while (lb < ub and lb < top):\n #select middle element as pivot and exchange with 1st element\n offset = (ub - lb) >> 1\n p = lb + offset - offset % size\n qswap2(lb, p, size)\n\n #partition into two segments\n i = lb + size\n j = ub\n while 1:\n while (i < j and compar(lb, i) > 0):\n i += size\n while (j >= i and compar(j, lb) > 0):\n j -= size\n if (i >= j):\n break\n qswap2(i, j, size)\n i += size\n j -= size\n\n # move pivot where it belongs\n qswap2(lb, j, size)\n\n # keep processing smallest segment, and stack largest\n if (j - lb <= ub - j):\n sp.base = j + size\n sp.last = ub\n sp += 1\n ub = j - size\n else:\n sp.base = lb\n sp.last = j - size\n sp += 1\n lb = j + size\n\n\n\n cdef int int_comp(void* a, void* b) nogil:\n cdef int ai = (a)[0] \n cdef int bi = (b)[0]\n return (ai > bi ) - (ai < bi)\n\n def pyselect2(numpy.ndarray[int, ndim=1, mode=\"c\"] na, int n):\n cdef int* a = &na[0]\n qselect2(a, len(na), sizeof(int), n, int_comp)\n\n\nHere are the benchmark results (1,000 tests):\n\n#of elements K #qsort (s) #qselect2 (s)\n1,000 50 0.1261 0.0895\n1,000 100 0.1261 0.0910\n\n10,000 50 0.8113 0.4157\n10,000 100 0.8113 0.4367\n10,000 1,000 0.8113 0.4746\n\n100,000 100 7.5428 3.8259\n100,000 1,000 7,5428 3.8325\n100,000 10,000 7,5428 4.5727\n\nFor those who are curious, this piece of code is a jewel in the field of surface reconstruction using neural networks.\nThanks again to @chqrlie, your code is unique on The Web.\n\nA: Here is a quick implementation for your purpose: qsort_select is a simple implementation of qsort with automatic pruning of unnecessary ranges.\nWithout && lb < top, it behaves like the regular qsort except for pathological cases where more advanced versions have better heuristics. This extra test prevents complete sorting of ranges that are outside the target 0 .. (k-1). The function selects the k smallest values and sorts them, the rest of the array has the remaining values in an undefinite order.\n#include \n#include \n\nstatic void exchange_bytes(uint8_t *ac, uint8_t *bc, size_t size) {\n while (size-- > 0) { uint8_t t = *ac; *ac++ = *bc; *bc++ = t; }\n}\n\n/* select and sort the k smallest elements from an array */\nvoid qsort_select(void *base, size_t nmemb, size_t size,\n int (*compar)(const void *a, const void *b), size_t k)\n{\n struct { uint8_t *base, *last; } stack[64], *sp = stack;\n uint8_t *lb, *ub, *p, *i, *j, *top;\n\n if (nmemb < 2 || size <= 0)\n return;\n\n top = (uint8_t *)base + (k < nmemb ? k : nmemb) * size;\n sp->base = (uint8_t *)base;\n sp->last = (uint8_t *)base + (nmemb - 1) * size;\n sp++;\n while (sp > stack) {\n --sp;\n lb = sp->base;\n ub = sp->last;\n while (lb < ub && lb < top) {\n /* select middle element as pivot and exchange with 1st element */\n size_t offset = (ub - lb) >> 1;\n p = lb + offset - offset % size;\n exchange_bytes(lb, p, size);\n\n /* partition into two segments */\n for (i = lb + size, j = ub;; i += size, j -= size) {\n while (i < j && compar(lb, i) > 0)\n i += size;\n while (j >= i && compar(j, lb) > 0)\n j -= size;\n if (i >= j)\n break;\n exchange_bytes(i, j, size);\n }\n /* move pivot where it belongs */\n exchange_bytes(lb, j, size);\n\n /* keep processing smallest segment, and stack largest */\n if (j - lb <= ub - j) {\n sp->base = j + size;\n sp->last = ub;\n sp++;\n ub = j - size;\n } else {\n sp->base = lb;\n sp->last = j - size;\n sp++;\n lb = j + size;\n }\n }\n }\n}\n\nint int_cmp(const void *a, const void *b) {\n int aa = *(const int *)a;\n int bb = *(const int *)b;\n return (aa > bb) - (aa < bb);\n}\n\n#define ARRAY_SIZE 50000\n\nint array[ARRAY_SIZE];\n\nint main(void) {\n int i;\n for (i = 0; i < ARRAY_SIZE; i++) {\n array[i] = ARRAY_SIZE - i;\n }\n qsort_select(array, ARRAY_SIZE, sizeof(*array), int_cmp, 50);\n for (i = 0; i < 50; i++) {\n printf(\"%d%c\", array[i], i + 1 == 50 ? '\\n' : ',');\n }\n return 0;\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/52016431", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-3"}}
{"text": "Q: What is eating up my disk space? I have very recently installed Ubuntu 15.10. I have been watching the available amount of memory over two days, and i noticed that the free memory goes on decreasing at a slow rate. Initially the used memory was 5GB, Then it went on increasing to 6 to 6.5 and now it stands around 6.8. I haven't installed anything significant over this period (except some small packages worth a few MBs) .My home folder is just few 100kbs. What is eating up my disk space? How can find out if something is going on?\n\nA: The indicated amount seems to be .deb cache in majority. Issue this command: \nsudo apt-get clean\n\nand after that check again the disk usage.\n\nA: You can find out how much space sub-directories occupy using the following command:\nsudo du -hxd 1 YOUR_PATH 2>/dev/null | sort -hr\n\nWhat it does:\n\n\n*\n\n*sudo: run the du command as root - only needed/recommended if you want to list stuff outside your own home directory.\n\n*du: disk usage analyzing tool. Arguments:\n\n\n*\n\n*-h: use human readable numeric output (i.e. 2048 bytes = 2K)\n\n*-x: stay on the same file system, do not list directories which are just mounted there\n\n*-d 1: display recursion depth is set to 1, that means it will only print the given directory and the direct subdirectories.\n\n*YOUR_PATH: The path which should be analyzed. Change this to whatever path you want.\n\n*2>/dev/null: we do not want error output (e.g. from when it tries to get the size of virtual files), so we pipe that to the digital nirvana a.k.a. /dev/null.\n\n\n*|: use the output of the previous command as input for the next command\n\n*sort: sort the input. Arguments:\n\n\n*\n\n*-h: recognize numbers like 2K and sort them according to their real value\n\n*-r: reversed order: print the largest numbers first\n\n\n\nExample for my file system root /:\n$ sudo du -hxd 1 / 2>/dev/null | sort -hr\n5,7G /\n4,0G /usr\n1,3G /var\n358M /lib\n49M /opt\n15M /etc\n13M /sbin\n13M /bin\n840K /tmp\n32K /root\n16K /lost+found\n8,0K /media\n4,0K /srv\n4,0K /mnt\n4,0K /lib64\n4,0K /cdrom\n\nNote that the given directory's total size is also included, not only the subdirectories.\n", "meta": {"language": "en", "url": "https://askubuntu.com/questions/725797", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Get values with no repeated data I have a query like this:\nSELECT\n P.LegacyKey\n ,D.DesignNumber\n FROM tbl1 AS [SO]\n GROUP BY D.DesignNumber,P.LegacyKey\n ORDER BY LegacyKey\n\nit returning values like:\n+-----------+--------------+\n| LegacyKey | DesignNumber |\n+-----------+--------------+\n| 17134 | 1 |\n| 17134 | 2 |\n| 18017 | 7 |\n+-----------+--------------+\n\nThat I want to do is to find duplicate LegacyKeys and get only values who legacyKey is exist one time, so I use HAVING COUNT:\nSELECT\n P.LegacyKey\n ,D.DesignNumber\n , COUNT([P].[LegacyKey])\n FROM tbl1 AS [SO]\n GROUP BY D.DesignNumber,P.LegacyKey\n HAVING COUNT([P].[LegacyKey]) = 1\n ORDER BY LegacyKey\n\nBut this is returning bad data, because it is returning LegacyKey = 17134 again and desire result is to get values where LegacyKey exists one time.\nSo desire result should be only\n 18017 | 7 \n\nWhat am I doing wrong?\n\nA: You can simply do:\nSELECT P.LegacyKey, MAX(D.DesignNumber) as DesignNumber\nFROM tbl1 AS [SO]\nGROUP BY P.LegacyKey\nHAVING COUNT(DISTINCT D.DesignNumber) = 1;\nORDER BY LegacyKey;\n\nNo subquery is necessary.\n\nA: You need something like this:\nselect t2.LegacyKey, t2.DesignNumber\nfrom\n(\n select t.LegacyKey \n from tbl1 t\n group by t.LegacyKey \n having count(t.LegacyKey ) = 1\n)x\njoin tbl1 t2 on x.LegacyKey = t2.LegacyKey\n\nor\nselect t2.LegacyKey, t2.DesignNumber\nfrom tbl1 t2\nwhere t2.LegacyKey in\n(\n select t.LegacyKey \n from tbl1 t\n group by t.LegacyKey \n having count(t.LegacyKey ) = 1\n)\n\n\nA: You could try this \nNB - This is untested\nSELECT * \nFROM (\n SELECT\n P.LegacyKey AS LegacyKey,\n D.DesignNumber AS DesignNumber,\n COUNT([P].[LegacyKey]) AS cnt\n FROM tbl1 AS [SO]\n GROUP BY D.DesignNumber,P.LegacyKey\n HAVING COUNT([P].[LegacyKey]) = 1\n ) a\nWHERE COUNT() OVER (PARTITION BY LegacyKey) = 1\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/54993000", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: @IBDesignable doesn't work in \"old\" project I have UIView subclass, for example, this:\n@IBDesignable\nclass GradientView: UIView {\n\n @IBInspectable var firstColor: UIColor = UIColor.red\n @IBInspectable var secondColor: UIColor = UIColor.green\n\n @IBInspectable var vertical: Bool = true\n\n override func awakeFromNib() {\n super.awakeFromNib()\n\n applyGradient()\n }\n\n func applyGradient() {\n let colors = [firstColor.cgColor, secondColor.cgColor]\n\n let layer = CAGradientLayer()\n layer.colors = colors\n layer.frame = self.bounds\n layer.startPoint = CGPoint(x: 0, y: 0)\n layer.endPoint = vertical ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0)\n\n self.layer.addSublayer(layer)\n }\n\n override func prepareForInterfaceBuilder() {\n super.prepareForInterfaceBuilder()\n applyGradient()\n }\n}\n\nIt successfully renders in Interface Builder for a new project, but it doesn't work for my \"old\" project. \nDoes anyone know why it happens?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/45217918", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: How do I refer to the people living in the particular city? Is it random always? Where do demonyms come from? At times they take -ite, some times -an, -er and this one is jaw-dropping '-siders!'\n\nA person living in New York is a New Yorker (-er) A person living in Delhi is Delhiite (-ite) A person living in Sydney is Sydneysider (-sider -OMG! Really?) A person living in Las Vegas is Las Vegan (-an)\n\nThere are innumerable cities across the world and remembering a demonym for each of them does not seem practical. \nI don't get demonyms without searching them on the Internet (and trust me, even after searching I fail to get them for some cities' residents!). \nThis becomes further difficult when the city name is long - say St. Louis, Amsterdam, Rio de Janeiro (Cariocas -full marks who knew this!) and many more. \nIs there any way we can assume/know the demonym of the city by looking at its spelling?\n\nA: Is there a hard and fast rule? Sadly, no. But there is a rule of thumb--which means it works, except when it doesn't.\nFirst: if the city is outside of the United States, US English usually (but not always) uses the naming convention of the native country. So \"Liverpudlian\" and \"Muenchner\" don't follow these rules; you need to learn that country's rules.\nWithin the United States, look at the sound (not the spelling!) of the last syllable of the city's name.\nDoes it end in a vowel sound? Add -n or -an.\n\n\n*\n\n*Atlantan\n\n*Cincinattian\n\n*Kenoshan\n\n*Pennsylvanian\n\n\nDoes it end in a hard d or k? Add -er.\n\n\n*\n\n*New Yorker\n\n*Oaklander\n\n*Portlander\n\n*Salt Laker\n\n\nDoes it end in an -l, or -r sound? Consider adding -ite.\n\n\n*\n\n*Seattleite\n\n*New Hampshirite\n\n\nDoes it end in an -s sound preceded by a schwa? Replace the s with an n.\n\n\n*\n\n*Kansan\n\n*Texan\n\n\nFor all other consonants, the most common rule is to add an -ian \n\n\n*\n\n*Oregonian\n\n*Bostonian\n\n*Knoxvillian\n\n\nAs always with English, there are then a ton of exceptions that you just have to learn.\n", "meta": {"language": "en", "url": "https://ell.stackexchange.com/questions/21370", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "4"}}
{"text": "Q: Passing object messages in Azure Queue Storage I'm trying to find a way to pass objects to the Azure Queue. I couldn't find a way to do this.\nAs I've seen I can pass string or byte array, which is not very comfortable for passing objects.\nIs there anyway to pass custom objects to the Queue?\nThanks!\n\nA: You can use the following classes as example:\n [Serializable]\n public abstract class BaseMessage\n {\n public byte[] ToBinary()\n {\n BinaryFormatter bf = new BinaryFormatter();\n byte[] output = null;\n using (MemoryStream ms = new MemoryStream())\n {\n ms.Position = 0;\n bf.Serialize(ms, this);\n output = ms.GetBuffer();\n }\n return output;\n }\n\n public static T FromMessage(CloudQueueMessage m)\n {\n byte[] buffer = m.AsBytes;\n T returnValue = default(T);\n using (MemoryStream ms = new MemoryStream(buffer))\n {\n ms.Position = 0;\n BinaryFormatter bf = new BinaryFormatter();\n returnValue = (T)bf.Deserialize(ms);\n }\n return returnValue;\n }\n }\n\nThen a StdQueue (a Queue that is strongly typed):\n public class StdQueue where T : BaseMessage, new()\n {\n protected CloudQueue queue;\n\n public StdQueue(CloudQueue queue)\n {\n this.queue = queue;\n }\n\n public void AddMessage(T message)\n {\n CloudQueueMessage msg =\n new CloudQueueMessage(message.ToBinary());\n queue.AddMessage(msg);\n }\n\n public void DeleteMessage(CloudQueueMessage msg)\n {\n queue.DeleteMessage(msg);\n }\n\n public CloudQueueMessage GetMessage()\n {\n return queue.GetMessage(TimeSpan.FromSeconds(120));\n }\n }\n\nThen, all you have to do is to inherit the BaseMessage:\n[Serializable]\npublic class ParseTaskMessage : BaseMessage\n{\n public Guid TaskId { get; set; }\n\n public string BlobReferenceString { get; set; }\n\n public DateTime TimeRequested { get; set; }\n}\n\nAnd make a queue that works with that message:\nCloudStorageAccount acc;\n if (!CloudStorageAccount.TryParse(connectionString, out acc))\n {\n throw new ArgumentOutOfRangeException(\"connectionString\", \"Invalid connection string was introduced!\");\n }\n CloudQueueClient clnt = acc.CreateCloudQueueClient();\n CloudQueue queue = clnt.GetQueueReference(processQueue);\n queue.CreateIfNotExist();\n this._queue = new StdQueue(queue);\n\nHope this helps!\n\nA: Extension method that uses Newtonsoft.Json and async\n public static async Task AddMessageAsJsonAsync(this CloudQueue cloudQueue, T objectToAdd)\n {\n var messageAsJson = JsonConvert.SerializeObject(objectToAdd);\n var cloudQueueMessage = new CloudQueueMessage(messageAsJson);\n await cloudQueue.AddMessageAsync(cloudQueueMessage);\n }\n\n\nA: I like this generalization approach but I don't like having to put Serialize attribute on all the classes I might want to put in a message and derived them from a base (I might already have a base class too) so I used...\nusing System;\nusing System.Text;\nusing Microsoft.WindowsAzure.Storage.Queue;\nusing Newtonsoft.Json;\n\nnamespace Example.Queue\n{\n public static class CloudQueueMessageExtensions\n {\n public static CloudQueueMessage Serialize(Object o)\n {\n var stringBuilder = new StringBuilder();\n stringBuilder.Append(o.GetType().FullName);\n stringBuilder.Append(':');\n stringBuilder.Append(JsonConvert.SerializeObject(o));\n return new CloudQueueMessage(stringBuilder.ToString());\n }\n\n public static T Deserialize(this CloudQueueMessage m)\n {\n int indexOf = m.AsString.IndexOf(':');\n\n if (indexOf <= 0)\n throw new Exception(string.Format(\"Cannot deserialize into object of type {0}\", \n typeof (T).FullName));\n\n string typeName = m.AsString.Substring(0, indexOf);\n string json = m.AsString.Substring(indexOf + 1);\n\n if (typeName != typeof (T).FullName)\n {\n throw new Exception(string.Format(\"Cannot deserialize object of type {0} into one of type {1}\", \n typeName,\n typeof (T).FullName));\n }\n\n return JsonConvert.DeserializeObject(json);\n }\n }\n}\n\ne.g.\nvar myobject = new MyObject();\n_queue.AddMessage( CloudQueueMessageExtensions.Serialize(myobject));\n\nvar myobject = _queue.GetMessage().Deserialize();\n\n\nA: In case the storage queue is used with WebJob or Azure function (quite common scenario) then the current Azure SDK allows to use POCO object directly. See examples here:\n\n\n*\n\n*https://learn.microsoft.com/en-us/sandbox/functions-recipes/queue-storage\n\n*https://github.com/Azure/azure-webjobs-sdk/wiki/Queues#trigger\nNote: The SDK will automatically use Newtonsoft.Json for serialization/deserialization under the hood.\n\nA: I liked @Akodo_Shado's approach to serialize with Newtonsoft.Json. I updated it for Azure.Storage.Queues and also added a \"Retrieve and Delete\" method that deserializes the object from the queue.\npublic static class CloudQueueExtensions\n{\n public static async Task AddMessageAsJsonAsync(this QueueClient queueClient, T objectToAdd) where T : class\n {\n string messageAsJson = JsonConvert.SerializeObject(objectToAdd);\n BinaryData cloudQueueMessage = new BinaryData(messageAsJson);\n await queueClient.SendMessageAsync(cloudQueueMessage);\n }\n\n public static async Task RetreiveAndDeleteMessageAsObjectAsync(this QueueClient queueClient) where T : class\n {\n\n QueueMessage[] retrievedMessage = await queueClient.ReceiveMessagesAsync(1);\n if (retrievedMessage.Length == 0) return null;\n string theMessage = retrievedMessage[0].MessageText;\n T instanceOfT = JsonConvert.DeserializeObject(theMessage);\n await queueClient.DeleteMessageAsync(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);\n\n return instanceOfT;\n }\n}\n\nThe RetreiveAndDeleteMessageAsObjectAsync is designed to process 1 message at time, but you could obviously rewrite to deserialize the full array of messages and return a ICollection or similar.\n\nA: That is not right way to do it. queues are not ment for storing object. you need to put object in blob or table (serialized).\nI believe queue messgae body has 64kb size limit with sdk1.5 and 8kb wih lower versions.\nMessgae body is ment to transfer crutial data for workera that pick it up only.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/8550702", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "28"}}
{"text": "Q: Help needed renaming custom post I really have very little Wordpress knowledge and I need help with the following:\nI have a theme which uses a custom post called 'services'. I needed another custom post created which worked exactly the same as services so I went through all the code and copied and pasted wherever I found references to services and changed it to \"signage\". This worked ok, however on the WP admin screen, \"signage\" is called \"posts\" as is the original \"posts\", and I cant work out how to change the name to signage. I have been able to change the original \"posts\" name but not the custom post.\n\nA: It could be the 'name' in the labels array of the register post type. It would be much easier to help if you can show us your code.\n", "meta": {"language": "en", "url": "https://wordpress.stackexchange.com/questions/116728", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}}
{"text": "Q: How to add FTP site in IIS 7 in Windows Vista Home premium edition How to add the FTP server in IIS 7 using Windows vista Home Premium Edition?\n\nA: Please check if FTP 7.5 can be used on your Windows Vista machine, http://www.iis.net/expand/FTP\nIf not, FileZilla is a free alternative, http://filezilla-project.org/download.php?type=server\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/2524250", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Unable to install any program Total newbie here, I installed Kubuntu about three days ago and have been trying to install some programmes, to date no success. No matter what I try to install I get the same error. I would be very grateful if someone could explain what is happening and how to resolve it, or point me to a document that can help.\nThanks in advance for your help,\nNoel \nsudo apt-get install muon\n[sudo] password for nleric: \nReading package lists... Done\nBuilding dependency tree \nReading state information... Done\nSome packages could not be installed. This may mean that you have\nrequested an impossible situation or if you are using the unstable\ndistribution that some required packages have not yet been created\nor been moved out of Incoming.\nThe following information may help to resolve the situation:\n\nThe following packages have unmet dependencies:\n muon : Depends: apt-xapian-index but it is not going to be installed\nE: Unable to correct problems, you have held broken packages.\n\n\nA: the package \"apt-xapian-index\" is in the universe repository since Ubuntu 16.04 Xenial (see http://packages.ubuntu.com/xenial/apt-xapian-index). Before Ubuntu 16.04 Xenial the package \"apt-xapian-index\" was in the main repository, so it was always available, even if the user had the \"universe\" repository disabled. It's not the case anymore.\nTo confirm what is above just run the following:\napt-cache policy apt-xapian-index\n\nIf the result is not available it's because apt-get can't find it in the present repositories present in the file /etc/apt/sources.list.\nMy guess is that you have removed/disabled the universe repository from your APT /etc/apt/sources.list file. Make sure to add \"universe\" at the end of the the lines starting with \"deb\" in that file. Example, change the following line to have the universe repository enabled, in the file /etc/apt/sources.list file:\ndeb http://archive.ubuntu.com/ubuntu/ xenial main\n\nTo something like (add the last word in the line):\ndeb http://archive.ubuntu.com/ubuntu/ xenial main universe\n\nThen update apt-get repositories:\nsudo apt-get update\n\nApt-get will update its sources of available packages, now with the universe repository enabled. Then try to fix the problem:\nsudo apt-get install -f\n\n", "meta": {"language": "en", "url": "https://askubuntu.com/questions/796482", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: NLog not creating a log file inside AWS ec2 Linux I have a .net core application in AWS ec2 linux and it does NOT create a log file. The application on AWS ec2 linux is published with Deployment Mode: Self-contained and Target Runtime: linux-x64.\nI tried it on windows and it does create a log file but somehow it's not working in AWS ec2 linux.\nHeres what I did.\n\n\n*\n\n*Open ubuntu machine terminal (CLI) and Go to the project directory\n\n*Provide execute permissions: chmod 777 ./appname\n\n*Execute application\n\n*./appname\nNote: It displays the Hello World.\npublic static void Main(string[] args)\n {\n try\n {\n using (var logContext = new LogContextHelper(null, \"MBP\", \"MBP\",\n new JObject() {\n { \"ASD\", \"asd\" },\n { \"ZXC\", \"asd\" },\n { \"QWE\", \"asd\" },\n { \"POI\", \"\" }\n }, setAsContextLog: true))\n { }\n }\n catch (Exception e)\n {\n Console.WriteLine(\"Error: {0}\", e);\n }\n //sample s = new sample(\"consuna\") { objectinitial = \"objuna\"};\n\n\n Console.WriteLine(\"Hello World!\");\n Console.ReadLine();\n }\n}\n\n Here is the NLog.config\n\n\n \n \n\n \n\n \n \n\n \n\n \n \n \n \n\n\n I expect that it will create a log file with logs on it just like on windows.\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/57800735", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: EditText length with \"exceptions\" I have an EditText and I'd like to set maxLength to four numbers (in range -9999 to 9999). Problem is that if I setandroid:maxLength=\"4\" in xml I can write there e.q \"9999\" but it doesn't accept \"-9999\" because of length (5 char). Is there any opportunity how to solve it (programatically or anyhow)\nThanks\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/36794789", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Understanding hashCode(), equals() and toString() in Java I am beginner in Java and although I have a look at several questions and answers in SO, I am not sure if I completely understand the usage of hashCode(), equals() and toString() in Java. I encountered the following code in a project and want to understand the following issues:\n1. Is it meaningful to define these methods and call via super like return super.hashCode()?\n2. Where should we defines these three methods? For each entity? Or any other place in Java?\n3. Could you please explain me the philosophy of defining these 3 (or maybe similar ones that I have not seen before) in Java?\n@Entity\n@SequenceGenerator(name = \"product_gen\", sequenceName = \"product_id_seq\")\n@Table\n@Getter\n@Setter\n@ToString(callSuper = true)\n@NoArgsConstructor\npublic class Product extends BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"product_gen\")\n private long id;\n\n @Override\n public int hashCode() {\n return super.hashCode();\n }\n\n @Override\n public boolean equals(Object other) {\n return super.equals(other);\n }\n}\n\n\n\nA: *\n\n*toString() method returns the String representation of an Object. The default implementation of toString() for an object returns the HashCode value of the Object. We'll come to what HashCode is.\nOverriding the toString() is straightforward and helps us print the content of the Object. @ToString annotation from Lombok does that for us. It Prints the class name and each field in the class with its value.\nThe @ToString annotation also takes in configuration keys for various behaviours. Read here. callSuper just denotes that an extended class needs to call the toString() from its parent.\nhashCode() for an object returns an integer value, generated by a hashing algorithm. This can be used to identify whether two objects have similar Hash values which eventually help identifying whether two variables are pointing to the same instance of the Object. If two objects are equal from the .equals() method, they must share the same HashCode\n\n\n*They are supposed to be defined on the entity, if at all you need to override them.\n\n\n*Each of the three have their own purposes. equals() and hashCode() are majorly used to identify whether two objects are the same/equal. Whereas, toString() is used to Serialise the object to make it more readable in logs.\nFrom Effective Java:\n\nYou must override hashCode() in every class that overrides equals().\nFailure to do so will result in a violation of the general contract\nfor Object.hashCode(), which will prevent your class from functioning\nproperly in conjunction with all hash-based collections, including\nHashMap, HashSet, and HashTable.\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/69024813", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: How to reference a variable from one activity to another I'm trying to get a variable string and integer from\nMain2Activity.java to MainActivity.java \n\nBut the problem is that I don't want to use the:\nstartActivity(intent);\n\nFor it to work. I just want the information to be passed so I can use it in my current activity. Is there any way to do this? What am I missing. This is how my MainActivity looks like:\nbtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n TextView textView = (TextView)findViewById(R.id.textView7);\n\n Intent intent = getIntent();\n String A = intent.getStringExtra(\"Apples\");\n textView.setText(A);\n }\n});\n\nAnd my Main2Activty: \nIntent intent = new Intent(Main2Activity.this, MainActivity.class);\nintent.putExtra(\"Apples\", \"Red\");\n\nThanks for helping. Please only comment if you know what you're talking about. \n\nA: There is an other way, you can define a Class DataHolder and static variable for sharing variable between Activity\nExample\nclass DataHolder {\n public static String appleColor = \"\";\n}\n\nThen you can use like this:\nIntent intent = new Intent(Main2Activity.this, MainActivity.class);\nDataHolder.appleColor = \"RED\";\n\nThen \nbtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n TextView textView = (TextView)findViewById(R.id.textView7);\n\n Intent intent = getIntent();\n textView.setText(DataHolder.appleColor);\n }\n});\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/48392826", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Replace black boot screen with Purple ( default ) I used to have Gnome and Cinnamon on my laptop. Maybe because of that, the boot screen has changed to a black one than default Purple boot screen. I have since then upgraded to 16.04 from 14.04 and everything was good. \nBut recently, I am facing frequent boot failure. The boot screen flashes, goes transparent and shows some terminal like activities in the background. In the end, mostly it will say some process failed and I never get to the GUI.\nThis is happening so frequently that I am not able to use my PC at all. Will replacing black boot screen with Purple solve this problem ? If no, kindly suggest a solution for the same. Thanks.\nPS: I now use Unity alone with 16.04\n", "meta": {"language": "en", "url": "https://askubuntu.com/questions/855301", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Only grep img tags that contain a keyword, but not img tags that don't? Using grep/regex, I am trying to pull img tags out of a file. I only want img tags that contain 'photobucket' in the source, and I do not want img tags that do not contain photobucket.\nWant:\n\n\nDo Not Want:\n\n
We like photobucket
\n\nWhat I have tried:\n()\n\nThis did not work, because it pulled the second example in \"Do Not Want\", as there was a 'photobucket' and then a closing bracket. How can I only check for 'photobucket' up until the first closing bracket, and if photobucket is not contained, ignore it and move on?\n'photobucket' may be in different locations within the string.\n\nA: Just add a negation of > sign:\n(]*?photobucket.*?>)\n\nhttps://regex101.com/r/tZ9lI9/2\n\nA: grep -o ']*src=\"[^\"]*photobucket[^>]*>' infile\n\n-o returns only the matches. Split up:\n\n]* # Zero or more of \"not >\"\nsrc=\" # start of src attribute\n[^\"]* # Zero or more or \"not quotes\"\nphotobucket # Match photobucket\n[^>]* # Zero or more of \"not >\"\n> # Closing angle bracket\n\nFor the input file\n\n
We like photobucket
\n\n\n\n\n\n\nthis returns \n$ grep -o ']*src=\"[^\"]*photobucket[^>]*>' infile\n\n\n\n\nThe non-greedy .*? works only with the -P option (Perl regexes).\n\nA: Try the following:\n]*?photobucket[^>]*?>\n\nThis way the regex can't got past the '>'\n\nA: Try with this pattern:\n\n\nI\u00b4m not sure the characters admited by the name folders, but you just need add in the ranges \"[]\" before and after the \"photobucket\".\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/34882511", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Maximum number reached for Sharepoint 2007 number-type column In a SharePoint 2007 List, there is a number-type column which have a maximum value 1000. Suppose that the column is used for a auto-increment ID, what will happen if the ID exceed 1000?\nWill the next ID be reset to 0 or a error will occur?\n", "meta": {"language": "en", "url": "https://sharepoint.stackexchange.com/questions/19840", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Icon color of html5 input date picker How can I change the icon color of the native HTML5 date input ()?\nIs it possible to change the calendar icon color to HEX: #018bee or RGB: (1, 139, 238)? I saw a post saying that it was possible using filters, but I was unsuccessful.\n\nCodepen Example:\nhttps://codepen.io/gerisd/pen/VwPzqMy\nHTML:\n \n\nCSS:\n#deadline{\n width: 100%;\n min-width: 100px;\n border: none;\n height: 100%;\n background: none;\n outline: none;\n padding-inline: 5px;\n resize: none;\n border-right: 2px solid #dde2f1;\n cursor: pointer;\n color: #9fa3b1;\n text-align: center;\n}\n\ninput[type=\"date\"]::-webkit-calendar-picker-indicator {\n cursor: pointer;\n border-radius: 4px;\n margin-right: 2px;\n filter: invert(0.8) sepia(100%) saturate(10000%) hue-rotate(240deg);\n}\n\n\nA: Have you tried using webkit? I found a similar qustion from\nenter link description here\ntry this code from that question maybe:\n::-webkit-calendar-picker-indicator {\nfilter: invert(1);\n\n}\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/66974856", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: how can i display data in detail component from list component? i have problem to display data from one component to another component.\ni put the data which i fetch from the serve in prova and i display the list of all work. but I can't transfer the data that is on \"prova\" to another component to make the details visible through their own id.\nthis is my apicall service\n\nimport { Injectable } from '@angular/core';\nimport {HttpClient,HttpClientModule,HttpResponse} from '@angular/common/http';\nimport {Observable} from \"rxjs\";\nimport {map} from \"rxjs/operators\";\nimport {results} from \"./results\"\n\n\n@Injectable({\n providedIn: 'root'\n})\nexport class GetApiService {\n\n constructor(\n private http:HttpClient,\n ) { }\n\n\n apiCall():Observable\n {\n return this.http.get('https://www.themuse.com/api/public/jobs?category=Engineering&page=10')\n .pipe(map\n (\n (response:any) => {\n const data = response.results;\n console.log (data)\n return data ;\n \n }\n )\n );\n }\n}\n\nthis is my observable results\n export interface results\n {\n categories : any;\ncompany: string;\ncontents:string;\nid : number;\n levels:string;\n locations:string;\n model_type: string;\n name: string;\n refs: string;\n short_name: string;\n type:string;\n\n }\n\n\nthis is my component where are a list of works\nimport {results} from \"../results\";\nimport {GetApiService} from '../get-api.service';\nimport {switchMap} from \"rxjs/operators\";\nimport { Observable } from 'rxjs';\nimport { ActivatedRoute } from '@angular/router';\n\n\n@Component({\n selector: 'app-work-list',\n templateUrl: './work-list.component.html',\n styleUrls: ['./work-list.component.css']\n})\nexport class WorkListComponent implements OnInit {\n \n prova: results[]=[] ;\n item: any;\n selectedId: any ;\n constructor(\n private api :GetApiService,\n private route: ActivatedRoute,\n ) { }\n\n ngOnInit(){\n\n this.api.apiCall()\n .subscribe\n (\n (data:results[]) => {\n this.prova=data;\n console.log (data);\n\n });\n\n}\n}\n\nand the respectiv html connected by id\n
\n\nthis is the details where i can't display the selected work with its own details\nimport { ActivatedRoute } from '@angular/router';\nimport {results} from '../results';\nimport {GetApiService} from '../get-api.service';\nimport {switchMap} from \"rxjs/operators\";\n\n\n@Component({\nselector: 'app-work-details',\ntemplateUrl: './work-details.component.html',\nstyleUrls: ['./work-details.component.css']\n})\nexport class WorkDetailsComponent implements OnInit {\n@Input()\nitem: {\n categories: any;\n company: string;\n contents: string;\n id: number;\n levels: string;\n locations: string;\n model_type: string;\n name: string;\n refs: string;\n short_name: string;\n type: string;\n} | undefined;\n@Input ()\nprova: results[]=[];\nselectedId:string | undefined;\nconstructor(\n private route: ActivatedRoute,\n private api: GetApiService,\n) { }\n\nngOnInit():void {\n\n this.route.paramMap.subscribe\n (params => {\n this.item=this.prova[+params.get('selectedId')];\n\n**// it should be somewthing like this but prova is empty.**\n \n })\n ;\n}\n}\n\n\nA: It looks like you're mixing two different mechanisms?\nOne is of a parent -> child component relationship where you have your WorkDetailsComponent with an @Input() for prova, but at the same time, it looks like the component is its own page given your and the usage of this.route.paramMap.subscribe....\nFairly certain you can't have it both ways.\nYou either go parent -> child component wherein you pass in the relevant details using the @Input()s:\n
\n\nOR you go with the separate page route which can be done one of two ways:\n\n*\n\n*Use the service as a shared service; have it remember the state (prova) so that when the details page loads, it can request the data for the relevant id.\n\n\n*Pass the additional data through the route params\nFor 1, it would look something like:\nprivate prova: results[]; // Save request response to this as well\n\npublic getItem(id: number): results {\n return this.prova.find(x => x.id === id);\n}\n\nAnd then when you load your details page:\nngOnInit():void {\n\n this.route.paramMap.subscribe\n (params => {\n this.selectedId=+params.get('selectedId');\n\n this.item = this.service.getItem(this.selectedId);\n \n });\n}\n\nFor 2, it involves routing with additional data, something like this:\n..\n\nThis article shows the various ways of getting data between components in better detail.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/65146369", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Shifting elements of an array to the right I am aware that there are solutions for shifting arrays out there. However no solution works for me. The code should achieve the following:\nThe method shift(int[] array, int places) takes in an array, shifts the elements places - times to the right and replaces the \"leftover\" elements with \"0\".\nSo far I have:\npublic static int[] shiftWithDrop(int[] array, int places) {\n \n if (places == 0 || array == null) {\n return null;\n }\n for (int i = array.length-places-1; i >= 0; i-- ) {\n array[i+places] = array[i];\n array[i] = 0;\n } \n return array;\n}\n\nThis code does only somehow work, but it does not return the desired result. What am I missing?\n\nA: There are several issues in this code:\n\n*\n\n*It returns null when places == 0 -- without shift, the original array needs to be returned\n\n*In the given loop implementation the major part of the array may be skipped and instead of replacing the first places elements with 0, actually a few elements in the beginning of the array are set to 0.\n\nAlso it is better to change the signature of the method to set places before the vararg array.\nSo to address these issues, the following solution is offered:\npublic static int[] shiftWithDrop(int places, int ... array) {\n if(array == null || places <= 0) {\n return array;\n }\n for (int i = array.length; i-- > 0;) {\n array[i] = i < places ? 0 : array[i - places];\n }\n \n return array;\n} \n\nTests:\nSystem.out.println(Arrays.toString(shiftWithDrop(1, 1, 2, 3, 4, 5)));\nSystem.out.println(Arrays.toString(shiftWithDrop(2, new int[]{1, 2, 3, 4, 5})));\nSystem.out.println(Arrays.toString(shiftWithDrop(3, 1, 2, 3, 4, 5)));\nSystem.out.println(Arrays.toString(shiftWithDrop(7, 1, 2, 3, 4, 5)));\n\nOutput:\n[0, 1, 2, 3, 4]\n[0, 0, 1, 2, 3]\n[0, 0, 0, 1, 2]\n[0, 0, 0, 0, 0]\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/70135652", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Write Json Webhook to Cloud Firestore with Cloud Functions. Cloud Function Failed to Deploy. Function failed on loading user code I have a Webhook that delivers a complex JSON payload to my Cloud Function URL, and writes that JSON to collections & documents within my Cloud Firestore.\nI believe the Node.JS Runtime on Google Cloud Functions uses the Express Middleware HTTP framework.\nI have a WooCommerce Webhook that wants me to send a JSON to a URL, I believe this is a POST http request.\nI've used Webhook.site to test the Webhook, and it is displaying the correct JSON payload.\nDevelopers have suggested I use cloud functions to receive the JSON, parse the JSON and write it to the Cloud Firestore.\n// cloud-function-name = wooCommerceWebhook\nexports.wooCommerceWebhook = functions.https.onRequest(async (req, res) => {\n const payload = req.body;\n\n // Write to Firestore - People Collection\n await admin.firestore().collection(\"people\").doc().set({\n people_EmailWork: payload.billing.email,\n });\n\n// Write to Firestore - Volociti Collection\n await admin.firestore().collection(\"volociti\").doc(\"fJHb1VBhzTbYmgilgTSh\").collection(\"orders\").doc(\"yzTBXvGja5KBZOEPKPtJ\").collection(\"orders marketplace orders\").doc().set({\n ordersintuit_CustomerIPAddress: payload.customer_ip_address,\n });\n\n // Write to Firestore - Companies Collection\n await admin.firestore().collection(\"companies\").doc().set({\n company_AddressMainStreet: payload.billing.address_1,\n });\n return res.status(200).end();\n});\n\n\nI have the logs to my cloud function's failure to deploy if that is helpful.\nFunction cannot be initialized. Error: function terminated. Recommended action: inspect logs for termination reason. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging\n\nMy package.json:\n{\n \"name\": \"sample-http\",\n \"version\": \"0.0.1\"\n}\n\n\nA: You need to correctly define the dependency with the Firebase Admin SDK for Node.js, and initialize it, as shown below.\nYou also need to change the way you declare the function: exports.wooCommerceWebhook = async (req, res) => {...} instead of exports.wooCommerceWebhook = functions.https.onRequest(async (req, res) => {...});. The one you used is for Cloud Functions deployed through the CLI.\npackage.json\n{\n \"name\": \"sample-http\",\n \"version\": \"0.0.1\",\n \"dependencies\": { \"firebase-admin\": \"^9.4.2\" }\n}\n\nindex.js\nconst admin = require('firebase-admin')\nadmin.initializeApp();\n\nexports.wooCommerceWebhook = async (req, res) => { // SEE COMMENT BELOW\n const payload = req.body;\n\n // Write to Firestore - People Collection\n await admin.firestore().collection(\"people\").doc().set({\n people_EmailWork: payload.billing.email,\n });\n\n // Write to Firestore - Volociti Collection\n await admin.firestore().collection(\"volociti\").doc(\"fJHb1VBhzTbYmgilgTSh\").collection(\"orders\").doc(\"yzTBXvGja5KBZOEPKPtJ\").collection(\"orders marketplace orders\").doc().set({\n ordersintuit_CustomerIPAddress: payload.customer_ip_address,\n });\n\n // Write to Firestore - Companies Collection\n await admin.firestore().collection(\"companies\").doc().set({\n company_AddressMainStreet: payload.billing.address_1,\n });\n\n return res.status(200).end();\n };\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/69398084", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}}
{"text": "Q: Server-side redirect that transfers to another server From this question, I concluded that \n\nResponse.Redirect simply sends a message (HTTP 302) down to the\n browser.\nServer.Transfer happens without the browser knowing anything, the\n browser request a page, but the server returns the content of another. So doesn't send to another server.\n\nProblem:\nI have two servers, running IIS webserver. Server 1 receives api calls from clients, the clients have different databases, some on server 1, others on server 2.\nif the DB of the client is on Server 2, then his API call shall be redirected to server 2.\nNote that you can tell from the URL which server an API call should be routed\nWhat do I want?\nI want a server-side redirect method capable of redirecting to another server. in order to redirect the API calls.\n(And if there's any better way of doing what I'm asking for, like a proxy or some software, that big companies use, please let me know)\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/34425625", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Systemd service stdout incompletely captured by systemd journal I have a trivial systemd service (called \"testpath\") which simply prints some output to be captured by the journal. The journal is intermittently and unpredictably losing part of the output. The behaviour seems so erratic, and the test case so trivial, that it's hard to see how it could be any kind of intended behaviour.\nCan anyone offer a explanation in terms of expected systemd behaviour? Failing that, can anyone suggest a strategy to try to isolate this as a bug?\nThe service simply runs this script:\n% cat ~/tmp/testpath.bin \n#!/bin/bash\n\nsleep 0.1\nps -p $$\necho Echo statement.\n\nThe expected behaviour is that both the ps and echo outputs should appear in the journal at each system invocation. But instead the the ps output appears maybe half the time, and the echo output maybe 90% of the time. For example, manually running systemctl --user start testpath produced this journal:\n% journalctl --user -u testpath.service --follow\n\nOct 30 00:47:36 skierfe systemd[1518]: Started Testpath service.\nOct 30 00:47:36 skierfe testpath.bin[862530]: PID TTY TIME CMD\nOct 30 00:47:36 skierfe testpath.bin[862530]: 862527 ? 00:00:00 testpath.bin\nOct 30 00:47:36 skierfe testpath.bin[862527]: Echo statement.\nOct 30 00:53:17 skierfe systemd[1518]: Started Testpath service.\nOct 30 00:53:17 skierfe testpath.bin[863505]: Echo statement.\nOct 30 00:53:20 skierfe systemd[1518]: Started Testpath service.\nOct 30 00:53:21 skierfe testpath.bin[863545]: Echo statement.\nOct 30 00:53:23 skierfe systemd[1518]: Started Testpath service.\nOct 30 00:53:23 skierfe testpath.bin[863553]: Echo statement.\nOct 30 00:53:26 skierfe systemd[1518]: Started Testpath service.\nOct 30 00:53:26 skierfe testpath.bin[863558]: Echo statement.\nOct 30 00:53:28 skierfe systemd[1518]: Started Testpath service.\nOct 30 00:53:33 skierfe systemd[1518]: Started Testpath service.\nOct 30 00:53:33 skierfe testpath.bin[863577]: PID TTY TIME CMD\nOct 30 00:53:33 skierfe testpath.bin[863577]: 863574 ? 00:00:00 testpath.bin\nOct 30 00:53:33 skierfe testpath.bin[863574]: Echo statement.\nOct 30 00:53:37 skierfe systemd[1518]: Started Testpath service.\nOct 30 00:53:37 skierfe testpath.bin[863579]: Echo statement.\n\nThe unit file:\nskierfe:(f)..config/systemd/user % cat ~/.config/systemd/user/testpath.service\n[Unit]\nDescription = Testpath service\n\n[Service]\nExecStart = %h/tmp/testpath.bin\n\nThings I've considered or tried (none of which have helped):\n\n*\n\n*System resource contention: no, new Core i5 system with low loadavg\n\n*Rate-limit parameters per #774809: no, RateLimitInterval and RateLimitBurst are commented out in /etc/systemd/journald.conf, and the logging rate is trivial anyway\n\n*Extending or removing the sleep command (timing issues?)\n\n*Changing the service to Type=oneshot\n\n*Setting explicit StandardOutput=journal per #1089887\nNone of these have changed the behaviour.\nI'm on x86_64 Ubuntu 22.04 with current package updates.\nskierfe:(f)~/tmp % systemd --version\nsystemd 249 (249.11-0ubuntu3.6)\n+PAM +AUDIT +SELINUX +APPARMOR +IMA +SMACK +SECCOMP +GCRYPT +GNUTLS +OPENSSL +ACL +BLKID +CURL +ELFUTILS +FIDO2 +IDN2 -IDN +IPTC +KMOD +LIBCRYPTSETUP +LIBFDISK +PCRE2 -PWQUALITY -P11KIT -QRENCODE +BZIP2 +LZ4 +XZ +ZLIB +ZSTD -XKBCOMMON +UTMP +SYSVINIT default-hierarchy=unified\n\n", "meta": {"language": "en", "url": "https://serverfault.com/questions/1114346", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: How to get name of windows service from inside the service itself I have a bunch of win services written in .NET that use same exact executable with different configs. All services write to the same log file. However since I use the same .exe the service doesn't know its own service name to put in the log file.\nIs there a way my service can programatically retrieve its own name?\n\nA: Insight can be gained by looking at how Microsoft does this for the SQL Server service. In the Services control panel, we see:\nService name: MSSQLServer\nPath to executable: \"C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Binn\\sqlservr.exe\" -sMSSQLSERVER\nNotice that the name of the service is included as a command line argument. This is how it is made available to the service at run time. With some work, we can accomplish the same thing in .NET.\nBasic steps:\n\n\n*\n\n*Have the installer take the service name as an installer parameter.\n\n*Make API calls to set the command line for the service to include the service name.\n\n*Modify the Main method to examine the command line and set the ServiceBase.ServiceName property. The Main method is typically in a file called Program.cs.\n\n\nInstall/uninstall commands\nTo install the service (can omit /Name to use DEFAULT_SERVICE_NAME):\ninstallutil.exe /Name=YourServiceName YourService.exe\n\nTo uninstall the service (/Name is never required since it is stored in the stateSaver):\ninstallutil.exe /u YourService.exe\n\nInstaller code sample:\nusing System;\nusing System.Collections;\nusing System.Configuration.Install;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.ServiceProcess;\n\nnamespace TestService\n{\n [RunInstaller(true)]\n public class ProjectInstaller : Installer\n {\n private const string DEFAULT_SERVICE_NAME = \"TestService\";\n private const string DISPLAY_BASE_NAME = \"Test Service\";\n\n private ServiceProcessInstaller _ServiceProcessInstaller;\n private ServiceInstaller _ServiceInstaller;\n\n public ProjectInstaller()\n {\n _ServiceProcessInstaller = new ServiceProcessInstaller();\n _ServiceInstaller = new ServiceInstaller();\n\n _ServiceProcessInstaller.Account = ServiceAccount.LocalService;\n _ServiceProcessInstaller.Password = null;\n _ServiceProcessInstaller.Username = null;\n\n this.Installers.AddRange(new System.Configuration.Install.Installer[] {\n _ServiceProcessInstaller,\n _ServiceInstaller});\n }\n\n public override void Install(IDictionary stateSaver)\n {\n if (this.Context != null && this.Context.Parameters.ContainsKey(\"Name\"))\n stateSaver[\"Name\"] = this.Context.Parameters[\"Name\"];\n else\n stateSaver[\"Name\"] = DEFAULT_SERVICE_NAME;\n\n ConfigureInstaller(stateSaver);\n\n base.Install(stateSaver);\n\n IntPtr hScm = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);\n if (hScm == IntPtr.Zero)\n throw new Win32Exception();\n try\n {\n IntPtr hSvc = OpenService(hScm, this._ServiceInstaller.ServiceName, SERVICE_ALL_ACCESS);\n if (hSvc == IntPtr.Zero)\n throw new Win32Exception();\n try\n {\n QUERY_SERVICE_CONFIG oldConfig;\n uint bytesAllocated = 8192; // Per documentation, 8K is max size.\n IntPtr ptr = Marshal.AllocHGlobal((int)bytesAllocated);\n try\n {\n uint bytesNeeded;\n if (!QueryServiceConfig(hSvc, ptr, bytesAllocated, out bytesNeeded))\n {\n throw new Win32Exception();\n }\n oldConfig = (QUERY_SERVICE_CONFIG)Marshal.PtrToStructure(ptr, typeof(QUERY_SERVICE_CONFIG));\n }\n finally\n {\n Marshal.FreeHGlobal(ptr);\n }\n\n string newBinaryPathAndParameters = oldConfig.lpBinaryPathName + \" /s:\" + (string)stateSaver[\"Name\"];\n\n if (!ChangeServiceConfig(hSvc, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE,\n newBinaryPathAndParameters, null, IntPtr.Zero, null, null, null, null))\n throw new Win32Exception();\n }\n finally\n {\n if (!CloseServiceHandle(hSvc))\n throw new Win32Exception();\n }\n }\n finally\n {\n if (!CloseServiceHandle(hScm))\n throw new Win32Exception();\n }\n }\n\n public override void Rollback(IDictionary savedState)\n {\n ConfigureInstaller(savedState);\n base.Rollback(savedState);\n }\n\n public override void Uninstall(IDictionary savedState)\n {\n ConfigureInstaller(savedState);\n base.Uninstall(savedState);\n }\n\n private void ConfigureInstaller(IDictionary savedState)\n {\n _ServiceInstaller.ServiceName = (string)savedState[\"Name\"];\n _ServiceInstaller.DisplayName = DISPLAY_BASE_NAME + \" (\" + _ServiceInstaller.ServiceName + \")\";\n }\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern IntPtr OpenSCManager(\n string lpMachineName,\n string lpDatabaseName,\n uint dwDesiredAccess);\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern IntPtr OpenService(\n IntPtr hSCManager,\n string lpServiceName,\n uint dwDesiredAccess);\n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]\n private struct QUERY_SERVICE_CONFIG\n {\n public uint dwServiceType;\n public uint dwStartType;\n public uint dwErrorControl;\n public string lpBinaryPathName;\n public string lpLoadOrderGroup;\n public uint dwTagId;\n public string lpDependencies;\n public string lpServiceStartName;\n public string lpDisplayName;\n }\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool QueryServiceConfig(\n IntPtr hService,\n IntPtr lpServiceConfig,\n uint cbBufSize,\n out uint pcbBytesNeeded);\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool ChangeServiceConfig(\n IntPtr hService,\n uint dwServiceType,\n uint dwStartType,\n uint dwErrorControl,\n string lpBinaryPathName,\n string lpLoadOrderGroup,\n IntPtr lpdwTagId,\n string lpDependencies,\n string lpServiceStartName,\n string lpPassword,\n string lpDisplayName);\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool CloseServiceHandle(\n IntPtr hSCObject);\n\n private const uint SERVICE_NO_CHANGE = 0xffffffffu;\n private const uint SC_MANAGER_ALL_ACCESS = 0xf003fu;\n private const uint SERVICE_ALL_ACCESS = 0xf01ffu;\n }\n}\n\nMain code sample:\nusing System;\nusing System.ServiceProcess;\n\nnamespace TestService\n{\n class Program\n {\n static void Main(string[] args)\n {\n string serviceName = null;\n foreach (string s in args)\n {\n if (s.StartsWith(\"/s:\", StringComparison.OrdinalIgnoreCase))\n {\n serviceName = s.Substring(\"/s:\".Length);\n }\n }\n\n if (serviceName == null)\n throw new InvalidOperationException(\"Service name not specified on command line.\");\n\n // Substitute the name of your class that inherits from ServiceBase.\n\n TestServiceImplementation impl = new TestServiceImplementation();\n impl.ServiceName = serviceName;\n ServiceBase.Run(impl);\n }\n }\n\n class TestServiceImplementation : ServiceBase\n {\n protected override void OnStart(string[] args)\n {\n // Your service implementation here.\n }\n }\n}\n\n\nA: I use this function in VB\nPrivate Function GetServiceName() As String\n Try\n Dim processId = Process.GetCurrentProcess().Id\n Dim query = \"SELECT * FROM Win32_Service where ProcessId = \" & processId.ToString\n Dim searcher As New Management.ManagementObjectSearcher(query)\n Dim share As Management.ManagementObject\n For Each share In searcher.Get()\n Return share(\"Name\").ToString()\n Next share\n Catch ex As Exception\n Dim a = 0\n End Try\n Return \"DefaultServiceName\"\nEnd Function\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/773678", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "13"}}
{"text": "Q: Problems with quad in sympy Can someone explain, why:\nfrom sympy.mpmath import quad\nx, y = symbols('x y')\nf, g = symbols('f g', cls=Function)\nf = x\ng = x+1\nu_1 = lambda x: f + g\nquad(u_1,[-1,1])\n\ngives a mistake and\nfrom sympy.mpmath import quad\nx, y = symbols('x y')\nf, g = symbols('f g', cls=Function)\nf = x\ng = x+1\nu_1 = lambda x: x + x+1\nquad(u_1,[-1,1])\n\nworks fine?\nHow to make first version works right?\n\nA: lambda x: f + g\n\nThis is a function that takes in x and returns the sum of two values that do not depend on x. Whatever values f and g were before they stay that value. \nlambda x: x + x + 1\n\nThis is a function that returns the input value x as x+x+1. This function will depend on the input. \nIn python, unlike mathematics, when you evaluate the series of commands\na = 1\nb = a\na = 2\n\nthe value of b is 1.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/22326181", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: How to wrap ConcurrentDictionary in BlockingCollection? I try to implement a ConcurrentDictionary by wrapping it in a BlockingCollection but did not seem to be successful.\nI understand that one variable declarations work with BlockingCollection such as ConcurrentBag, ConcurrentQueue, etc.\nSo, to create a ConcurrentBag wrapped in a BlockingCollection I would declare and instantiate like this:\nBlockingCollection bag = new BlockingCollection(new ConcurrentBag());\n\nBut how to do it for ConcurrentDictionary? I need the blocking functionality of the BlockingCollection on both the producer and consumer side.\n\nA: Maybe you need a concurrent dictionary of blockingCollection\n ConcurrentDictionary> mailBoxes = new ConcurrentDictionary>();\n int maxBoxes = 5;\n\n CancellationTokenSource cancelationTokenSource = new CancellationTokenSource();\n CancellationToken cancelationToken = cancelationTokenSource.Token;\n\n Random rnd = new Random();\n // Producer\n Task.Factory.StartNew(() =>\n {\n while (true)\n {\n int index = rnd.Next(0, maxBoxes);\n // put the letter in the mailbox 'index'\n var box = mailBoxes.GetOrAdd(index, new BlockingCollection());\n box.Add(\"some message \" + index, cancelationToken);\n Console.WriteLine(\"Produced a letter to put in box \" + index);\n\n // Wait simulating a heavy production item.\n Thread.Sleep(1000);\n }\n });\n\n // Consumer 1\n Task.Factory.StartNew(() =>\n {\n while (true)\n {\n int index = rnd.Next(0, maxBoxes);\n // get the letter in the mailbox 'index'\n var box = mailBoxes.GetOrAdd(index, new BlockingCollection());\n var message = box.Take(cancelationToken);\n Console.WriteLine(\"Consumed 1: \" + message);\n\n // consume a item cost less than produce it:\n Thread.Sleep(50);\n }\n });\n\n // Consumer 2\n Task.Factory.StartNew(() =>\n {\n while (true)\n {\n int index = rnd.Next(0, maxBoxes);\n // get the letter in the mailbox 'index'\n var box = mailBoxes.GetOrAdd(index, new BlockingCollection());\n var message = box.Take(cancelationToken);\n Console.WriteLine(\"Consumed 2: \" + message);\n\n // consume a item cost less than produce it:\n Thread.Sleep(50);\n }\n });\n\n Console.ReadLine();\n cancelationTokenSource.Cancel();\n\nBy this way, a consumer which is expecting something in the mailbox 5, will wait until the productor puts a letter in the mailbox 5. \n\nA: You'll need to write your own adapter class - something like:\npublic class ConcurrentDictionaryWrapper\n : IProducerConsumerCollection>\n{\n private ConcurrentDictionary dictionary;\n\n public IEnumerator> GetEnumerator()\n {\n return dictionary.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n public void CopyTo(Array array, int index)\n {\n throw new NotImplementedException();\n }\n\n public int Count\n {\n get { return dictionary.Count; }\n }\n\n public object SyncRoot\n {\n get { return this; }\n }\n\n public bool IsSynchronized\n {\n get { return true; }\n }\n\n public void CopyTo(KeyValuePair[] array, int index)\n {\n throw new NotImplementedException();\n }\n\n public bool TryAdd(KeyValuePair item)\n {\n return dictionary.TryAdd(item.Key, item.Value);\n }\n\n public bool TryTake(out KeyValuePair item)\n {\n item = dictionary.FirstOrDefault();\n TValue value;\n return dictionary.TryRemove(item.Key, out value);\n }\n\n public KeyValuePair[] ToArray()\n {\n throw new NotImplementedException();\n }\n}\n\n\nA: Here is an implementation of a IProducerConsumerCollection collection which is backed by a ConcurrentDictionary. The T of the collection is of type KeyValuePair. It is very similar to Nick Jones's implementation, with some improvements:\npublic class ConcurrentDictionaryProducerConsumer\n : IProducerConsumerCollection>\n{\n private readonly ConcurrentDictionary _dictionary;\n private readonly ThreadLocal>> _enumerator;\n\n public ConcurrentDictionaryProducerConsumer(\n IEqualityComparer comparer = default)\n {\n _dictionary = new(comparer);\n _enumerator = new(() => _dictionary.GetEnumerator());\n }\n\n public bool TryAdd(KeyValuePair entry)\n {\n if (!_dictionary.TryAdd(entry.Key, entry.Value))\n throw new DuplicateKeyException();\n return true;\n }\n\n public bool TryTake(out KeyValuePair entry)\n {\n // Get a cached enumerator that is used only by the current thread.\n IEnumerator> enumerator = _enumerator.Value;\n while (true)\n {\n enumerator.Reset();\n if (!enumerator.MoveNext())\n throw new InvalidOperationException();\n entry = enumerator.Current;\n if (!_dictionary.TryRemove(entry)) continue;\n return true;\n }\n }\n\n public int Count => _dictionary.Count;\n public bool IsSynchronized => false;\n public object SyncRoot => throw new NotSupportedException();\n public KeyValuePair[] ToArray() => _dictionary.ToArray();\n public IEnumerator> GetEnumerator()\n => _dictionary.GetEnumerator();\n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n public void CopyTo(KeyValuePair[] array, int index)\n => throw new NotSupportedException();\n public void CopyTo(Array array, int index) => throw new NotSupportedException();\n}\n\npublic class DuplicateKeyException : InvalidOperationException { }\n\nUsage example:\nBlockingCollection> collection\n = new(new ConcurrentDictionaryProducerConsumer());\n\n//...\n\ntry { collection.Add(KeyValuePair.Create(key, item)); }\ncatch (DuplicateKeyException) { Console.WriteLine($\"The {key} was rejected.\"); }\n\nThe collection.TryTake method removes a practically random key from the ConcurrentDictionary, which is unlikely to be a desirable behavior. Also the performance is not great, and the memory allocations are significant. For these reasons I don't recommend enthusiastically to use the above implementation. I would suggest instead to take a look at the ConcurrentQueueNoDuplicates that I have posted here, which has a proper queue behavior.\nCaution: Calling collection.TryAdd(item); is not having the expected behavior of returning false if the key exists. Any attempt to add a duplicate key results invariably in a DuplicateKeyException. For an explanation look at the aforementioned other post.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/10736209", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "8"}}
{"text": "Q: Shaping json object rows[\n {0: c:[{0: {v:'2013'}, 1: {v: 'apple'},2: {v: '200'}}]},\n {1: c:[{0: {v:'2014'}, 1: {v: 'apple'},2: {v: '1000'}}]},\n {2: c:[{0: {v:'2013'}, 1: {v: 'orange'},2: {v: '200'}}]},\n {3: c:[{0: {v:'2014'}, 1: {v: 'orange'},2: {v: '1000'}}]}\n]\n\nI am trying to reshape it into something like this:\n[apple: {2013: '200', 2014: '1000'}, orange: {2013: '200', 2014: '1000'}]\n\nOR\n[\n apple: {\n 2013: {year: '2013', amount: '200'},\n 2014: {year: '2014', amount: '1000'}\n },\n orange: {\n 2013: {year: '2013', amount: '200'},\n 2014: {year: '2014', amount: '1000'}\n}]\n\nOR\napple: [{year:2013, amount:200},{year:2014,amount:1000}]\nI have tried playing with lodash's .map,.uniq,.reduce,.zipObject but I am still unable to figure it out.\n\nA: Used the following lodash functions:\nGet the name of fruits using _.map.\nuniqueFruitNames = Get the unique names by _.uniq and then sort them.\ndata2013 and data2014 = Use _.remove to get fruits of particular year and sort them respectively.\nUse _.zipObject to zip uniqueFruitsName and data2013\nuniqueFruitsName and data2014\nThen _.merge the two zipped Objects. \nvar dataSeries = _.map(mergedData, function(asset,key) { \n return { \n name: key, \n data: [fruit[0].amount, fruit[1].amount]\n }\n });\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/29170350", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Get all media from wp-json/wp/v2/media I'm struggling with a strange issue. I was pretty sure that I can use such a pattern to collect all media:\ndef get_all(url):\n all_results = []\n page = 1\n posts_url = \"{0}?per_page={1}&page={2}&order=asc\".format(url, 10, page)\n r = requests.get(posts_url)\n page_results = r.json()\n all_results.extend(page_results)\n while len(page_results) == 10:\n page += 1\n posts_url = \"{0}?per_page={1}&page={2}&order=asc\".format(url, 10, page)\n r = requests.get(posts_url)\n page_results = r.json()\n all_results.extend(page_results)\n\n return all_result\n\ndef get_all_media(url):\n return get_all(\"{0}wp/v2/media\".format(url)\n\nUnfortunately the:\nwp-json/wp/v2/media?per_page=10&page=6&order=asc\ncall returns only 8 elements, however there are pages number:\n7 - 8 elements,\n8 - 1 element\nIs it correct or my Wordpress instance is malfunctioning?\n//edit\nThanks to @SallyCJ I'm now familiar with X-WP-Total and X-WP-TotalPages headers.\nHowever, I'm still not convinced if this instance works correctly. The X-WP-TotalPages contains a correct value (8), but X-WP-Total is equal 71.\n\n*\n\n*6 pages with 10 elements = 60 elements\n\n*2 pages with 8 elements = 16\n\n*elements 1 page with 1 element = 1 element\n\nSum: 77 elements\nWhich is not equal to the X-WP-Total header.\n", "meta": {"language": "en", "url": "https://wordpress.stackexchange.com/questions/408487", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: In python, how do I print a table using double for loops? Here is my python code, \nfrom fractions import gcd \nprint \"| 2 3 4 5 6 7 8 9 10 11 12 13 14 15\"\nprint \"-----------------------------------\"\nxlist = range(2,16)\nylist = range(2,51)\nfor b in ylist:\n print b, \" | \"\n for a in xlist:\n print gcd(a,b)\n\nI'm having trouble printing a table that will display on the top row 2-15 and on the left column the values 2-50. With a gcd table for each value from each row and each column. \nHere is a sample of what I'm getting\n| 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n\n2 | \n2\n1\n2\n\nA: You can have it much more concise with list comprehension:\nfrom fractions import gcd\nprint(\" | 2 3 4 5 6 7 8 9 10 11 12 13 14 15\")\nprint(\"-----------------------------------------------\")\nxlist = range(2,16)\nylist = range(2,51)\n\nprint(\"\\n\".join(\" \".join([\"%2d | \" % b] + [(\"%2d\" % gcd(a, b)) for a in xlist]) for b in ylist))\n\nOutput:\n | 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n-----------------------------------------------\n 2 | 2 1 2 1 2 1 2 1 2 1 2 1 2 1\n 3 | 1 3 1 1 3 1 1 3 1 1 3 1 1 3\n 4 | 2 1 4 1 2 1 4 1 2 1 4 1 2 1\n 5 | 1 1 1 5 1 1 1 1 5 1 1 1 1 5\n 6 | 2 3 2 1 6 1 2 3 2 1 6 1 2 3\n 7 | 1 1 1 1 1 7 1 1 1 1 1 1 7 1\n 8 | 2 1 4 1 2 1 8 1 2 1 4 1 2 1\n 9 | 1 3 1 1 3 1 1 9 1 1 3 1 1 3\n10 | 2 1 2 5 2 1 2 1 10 1 2 1 2 5\n11 | 1 1 1 1 1 1 1 1 1 11 1 1 1 1\n12 | 2 3 4 1 6 1 4 3 2 1 12 1 2 3\n13 | 1 1 1 1 1 1 1 1 1 1 1 13 1 1\n14 | 2 1 2 1 2 7 2 1 2 1 2 1 14 1\n15 | 1 3 1 5 3 1 1 3 5 1 3 1 1 15\n16 | 2 1 4 1 2 1 8 1 2 1 4 1 2 1\n17 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n18 | 2 3 2 1 6 1 2 9 2 1 6 1 2 3\n19 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n20 | 2 1 4 5 2 1 4 1 10 1 4 1 2 5\n21 | 1 3 1 1 3 7 1 3 1 1 3 1 7 3\n22 | 2 1 2 1 2 1 2 1 2 11 2 1 2 1\n23 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n24 | 2 3 4 1 6 1 8 3 2 1 12 1 2 3\n25 | 1 1 1 5 1 1 1 1 5 1 1 1 1 5\n26 | 2 1 2 1 2 1 2 1 2 1 2 13 2 1\n27 | 1 3 1 1 3 1 1 9 1 1 3 1 1 3\n28 | 2 1 4 1 2 7 4 1 2 1 4 1 14 1\n29 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n30 | 2 3 2 5 6 1 2 3 10 1 6 1 2 15\n31 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n32 | 2 1 4 1 2 1 8 1 2 1 4 1 2 1\n33 | 1 3 1 1 3 1 1 3 1 11 3 1 1 3\n34 | 2 1 2 1 2 1 2 1 2 1 2 1 2 1\n35 | 1 1 1 5 1 7 1 1 5 1 1 1 7 5\n36 | 2 3 4 1 6 1 4 9 2 1 12 1 2 3\n37 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n38 | 2 1 2 1 2 1 2 1 2 1 2 1 2 1\n39 | 1 3 1 1 3 1 1 3 1 1 3 13 1 3\n40 | 2 1 4 5 2 1 8 1 10 1 4 1 2 5\n41 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n42 | 2 3 2 1 6 7 2 3 2 1 6 1 14 3\n43 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n44 | 2 1 4 1 2 1 4 1 2 11 4 1 2 1\n45 | 1 3 1 5 3 1 1 9 5 1 3 1 1 15\n46 | 2 1 2 1 2 1 2 1 2 1 2 1 2 1\n47 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n48 | 2 3 4 1 6 1 8 3 2 1 12 1 2 3\n49 | 1 1 1 1 1 7 1 1 1 1 1 1 7 1\n50 | 2 1 2 5 2 1 2 1 10 1 2 1 2 5\n\nThis works in Python2 and Python3. If you want zeros at the beginning of each one-digit number, replace each occurence of %2d with %02d. You probably shouldn't print the header like that, but do it more like this:\nfrom fractions import gcd\nxlist = range(2, 16)\nylist = range(2, 51)\nstring = \" | \" + \" \".join((\"%2d\" % x) for x in xlist)\nprint(string)\nprint(\"-\" * len(string))\n\nprint(\"\\n\".join(\" \".join([\"%2d | \" % b] + [(\"%2d\" % gcd(a, b)) for a in xlist]) for b in ylist))\n\nThis way, even if you change xlist or ylist, the table will still look good.\n\nA: Your problem is that the python print statement adds a newline by itself.\nOne solution to this is to build up your own string to output piece by piece and use only one print statement per line of the table, like such:\nfrom fractions import gcd \nprint \"| 2 3 4 5 6 7 8 9 10 11 12 13 14 15\"\nprint \"-----------------------------------\"\nxlist = range(2,16)\nylist = range(2,51)\nfor b in ylist:\n output=str(b)+\" | \" #For each number in ylist, make a new string with this number\n for a in xlist:\n output=output+str(gcd(a,b))+\" \" #Append to this for each number in xlist\n print output #Print the string you've built up\n\nExample output, by the way:\n| 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n-----------------------------------\n2 | 2 1 2 1 2 1 2 1 2 1 2 1 2 1\n3 | 1 3 1 1 3 1 1 3 1 1 3 1 1 3\n4 | 2 1 4 1 2 1 4 1 2 1 4 1 2 1\n5 | 1 1 1 5 1 1 1 1 5 1 1 1 1 5\n6 | 2 3 2 1 6 1 2 3 2 1 6 1 2 3\n7 | 1 1 1 1 1 7 1 1 1 1 1 1 7 1\n8 | 2 1 4 1 2 1 8 1 2 1 4 1 2 1\n9 | 1 3 1 1 3 1 1 9 1 1 3 1 1 3\n\n\nA: You can specify what kind of character end the line using the end parameter in print.\nfrom fractions import gcd \nprint(\"| 2 3 4 5 6 7 8 9 10 11 12 13 14 15\")\nprint(\"-----------------------------------\")\nxlist = range(2,16)\nylist = range(2,51)\nfor b in ylist:\n print(b + \" | \",end=\"\")\n for a in xlist:\n print(gcd(a,b),end=\"\")\n print(\"\")#Newline\n\nIf you are using python 2.x, you need to add from __future__ import print_function to the top for this to work.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/35260965", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Mongo/Monk count of objects in collection I'm 2 hours into Mongo/Monk with node.js and I want to count how many objects I have inserted into a collection but I can't see any docs on how to do this with Monk.\nUsing the below doesn't seem to return what I expect\nvar mongo = require('mongodb');\nvar monk = require('monk');\nvar db = monk('localhost:27017/mydb');\nvar collection = db.get('tweets');\ncollection.count() \n\nAny ideas?\n\nA: You need to pass a query and a callback. .count() is asynchronous and will just return a promise, not the actual document count value.\ncollection.count({}, function (error, count) {\n console.log(error, count);\n});\n\n\nA: Or you can use co-monk and take the rest of the morning off: \nvar monk = require('monk');\nvar wrap = require('co-monk');\nvar db = monk('localhost/test');\nvar users = wrap(db.get('users'));\nvar numberOfUsers = yield users.count({});\n\nOf course that requires that you stop doing callbacks... :)\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/22972121", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}}
{"text": "Q: matching div heights with jQuery trying to match div heights using jQuery, and it seems I can only get it to match the smallest height, but I want it to match the tallest column. from what I can tell the code should find tallest column? so I am very confused, here is what I am using \nfunction matchColHeights(col1, col2) {\n var col1Height = $(col1).height();\n var col2Height = $(col2).height();\n if (col1Height < col2Height) {\n $(col1).height(col2Height);\n } else {\n $(col2).height(col1Height);\n }\n}\n\n$(document).ready(function() {\n matchColHeights('#leftPanel', '#rightPanel');\n});\n\ntrying to do it here: http://www.tigerstudiodesign.com/blog/\n\nA: This should be able to set more than one column to maxheight. Just specify the selectors just like you would if you wanted to select all your elements with jQuery.\nfunction matchColHeights(selector){\n var maxHeight=0;\n $(selector).each(function(){\n var height = $(this).height();\n if (height > maxHeight){\n maxHeight = height;\n }\n });\n $(selector).height(maxHeight);\n};\n\n$(document).ready(function() {\n matchColHeights('#leftPanel, #rightPanel, #middlePanel');\n});\n\n\nA: one line alternative\n$(\".column\").height(Math.max($(col1).height(), $(col2).height()));\n\nCheck out this fiddle: http://jsfiddle.net/c4urself/dESx6/\nIt seems to work fine for me?\njavascript\nfunction matchColHeights(col1, col2) {\n var col1Height = $(col1).height();\n console.log(col1Height);\n var col2Height = $(col2).height();\n console.log(col2Height);\n if (col1Height < col2Height) {\n $(col1).height(col2Height);\n } else {\n $(col2).height(col1Height);\n }\n}\n\n$(document).ready(function() {\n matchColHeights('#leftPanel', '#rightPanel');\n});\n\ncss\n.column {\n width: 48%;\n float: left;\n border: 1px solid red;\n}\n\nhtml\n
Lorem ipsum...
\n\n\n\nA: When I load your site in Chrome, #leftPanel has a height of 1155px and #rightPanel has a height of 1037px. The height of #rightPanel is then set, by your matchColHeights method, to 1155px.\nHowever, if I allow the page to load, then use the Chrome Developer Tools console to remove the style attribute that sets an explicit height on #rightPanel, its height becomes 1473px. So, your code is correctly setting the shorter of the two columns to the height of the taller at the time the code runs. But subsequent formatting of the page would have made the other column taller.\n\nA: The best tut on this subject could be found here:\nhttp://css-tricks.com/equal-height-blocks-in-rows/\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/8595657", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Zebra printer ignores the command I have got Zebra GC420d. Using zebra 0.0.3a, this is an example of my issue:\nlabel = \"\"\"\n^XA\n^FO10,10\n^A0,40,40\n^FD\nHello World\n^FS\n^XZ\n\"\"\"\n\nfrom zebra import zebra\nz = zebra('Zebra_GC420d')\nz.output(label)\n\nThe printer ignores the command and prints the contents of the variable \"label\". How can I fix it?\n\nA: It sounds like the printer is not configured to understand ZPL. Look at this article to see how to change the printer from line-print mode (where it simply prints the data it receives) to ZPL mode (where it understands ZPL commands).\nCommand not being understood by Zebra iMZ320\nBasically, you may need to send this command:\n! U1 setvar \"device.languages\" \"zpl\"\nNotice that you need to include a newline character (or carriage return) at the end of this command. \n\nA: zebra 0.0.3a is for EPL2, Not for ZPL2 !!!!\nSee the site : https://pypi.python.org/pypi/zebra/\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/19790053", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: Node.js WebSocket server is only accepting one client from my local machine I have a really simple Node.js server that uses 'ws' for WebSockets, but it's only accepting one client in what I believe is a multi-client server.\nHere's literally the program I'm using to test it right now. Short and simple, but isn't working.\nconst WebSocket = require('ws');\nconst fs = require('fs');\nconst https = require('https');\n\nlet server = new https.createServer({\n key: fs.readFileSync(\"./ssl/private.key\"),\n cert: fs.readFileSync(\"./ssl/certificate.crt\"),\n ca: fs.readFileSync(\"./ssl/ca_bundle.crt\")\n}).listen(443);\n\nlet wss = new WebSocket.Server({\n noServer: true\n});\n\nserver.on(\"upgrade\", (request, socket, head) => {\n wss.handleUpgrade(request, socket, head, (ws) => {\n ws.onopen = (event) => {\n console.log(\"A client has connected\");\n };\n ws.onclose = (event) => {\n console.log(\"A client has disconnected\");\n }\n });\n});\n\nBoth clients are running the same code in Google Chrome (Also tested with firefox)\nCode:\n\n\n \n \n \n \n \n\n\nOne client will log the open connection, every other client will log a timeout, error, and close event. Thanks in advance\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/62316993", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Should a C++ temporary be constant? I have a C++ class that has the following interface:\nclass F {\npublic:\n F(int n, int d);\n // no other constructors/assignment constructors defined\n F& operator *= (const F&);\n F& operator *= (int);\n int n() const;\n int d() const;\n};\n\nAnd I have the following code:\nconst F a{3, 7};\nconst F b{5, 10};\nauto result = F{a} *= b; // How does this compile?\n\nUnder Visual Studio (VS) 2013, the commented line compiles without error. Under VS2015 , error C2678 is produced:\nerror C2678: binary '*=': no operator found \n which takes a left-hand operand of type 'const F' \n (or there is no acceptable conversion)\nnote: could be 'F &F::operator *=(const F &)'\nnote: or 'F &F::operator *=(int)'\nnote: while trying to match the argument list '(const F, const F)'\n\nMy expectation was that F{a} would create a non-const temporary copy of a to which operator *= (b) would be applied, after which the temporary object would be assigned to result. I did not expect the temporary to be a constant. Interestingly: auto result = F(a) *= b; compiles without error in VS2015, which I thought should be semantically the same.\nMy question is: which behaviour is correct VS2015 or VS2013 & why? \nMany thanks\n\nA: Visual Studio 2015 is not producing the correct result for:\nF{a}\n\nThe result should be a prvalue(gcc and clang both have this result) but it is producing an lvalue. I am using the following modified version of the OP's code to produce this result:\n#include \n\nclass F {\npublic:\n F(int n, int d) :n_(n), d_(d) {};\n F(const F&) = default ;\n F& operator *= (const F&){return *this; }\n F& operator *= (int) { return *this; }\n int n() const { return n_ ; }\n int d() const { return d_ ; }\n int n_, d_ ;\n};\n\ntemplate\nstruct value_category {\n static constexpr auto value = \"prvalue\";\n};\n\ntemplate\nstruct value_category {\n static constexpr auto value = \"lvalue\";\n};\n\ntemplate\nstruct value_category {\n static constexpr auto value = \"xvalue\";\n};\n\n#define VALUE_CATEGORY(expr) value_category::value\n\nint main()\n{\n const F a{3, 7};\n const F b{5, 10}; \n std::cout << \"\\n\" << VALUE_CATEGORY( F{a} ) << \"\\n\";\n}\n\nHat tip to Luc Danton for the VALUE_CATEGORY() code.\nVisual Studio using webcompiler which has a relatively recent version produces:\nlvalue\n\nwhich must be const in this case to produce the error we are seeing. While both gcc and clang (see it live) produce:\nprvalue\n\nThis may be related to equally puzzling Visual Studio bug std::move of string literal - which compiler is correct?. \nNote we can get the same issue with gcc and clang using a const F:\nusing cF = const F ;\nauto result = cF{a} *= b; \n\nso not only is Visual Studio giving us the wrong value category but it also arbitrarily adding a cv-qualifier.\nAs Hans noted in his comments to your question using F(a) produces the expected results since it correctly produces a prvalue.\nThe relevant section of the draft C++ standard is section 5.2.3 [expr.type.conv] which says:\n\nSimilarly, a simple-type-specifier or typename-specifier followed by a braced-init-list creates a temporary\n object of the specified type direct-list-initialized (8.5.4) with the specified braced-init-list, and its value is\n that temporary object as a prvalue.\n\nNote, as far as I can tell this is not the \"old MSVC lvalue cast bug\". The solution to that issue is to use /Zc:rvalueCast which does not fix this issue. This issue also differs in the incorrect addition of a cv-qualifier which as far as I know does not happen with the previous issue.\n\nA: My thoughts it's a bug in VS2015, because if you specify user defined copy constructor:\nF(const F&);\n\nor make variable a non-const code will be compiled successfully.\nLooks like object's constness from a transferred into newly created object.\n\nA: Visual C++ has had a bug for some time where an identity cast doesn't produce a temporary, but refers to the original variable.\nBug report here: identity cast to non-reference type violates standard \n\nA: From http://en.cppreference.com/w/cpp/language/copy_elision:\n\nUnder the following circumstances, the compilers are permitted to omit the \n copy- and move-constructors of class objects even if copy/move constructor \n and the destructor have observable side-effects.\n.......\nWhen a nameless temporary, not bound to any references, would be moved or \n copied into an object of the same type (ignoring top-level cv-\nqualification), the copy/move is omitted. When that temporary is \n constructed, it is constructed directly in the storage where it would \n otherwise be moved or copied to. When the nameless temporary is the \n argument of a return statement, this variant of copy elision is known as \n RVO, \"return value optimization\".\n\nSo the compiler has the option to ignore the copy (which in this case would act as an implicit cast to non-const type).\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/34478737", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "15"}}
{"text": "Q: Fontawesome is installed - icons do not appear After installing fontawesome, I copied the icon I wanted to appear in my word document from http://fontawesome.io/icons/ \nWhen I paste the icon in my word document, it does not appear. I tried various icons. Various signs appear, from vertical stripes to greek letters, yet no icons.\uf1cd \uf04b \uf1d0 \n\nA: If you want to be able to copy and paste an icon from Font Awesome after installing the font you need to do it from this page.\nFont Awesome Cheat Sheet\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/43324804", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-2"}}
{"text": "Q: satellizer req.headers.authorization not defined in nodejs demo I'am using satellizer to authenticate my app with backend using nodejs, but every http request doesn't attact req.headers.authorization, and i don't know why, please help me fix this, tks in advance\napp.js\nangular.module('userApp', ['angular-ladda','mgcrea.ngStrap', 'ui.router', 'satellizer', 'angular-loading-bar'])\n.config(function($httpProvider, $stateProvider, $urlRouterProvider, $authProvider, $locationProvider) {\n\n $stateProvider\n .state('/home', {\n url: '/',\n templateUrl: 'app/views/pages/home.html'\n })\n\n .state('/login', {\n url: '/login',\n templateUrl: 'app/views/pages/login.html',\n controller: 'LoginCtrl',\n controllerAs: 'login'\n })\n\n .state('/signup', {\n url: '/signup',\n templateUrl: 'app/views/pages/signup.html',\n controller: 'SignupCtrl',\n controllerAs: 'signup'\n })\n\n .state('users', {\n url: '/users',\n templateUrl: 'app/views/pages/user/all.html',\n controller: 'UserCtrl',\n controllerAs: 'user',\n resolve: {\n authenticated: function($q, $location, $auth) {\n var deferred = $q.defer();\n\n if (!$auth.isAuthenticated()) {\n $location.path('/login');\n } else {\n deferred.resolve();\n }\n\n return deferred.promise;\n }\n }\n });\n\n\n $authProvider.facebook({\n clientId: 'xxxxxxxxxxx'\n });\n\n $urlRouterProvider.otherwise('/');\n $locationProvider.html5Mode(true);\n\n});\n\nuserController.js\nangular.module('userApp')\n.controller('UserCtrl', function(User, $alert) {\n vm = this;\n\n vm.getAllUser = function() {\n vm.processing = true;\n User.all()\n .success(function(data) {\n vm.processing = true;\n vm.users = data;\n })\n .error(function(error) {\n $alert({\n content: error.message,\n animation: 'fadeZoomFadeDown',\n type: 'material',\n duration: 3\n });\n });\n };\n\n vm.getAllUser();\n});\n\nuserService.js\nangular.module('userApp')\n.factory('User', function($http) {\n return{\n all: function() {\n return $http.get('/api/all');\n }\n };\n});\n\nfunction for checking authentication before calling restfull api\nfunction ensureAuthenticated(req, res, next) {\nif (!req.headers.authorization) {\n return res.status(401).send({ message: 'Please make sure your request has an Authorization header' });\n}\n\nvar token = req.headers.authorization;\n\nvar payload = null;\ntry {\n payload = jwt.decode(token, config.TOKEN_SECRET);\n} catch(err) {\n return res.status(401).send({ message: err.message });\n}\nreq.user = payload.sub;\nnext();\n\n}\napi\napiRouter.get('/all', ensureAuthenticated, function(req, res) {\n User.find({}, function(err, users) {\n res.send(users);\n });\n});\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/31322571", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: kendo ui transport data is null Can anyone explain to me why the obj parameter in the httpGet values are null/undefined! I'm using vb so there equal to Nothing! I don't understand why I can get the correct values from the data. \nvar newGridDataSource = new kendo.data.DataSource({\n transport: {\n read: {\n url: \"/api/Stuff/\",\n dataType: \"json\",\n data: \n function(){\n\n return { name: \"Bob\" };\n }\n\n }\n }\n});\n\nMy visual basic code is\nStructure g\n Public name As String\nEnd Structure\n\n\n\nFunction returnGrid( obj As g) As HttpResponseMessage\n\n Return Request.CreateResponse(HttpStatusCode.OK)\nEnd Function\n\n\nA: You are sending a function as the data, I think you want the return of the function so you would need to call it by including parens after it:\nvar newGridDataSource = new kendo.data.DataSource({\n transport: {\n read: {\n url: \"/api/Stuff/\",\n dataType: \"json\",\n data: \n function(){ \n return { name: \"Bob\" };\n }()\n }\n }\n});\n\nBut that seems kind of silly when you could just do:\n data: { name: \"Bob\" }\n\n\nudpate\n\nYou can't get data FromBody with a GET request. Remove and the model binder will look in the query string for data and it should work.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/36611073", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: About Specifying EIGEN3_DIR variable not use My computer has multiple versions of the eigen library. I have an eigen3 in the /usr/include/ and another eigen3 in the /usr/local/. I use the set() command in cmakelists, but the compiler only uses the eigen library in the/usr/include directory. Here are my cmakelists.txt settings\n`\ncmake_minimum_required(VERSION 2.8.3)\nproject(cmake_test)\n\nset(EIGEN3_DIR \"/usr/local/eigen-3.3.9/share/eigen3/cmake/\")\nfind_package(Eigen3)\n\ninclude_directories(\n # \"/usr/local/eigen-3.3.9/include/eigen3/\"\n ${PROJECT_SOURCE_DIR}/include\n ${EIGEN3_INCLUDE_DIR}\n)\n\nmessage(\"EIGEN3_INCLUDE_DIR =======\" ${EIGEN3_DIR})\n\nmessage(\"EIGEN3_INCLUDE_DIR =======\" ${EIGEN3_INCLUDE_DIR})\n\nadd_executable(cmake_test src/main.cpp)\n\n`\nDoes anyone know where I went wrong\nI hope someone can tell me how cmake searches for header files, library files, and Search order of the find_ package() command\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/74689717", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: TYPO3 typoscript condition without log error I am trying to make a condition which does not produces errors in the log.\nTried:\n[request.getQueryParams() && request.getQueryParams()['tx_news_pi1'] && request.getQueryParams()['tx_news_pi1']['news'] > 0 && request.getQueryParams()['tx_news_pi1']['news'] in [857,858,913,914]]\n\nand\n[traverse(request.getQueryParams(), 'tx_news_pi/news') in [857,858,913,914]]\n\nboth give Unable to get an item of non-array\n\nA: I found out that an old condition still existed in a system template which caused the var/log/typo3_x.log entry. So the condition examples above are good.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/70507949", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: webpack2 | postcss build warning I have a postcss.config.js file:\nconst webpack = require('webpack');\nconst path = require('path');\n\nmodule.exports = {\n parser: 'postcss-scss',\n plugins: [\n require('postcss-smart-import')({\n addDependencyTo: webpack,\n path:\u00a0[\n path.resolve(__dirname, 'src/common'),\n path.resolve(__dirname, 'src/common/styles'),\n path.resolve(__dirname, 'src/app1'),\n path.resolve(__dirname, 'src/app2'),\n ]\n }),\n require('precss'),\n require('autoprefixer'),\n ]\n}\n\nin webpack.conf.js I have simple definition:\n{\n test: /\\.(scss|sass|css)$/,\n exclude: /node_modules/,\n use: [\n 'style-loader',\n 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]--[hash:base64:5]',\n 'postcss-loader'\n ]\n}\n\nDuring a build I get a warning:\nWARNING in ./~/css-loader?modules&importLoaders=1&localIdentName=[name]__[local]--[hash:base64:5]!./~/postcss-loader/lib!./src/common/shared/ui/Button.scss\n(Emitted value instead of an instance of Error) postcss-extend: /Users/kania/projects/app-frontend/src/common/shared/ui/Button.scss:22:5: @extend is being used in an anti-pattern (extending things not yet defined). This is your first and final warning\n@ ./src/common/shared/ui/Button.scss 4:14-210 13:2-17:4 14:20-216\n@ ./src/common/shared/ui/Button.tsx\n@ ./src/common/shared/ui/index.ts\n(...)\nIn Button.scss I have a very simple definitions:\n@import 'shared/styles/buttons';\n@import 'shared/styles/fonts';\n\n.buttonContainer {\n display: flex;\n}\n\n.button {\n @extend %smallFont;\n padding: 0 2.5rem;\n flex: 1;\n\n &.style_primary {\n @extend %buttonPrimary;\n }\n\n &.style_secondary {\n @extend %buttonSecondary;\n }\n\n &.style_tertiary {\n @extend %buttonTertiary;\n }\n}\n\nInside .button class I define 3 nested classes (&.style_primary &.style_secondary and &.style_tertiary). I found out if 2 of them are commented everything works. It looks like if I use more than one placeholder selector from one file it throws a warning...\nPlaceholders are defined in imported files, files exist on defined location.\nI would appreciate any hint, how to solve this issue.\nUsed packages:\n\n\n*\n\n*postcss-loader@^2.0.5\n\n*postcss-extend@^1.0.5\n\n*postcss-smart-import@^0.7.4\n\n*precss@^1.4.0 autoprefixer@^7.1.1\n\n*webpack@^2.5.1\n\n*webpack-dev-server@^2.4.5\nI use this command to run the build:\nwebpack-dev-server --hot --progress --config webpack.dev.config.js\n\nA: After some hours spent on searching the reason of warning and not built styles for everything after the warning, I finally found the cause.\nAnd the winner is:\nprecss@^1.4.0\n\nThis is old package, last changes were added 2 years ago. It is not even a package, just gathered plugins for postcss to process styles.\nI removed this package from my project and added few needed plugins postcss.conf.js:\nconst webpack = require('webpack');\nconst path = require('path');\n\nmodule.exports = {\n parser: 'postcss-scss',\n plugins: [\n require('postcss-smart-import')({\n addDependencyTo: webpack,\n path:\u00a0[\n path.resolve(__dirname, 'src/common'),\n path.resolve(__dirname, 'src/app1'),\n path.resolve(__dirname, 'src/app2'),\n ]\n }),\n require('postcss-advanced-variables'),\n require('postcss-mixins'),\n require('postcss-nested'),\n require('postcss-nesting'),\n require('postcss-extend'),\n require('autoprefixer'),\n ]\n};\n\nworks!\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/44242031", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: How to auto update line transition using d3.js How to automatically update line graph transition for the given json data,I had developed for the line graph,but i don't know how to transition or animation automatically update graph.\nTh below is the json object\nvar data=[\n {a: 43097, b: 1},\n {a: 43098, b: 3},\n {a: 43099, b: 4},\n {a: 43100, b: 8},\n {a: 43101, b: 5},\n {a: 43102, b: 5},\n {a: 43103, b: 3},\n {a: 43104, b: 2},\n {a: 43104, b: 5},\n {a: 43104, b: 8},\n {a: 43104, b: 5},\n {a: 43104, b: 7}\n ]\n\nUsing the above json object i am able draw a line graph by using d3.js\nBut, now i need to draw a line transition or animation \nI tried some code to do transition but i am unable to get the transition\nThe code is like below\nsetInterval(function (){\n var s=data.shift;\n data.push(s);\n animation();},1000)\n }\n\nI didn't get the trnsition\nCan any one please tell me the how to do transition \n\nA: There are some issues with your data. First, I think that your a parameter is constant for the last 5 entries, so the line would only plot the first one. \nFurther, the method animate() would not do anything to the line (unless you have somehow implemented it and not shown in your example). Also you need to update the axis domain, otherwise your line wouldn't be shown correctly.\nI have created a JSFiddle here so please have a look. Essentially, I cleaned your data and created a setInterval method as shown here:\nsetInterval(\n function (){\n // Append your new data, here I just add an increment to your a\n data.push(\n {\"a\":Number(parseFloat(d3.max(data, function(d){return d.a}))+1),\n \"b\":Math.random()*10\n });\n //Redraw the line\n svg.select(\".line\").transition().duration(50).attr(\"d\",line)\n //Recompute the axes domains\n x.domain(d3.extent(data, function(d) { return parseFloat(d.a); }));\n y.domain(d3.extent(data, function(d) { return parseFloat(d.b); }));\n // Redraw the axes\n svg.select('.x-axis').call(xAxis);\n svg.select('.y-axis').call(yAxis)\n},1000)\n\nHope this helps.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/28007120", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Why was Rand not able to heal Tam in The Eye of the world? In the Eye of the World, Edmond's Field is attacked by Trollocs, and the housed of Rand, Mat and Perrin are attacked exclusively.\nIn the attack, Tam is injured and Rand has to drag him in the litter overnight. He reaches the village, but Nynaeve declares that she will not be able to help him. However, Morraine was able to heal him.\nLater in the book, we learn that Rand is infact, The dragon Reborn and he can channel. Morraine concludes this to be true since Rand healed Bela because he was worried about the horse falling behind. \nWhy was he not able to heal Tam? He was worried sufficiently and fairly desperate. In the later books it is shown that he did much greater feats of channeling without knowing how.\n\nA: in one of the books Rand specifically says that Lew's Therin has little talent as a healer; in fact, even though he is as strong as a man can be in the One Power and can split his flows more ways than anyone except Egwene (12 for him, 14 for her) he is never mentioned as having any Talents.\n\nA: In The Eye of the World, when Tam is wounded, Rand has not yet started channeling, at least not in any viable way. Washing away Bela's fatigue was very simple and required little power compared to actually healing someone with a serious wound and infection and it didn't happen until after he had left Emond's field. In fact that was probably the first time that he actually channeled.\n\n\"It is during this journey that hints are given that Rand can channel; when he gets goose bumps on his arms when Moiraine channels near him and when the group are healed from their fatigue but Bela is perfect as Rand already healed the horse (for which he suffers a bout of reckless bravado with a trio of Whitecloaks). His first big use of saidin is when the Darkfriend Howal Gode tries to attack Rand and Mat. Rand blasts a hole in the wall, blinding Mat temporarily. He then suffers flu-like symptoms after this heavy use of the One Power.\"\n\n\nEven Nynaeve, who was an accomplished healer in her own right and had been unknowingly using the One Power for some time as a wilder could not heal Tam.\n\n\"She had been the youngest Wisdom the Two Rivers had ever had, and one of the most successful. She was said to be able to cure ailments no other Wisdom ever could and wounds that would leave a man maimed for life were sometimes gone without a scar [verify]. She was the only Wisdom in the Two Rivers within the span of the books who can truly Listen to the Wind.\"\n\n\nSo it stands to reason that at that time he did not have the power to heal his father no matter how worried or desperate he was and only later was able to perform great feats without understanding how.\nI hope this answers your question. Link to my info source below. Tai'shar Malkier!\nhttp://wot.wikia.com/wiki/\n\nA: Don't take for granted how tough it is to channel without any training. Rand manages to channel lightning in Four Kings in tEotW out of sheer desperation. It was life or death. And still, even after his sickness that follows, he didn't know what he did, nor could he repeat it. He doesn't actually consciously know how to channel until Asmodean trains him in tSR. And even once he's trained, he doesn't know how to heal. In fact, the only time he even tries to heal is when he tries to heal the serving maid of death with Callandor at the beginning of tSR (and obviously he fails). It doesn't seem to be one of his talents. Even when he \"breaks\" and becomes one with Lews Therin, gaining all of his skill and knowledge, he doesn't heal. Perhaps his prolonged proximity to Bela inadvertently sapped her of fatigue, but Moraine never explains how he was able to do that. But, even so, Tam wasn't fatigued. He was severely injured. Even if Rand had somehow managed to do the same with Tam as he had with Bela, healing his fatigue wouldn't have done much. \n\nA: I believe the imperfect healing of Tam by Morraine was on purpose.\nMorraine needed Rand to agree to leave the Two Rivers with her. I believe she could have healed Tam to full health no problem, but did just enough to make him recover but stay asleep. This was so he couldn't interfere with her plans.\n", "meta": {"language": "en", "url": "https://scifi.stackexchange.com/questions/141610", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "6"}}
{"text": "Q: about return syntax in c# I wonder why I need to put return syntax twice time in below code,\npublic string test(){\n bool a = true;\n if(a){\n string result = \"A is true\";\n }else{\n string result = \"A is not true\";\n }\n\n return result;\n}\n\nit makes an error that say The name 'result' does not exist in the current context.\nbut either way, there is the result variable. Hmm..\nSo I changed the code like this,\npublic string test(){\n bool a = true;\n if(a){\n string result = \"A is true\";\n return result;\n }else{\n string result = \"A is not true\";\n return result;\n }\n}\n\nThen it works. Is it correct using like this?\nplease advice me,\nThank you!\n\nA: You are just missing the declaration of result in the code blocks.. personally I would suggest the second code block anyway (when corrected) but here...\npublic string test(){\n bool a = true;\n string result = string.Empty;\n if(a){\n result = \"A is true\";\n }else{\n result = \"A is not true\";\n }\n\n return result;\n}\n\nAnd if you were going to go with the second block you could simplify it to:\npublic string test(){\n bool a = true;\n if(a){\n return \"A is true\";\n }else{\n return \"A is not true\";\n }\n}\n\nOr further to:\npublic string test(){\n bool a = true;\n\n return a ? \"A is true\" : \"A is not true\";\n}\n\nAnd several other iterations of similar code (string formatting etc).\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/10744539", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Drawing in Objective-c This is my first time drawing, so it must be something very stupid, but my drawRect: method doesn't work...\nHere is my code:\n- (void)drawRect:(CGRect)rect {\n CGPoint center = CGPointMake(self.bounds.origin.x + self.bounds.size.width / 2, self.bounds.origin.y + self.bounds.size.height / 2);self.bounds.origin.y + self.bounds.size.height / 2)\n CGContextRef ctx = UIGraphicsGetCurrentContext();\n [[UIColor redColor] setStroke];\n CGFloat radius = (self.bounds.size.width > self.bounds.size.height) ? self.bounds.size.width - 30 : self.bounds.size.height - 30;\n CGContextBeginPath(ctx);\n CGContextAddArc(ctx, center.x, center.y, radius, 0, 2 * M_PI, YES);\n CGContextStrokePath(ctx);\n}\n\n\nA: The radius of an arc is measured from its center. You're using almost the entire view's width/height, so that the arc will be drawn outside of the visible area. Use a smaller radius and you'll see your arc.\nBtw, if all you want is to draw a circle (an arc with an angle of 2\u03c0 is the same), CGContextAddEllipseInRect is easier to use.\n\nA: you are drawing the circle just outside the view. CGContextAddArctakes radius as parameter. In your case, you are giving the method diameter.\nQuick fix:\nradius/=2;\n\n\nA: Your example is working. It's actually drawing, but you can't see the circle, as the radius variable probably get's a big value that make the circle to be drawn outside the bounds of the view.\nJust replace manually radius value with a value, say 20, and you'll see that's working fine.\nRegards\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/10245907", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Accessing a WPF or WinForm Element From a Different Appdomain I want to create an application that will run in the background and track the click actions of the mouse, and when the user clicks on an external WPF or Winforms app, the background app should be able to detect the clicked control and display its ID/name/text.\nI'm not sure if this is possible, but since there are automation tools that can perform similar actions, I think it should be possible. For example, with some tools it is possible to get the \"window\" object using the external app's PID, and then the controls (for example a button) can be accessed by providing the ID of the control. However in my case it is the other way around. I need to get ID/name/text of the control the user has clicked.\n\n*\n\n*I can obtain the mouse position using windows Hook\n\n*I can obtain the hwnd and Process ID of the window the user has clicked\n\nSo is it possible to obtain the information about the element clicked? Any help and advice is appreciated, thanks in advance.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/71757808", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Fourier Transform for triangular wave Could someone tell me if I've worked this out right? I'm unsure of the process, especially the final parts where I convert it to a sinc function.\n\nPlease let me know if I've made mistakes anywhere else too.\n\nA: The mistake on the last step:\n$$\n\\frac{6}{\\sqrt{2\\pi}} \\left[ \\frac {\\sin^2\\frac{3\\omega}2}{\\frac{3\\omega^2}2} \\right]\n=\n\\frac{6}{\\sqrt{2\\pi}} \\left[ \\frac {\\sin^2\\frac{3\\omega}2}{\\frac{2}{3}\\left(\\frac{3\\omega}2\\right)^2} \\right]\n=\n\\frac{9}{\\sqrt{2\\pi}} \\left[ \\frac {\\sin\\frac{3\\omega}2}{\\frac{3\\omega}2} \\right]^2\n=\n\\frac{9}{\\sqrt{2\\pi}} {{\\rm sinc}^2\\frac{3\\omega}2}\n$$\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/699216", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Spring Authorization Server 0.3.1 problem registering several RegisteredClientRepository \nHi,\nI need register several clients but when I try to do this it this exception is thrown, I have made sure that each client has a different identifier:\n*Caused by: java.lang.IllegalArgumentException: Registered client must be unique. Found duplicate client secret for identifier: appclientes\nat org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository.lambda$assertUniqueIdentifiers$0(InMemoryRegisteredClientRepository.java:107)\nat java.base/java.util.concurrent.ConcurrentHashMap$ValuesView.forEach(ConcurrentHashMap.java:4772)\nat org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository.assertUniqueIdentifiers(InMemoryRegisteredClientRepository.java:95)\nat org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository.(InMemoryRegisteredClientRepository.java:64)\nat com.pryconsa.backend.config.AuthorizationServerConfig.registeredClientRepository(AuthorizationServerConfig.java:100)\nat com.pryconsa.backend.config.AuthorizationServerConfig$$EnhancerBySpringCGLIB$$46216dc1.CGLIB$registeredClientRepository$2()\nat com.pryconsa.backend.config.AuthorizationServerConfig$$EnhancerBySpringCGLIB$$46216dc1$$FastClassBySpringCGLIB$$b448ca22.invoke()\nat org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)\nat org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)\nat com.pryconsa.backend.config.AuthorizationServerConfig$$EnhancerBySpringCGLIB$$46216dc1.registeredClientRepository()\nat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\nat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\nat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\nat java.base/java.lang.reflect.Method.invoke(Method.java:566)\nat org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)\n... 58 common frames omitted\n*\n\n\n\n\nMy code is the following:\n@Bean\npublic RegisteredClientRepository registeredClientRepository() { \n TokenSettings tokenClient1Settings = TokenSettings.builder()\n .accessTokenTimeToLive(Duration.ofSeconds(client1AccessTokenValiditySeconds))\n .build();\n \n RegisteredClient registeredClient1 = RegisteredClient.withId(client1Id)\n .clientId(client1Id)\n .clientSecret(\"{noop}\" + client1Secret)\n .authorizationGrantType(AuthorizationGrantType.PASSWORD)\n .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)\n .tokenSettings(tokenBackofficeSettings)\n .scope(\"read\")\n .scope(\"write\")\n .build();\n \n TokenSettings tokenClient2Settings = TokenSettings.builder()\n .accessTokenTimeToLive(Duration.ofSeconds(client2AccessTokenValiditySeconds))\n .build();\n \n RegisteredClient registeredClient2 = RegisteredClient.withId(client2Id)\n .clientId(client2Id)\n .clientSecret(\"{noop}\" + client2Secret)\n .authorizationGrantType(AuthorizationGrantType.PASSWORD)\n .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)\n .tokenSettings(tokenClient2Settings)\n .scope(\"read\")\n .scope(\"write\")\n .build();\n \n return new InMemoryRegisteredClientRepository(List.of(registeredClient1, registeredClient2));\n}\n\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/74551673", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Is it safe to store the activity references in savedinstancestate in my application, i have kept a controller class & this is a singleton class. I use this class to fetch the data from first activity, or store some of the information which is required for remaining activities in my app. Even sometime i require to access First activity method from last activity also. At this time, this controller comes to help.\nThe problem comes when user press homebutton, if a user press home button, and resumed after sometime or after opening several other applications, app crashes.\nI got to know that issue is because, activity references wont be existing in controller. So, whenever user press homebutton can i save all these instances & use it once user resume?.\nEven i have fragments in one activity, does those references also needs to be saved?\nHow to handle thse senarios?, any help\n\nA: \nSo, whenever user press homebutton can i save all these instances &\n use it once user resume?.\n\nThe \"instances\" aren't removed when you press home. They are removed when the app is in the background and Android needs more memory some time later (might never happen).\n\nIs it safe to store the activity references in savedinstancestate\n\nYes this is what saved instance state was made for:\n\nAs your activity begins to stop, the system calls\n onSaveInstanceState() so your activity can save state information with\n a collection of key-value pairs. The default implementation of this\n method saves information about the state of the activity's view\n hierarchy, such as the text in an EditText widget or the scroll\n position of a ListView.\n\n.\n\ncan i save all these instances?\n\nYou can't save the instances - you will have to store the information that you will use to re-build your activity as key-value pairs. What I do is I store just enough information so that the activity can rebuild itself. \nFor example, if the Activity has a list that was constructed from api.myapp.com, I will save this URL, as well as the scroll location of the list. The rest you should probably go retrieve again as if you had just launched the app for the first time - this will make your code much simpler.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/24051963", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Is a function with uniformly continuous derivatives on a bounded regular domain also uniformly continuous? Let $\\Omega\\subset \\mathbb{R}^n$ be a bounded connected set which is regular open, meaning that $\\textrm{int }\\textrm{cl }\\Omega = \\Omega$. Suppose that $f\\in C^1(\\Omega)$ has uniformly continuous partial derivatives on $\\Omega$. Is it necessary that $f$ is uniformly continuous on $\\Omega$?\nIf $\\Omega$ is not assumed to be regular open the result would be false; an example can be found here. If the partial derivatives of $f$ are only suppose to be bounded then we can construct a counterexample as follows: let $$\\Omega = ((-1,0)\\times (0,1))\\cup\\left(\\displaystyle{\\bigcup_{n\\in\\mathbb{N^*}}} [0,1)\\times \\left(\\dfrac{1}{2n},\\dfrac{1}{2n-1}\\right) \\right)$$\nDefine $f|_{(-1,0)\\times (0,1)} = 0$, $f|_{[0,1)\\times \\left(\\frac{1}{2n},\\frac{1}{2n-1}\\right)} = (-1)^n x^2$, then $f_x$ is bounded by $2$, but $f$ is not uniformly continuous.\nI believe that there are still counterexamples even when $\\Omega$ is regular open have $f$ has uniformly continuous partial derivatives, but I couldn't find an example. Any help appreciated.\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/4516769", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: UART DMA Tx/Rx Architecture \nPossible Duplicate:\nUART ISR Tx Rx Architecture \n\nI'm working with a TI micro right now that includes a DMA UART Driver and an operating system that supports parallel tasks. The UART driver's functions include:\n\n\n*\n\n*static void HalUARTInitDMA(void);\n\n*static void HalUARTOpenDMA(halUARTCfg_t *config);\n\n*static uint16 HalUARTReadDMA(uint8 *buf, uint16 len);\n\n*static uint16 HalUARTWriteDMA(uint8 *buf, uint16 len);\n\n*static void HalUARTPollDMA(void);\n\n*static uint16 HalUARTRxAvailDMA(void);\n\n*static void HalUARTSuspendDMA(void);\n\n*static void HalUARTResumeDMA(void);\n\n\nI'm trying to communicate with another peripheral that accepts messages terminated with a carriage return and responds with messages afterwards with a carriage return.\nI was curious what the best way to architect this type of communication state machine. My problem is designing the callback function for the UART port such that it...\n\n\n*\n\n*does not hang the system waiting for a response. (Some sort of timeout)\n\n*If a response is read too soon, it will concat the responses together\n\n*A carriage return will signify the end of the message\n\n\nThe basic theory is something like this:\n//send messsage to peripheral\nHalUARTWriteDMA(\"tx\\r\",4);\n\n//wait a little bit for the device to process the message\n\n//start reading from the peripheral \ndo {\n //how many bytes are at the RX port?\n int len = HalUARTRxAvailDMA();\n\n //Read those bytes\n HalUARTReadDMA(msg, len);\n\n //append the rx msg to the buffer\n strcat(rxbuf, msg)\n\n //does the response contain a CR?\n} while(strchr(rxbuf, 0x0D));\n\nThere are a couple of obvious flaws with this idea. I was hoping someone could share some ideas on how this type of communication is performed?\nThanks!\n\nA: There is one immediate problem with the design as you describe it if you intend to block the thread waiting for messages - which is the use variable sized messages and a CR as the delimiter.\nI imagine that HalUARTReadDMA() is designed to block the calling thread until len bytes have been received so you clearly cannot reliably use it to block for a variable length message.\nThe code would look something like (making a few assumptions):\nwhile (1) \n{\n static const size_t bufferSize = sizeof(Message_t);\n uint8_t buffer[bufferSize];\n\n // blocks until message received \n unsigned len = HalUARTReadDMA(buffer, bufferSize);\n\n if (len == bufferSize)\n processMessage(buffer);\n}\n\nThere's no particularly nice or reliable solution to the problem of using variable sized messages with DMA that doesn't involve polling - unless the DMA controller can detect end-of-message delimiters for you.\nIf you can't change the message format, you'd be better off with interrupt-driven IO in which you block on reception of individual message bytes - especially in the case of a UART, which has relatively low data rate. \n\nA: Unless your DMA driver has the functinality to accept a queue of buffer pointers, can generate an interrupt when a CR is received and move on its own to the next buffer pointer, you are going to be stuck with iterating the rx data, looking for a CR.\nIf you have to iterate the data, you may as well do it in a 'classic' ISR, fetching the chars one-by-one from the rx FIFO and shoving them into a buffer until a CR is received. \nYou could then queue the buffer pointer into a suitable circular queue, fetch another buffer from another circular pool queue of 'empty' buffers for the next message, signal a semaphore so that the thread that is going to handle the message will be run and exit from your ISR via the OS so that an immediate reschedule is performed.\nThe rx thread could dequeue the message, process it and then requeue it to the pool queue for re-use by the ISR.\nContinually searching a complete buffer for a CR with strchr() is not likely to be particularly efficient or easy - the CR may be in the middle of the DMA buffer and you involve yourself with data copying of the remining partial buffer.\n.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/13003971", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: video will not autoplay on chrome when it is inserted into the DOM I have a video (meant for background purposes), that is muted and I intend to auto-play. If I were to put the following code into an html file:\n\n\nIt would work just fine on Chrome.\nHowever, If I were to insert the exact same video using DOM manipulation, I would have trouble on Chrome but success in other browsers like Firefox.\n\n\n\n \n\n\nChrome appears notorious for blocking autoplay. The general solutions are either to be muted (which I already do), or to use dom manipulation to call play (which doesn't work). Is there a way to get this to work after inserting the video into the dom. The reason I care is because my actual website requires everything to be rendered (My site is in ember.js). \nThis is in Chrome version 71.\nThanks!\n\nA: This is probably a bug (and not the only one with this autoplay policy...).\nWhen you set the muted attribute through Element.setAttribute(), the policy is not unleashed like it should be.\nTo workaround that, set the IDL attribute through the Element's property:\nfunction render() {\n const video = document.createElement('video');\n video.muted = true;\n video.autoplay = true;\n video.loop = true;\n video.setAttribute('playsinline', true);\n\n const source = document.createElement('source');\n source.setAttribute('src', 'https://res.cloudinary.com/dthskrjhy/video/upload/v1545324364/ASR/Typenex_Dandelion_Break_-_Fade_To_Black.mp4');\n\n video.appendChild(source);\n document.body.appendChild(video);\n}\nrender();\n\nAs a fiddle since StackSnippets requiring a click event form the parent page are anyway always allowed to autoplay ;-).\n\nA: Async, Await, & IIFE\nAfter finding this article a couple of months ago, I still couldn't get a consistent autoplay behavior, muted or otherwise. So the only thing I hadn't tried is packing the async function in an IIFE (Immediately Invoked Function Expression).\nIn the demo:\n\n*\n\n*It is dynamically inserted into the DOM with .insertAdjacentHTML()\n\n\n*It should autoplay\n\n\n*It should be unmuted\n\n\n*All of the above should happen without user interaction.\n\nDemo\n\n\nvar clip = document.getElementById('clip');\n\n(function() {\n playMedia();\n})();\n\nasync function playMedia() {\n try {\n await stamp();\n await clip.play();\n } catch (err) {\n }\n}\n\nfunction stamp() {\n document.body.insertAdjacentHTML('beforeend', ``);\n}\n\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/54246807", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Header Block not displaying in magento 2 https://www.nishatre.com/ is the live url for my website. ALl of a sudden my header block has disappeared.. Can anyone kindly help how to bring back the header block?\nmy header code - \ngetWelcome();\n\n$_config = $this->helper('Sm\\Shiny\\Helper\\Data');\n$headerStyle = $_config->getThemeLayout('header_style');\n$compile_less = $_config->getAdvanced('compile_less');\n$login_customer = $block->getLayout()->createBlock('Magento\\Customer\\Block\\Account\\Customer');\n\nif($login_customer->customerLoggedIn()){\n $loggedin = 'loggedin';\n} else{\n $loggedin = '';\n}\n\ninclude (dirname(__FILE__).'/header-style/'.$headerStyle.'.phtml');\nif( $compile_less ){\n include (dirname(__FILE__).'/compile_less.phtml');\n}\n?>\n\ngetAdvanced('show_newsletter_popup')){\n echo $block->getChildHtml('form.subscribe.popup'); \n }\n?>\n\ngetGeneral('menu_ontop') == 1){ ?>\n \n\n\n\nA: It seems you are using a custom Magento2 theme. \nI believe your Magento cant read the below file.\nTry changing to correct ownership or remove pub/static folders and create the files again.\ninclude (dirname(__FILE__).'/header-style/'.$headerStyle.'.phtml');\n\n", "meta": {"language": "en", "url": "https://magento.stackexchange.com/questions/209447", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: jQuery deleting cookies using cookies plugin I am using this plugin to store some cookies:\nhttps://code.google.com/p/cookies/wiki/Documentation\nI was wondering how i would go about deleting all cookies with a certain prefix and/or delete all cookies that have a certain value. I need this to be done once some user has completed their journey through my application.\nFor example i store the visible state of certain tables on a page like so:\n // check visible status of table and persist\n$('div.dependant').each(function(){\n\n var $childCount = $(this).index('div.dependant');\n\n $(this).addClass('tableStatus' + $childCount);\n\n // get the value of the cookie\n var $tableStatus = $.cookies.get('tableStatus' + $childCount);\n\n // if variable not null\n if ($tableStatus) {\n if ($tableStatus == 'hidden') {\n $('.tableStatus' + $childCount).hide(); \n } else if ($tableStatus == 'visible') {\n $('.tableStatus' + $childCount).show();\n }\n }\n\n});\n\nSo the cookies will be 'tableStatus0', 'tableStatus1' etc...\nI could manually delete but there will be an unknown number of tables.\n\nA: Answered here:\nhttps://code.google.com/p/cookies/wiki/Documentation\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/2407866", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Creating a stack of strings in C I want to have a stack that takes strings. I want to be able to push and pop strings off, as well as clear the whole stack. I think C++ has some methods for this. What about C?\n\nA: Try GNU Obstacks.\nFrom Wikipedia:\n\nIn the C programming language, Obstack is a memory-management GNU extension to the C standard library. An \"obstack\" is a \"stack\" of \"objects\" (data items) which is dynamically managed.\n\nCode example from Wikipedia:\nchar *x;\nvoid *(*funcp)();\n\nx = (char *) obstack_alloc(obptr, size); /* Use the macro. */\nx = (char *) (obstack_alloc) (obptr, size); /* Call the function. */\nfuncp = obstack_alloc; /* Take the address of the function. */\n\nIMO what makes Obstacks special: It does not need malloc() nor free(), but the memory still can be allocated \u00abdynamically\u00bb. It is like alloca() on steroids. It is also available on many platforms, since it is a part of the GNU C Library. Especially on embedded systems it might make more sense to use Obstacks instead of malloc(). \n\nA: See Wikipedia's article about stacks.\n\nA: Quick-and-dirty untested example. Uses a singly-linked list structure; elements are pushed onto and popped from the head of the list. \n#include \n#include \n\n/**\n * Type for individual stack entry\n */\nstruct stack_entry {\n char *data;\n struct stack_entry *next;\n}\n\n/**\n * Type for stack instance\n */\nstruct stack_t\n{\n struct stack_entry *head;\n size_t stackSize; // not strictly necessary, but\n // useful for logging\n}\n\n/**\n * Create a new stack instance\n */\nstruct stack_t *newStack(void)\n{\n struct stack_t *stack = malloc(sizeof *stack);\n if (stack)\n {\n stack->head = NULL;\n stack->stackSize = 0;\n }\n return stack;\n}\n\n/**\n * Make a copy of the string to be stored (assumes \n * strdup() or similar functionality is not\n * available\n */\nchar *copyString(char *str)\n{\n char *tmp = malloc(strlen(str) + 1);\n if (tmp)\n strcpy(tmp, str);\n return tmp;\n}\n\n/**\n * Push a value onto the stack\n */\nvoid push(struct stack_t *theStack, char *value)\n{\n struct stack_entry *entry = malloc(sizeof *entry); \n if (entry)\n {\n entry->data = copyString(value);\n entry->next = theStack->head;\n theStack->head = entry;\n theStack->stackSize++;\n }\n else\n {\n // handle error here\n }\n}\n\n/**\n * Get the value at the top of the stack\n */\nchar *top(struct stack_t *theStack)\n{\n if (theStack && theStack->head)\n return theStack->head->data;\n else\n return NULL;\n}\n\n/**\n * Pop the top element from the stack; this deletes both \n * the stack entry and the string it points to\n */\nvoid pop(struct stack_t *theStack)\n{\n if (theStack->head != NULL)\n {\n struct stack_entry *tmp = theStack->head;\n theStack->head = theStack->head->next;\n free(tmp->data);\n free(tmp);\n theStack->stackSize--;\n }\n}\n\n/**\n * Clear all elements from the stack\n */\nvoid clear (struct stack_t *theStack)\n{\n while (theStack->head != NULL)\n pop(theStack);\n}\n\n/**\n * Destroy a stack instance\n */\nvoid destroyStack(struct stack_t **theStack)\n{\n clear(*theStack);\n free(*theStack);\n *theStack = NULL;\n}\n\nEdit\nIt would help to have an example of how to use it:\nint main(void)\n{\n struct stack_t *theStack = newStack();\n char *data;\n\n push(theStack, \"foo\");\n push(theStack, \"bar\");\n ...\n data = top(theStack);\n pop(theStack);\n ...\n clear(theStack);\n destroyStack(&theStack);\n ...\n}\n\nYou can declare stacks as auto variables, rather than using newStack() and destroyStack(), you just need to make sure they're initialzed properly, as in\nint main(void)\n{\n struct stack_t myStack = {NULL, 0};\n push (&myStack, \"this is a test\");\n push (&myStack, \"this is another test\");\n ...\n clear(&myStack);\n}\n\nI'm just in the habit of creating pseudo constructors/destructors for everything. \n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/1919975", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "4"}}
{"text": "Q: How can I resize a box without resizing the box next to it using jQuery or Javascript? I'm trying to resize a box (orange box), but my issue is that I can ONLY resize it to the right and bottom , but I cannot resize it to the top (I only want to be able to resize it to the top).\nAlso after re-sizing it to the top I don't want it to resize the green box (I want the green box to be static, meaning that I don't want it to change its size, the orange box should be over it). I have tried and cannot come up with good results. Using jQuery or pure JavaScript works fine with me.\nHere's my code:\n\n \n \n \n \n \n \n \n \n
\n
This is some text
\n
This is some text
\n
This is some text
\n
This is some text
\n
\n \n
\n
This is the Orange Box
\n
\n \n\n\nCSS code:\n.ui-widget {\n background: orange;\n border: 1px solid #DDDDDD;\n color: #333333;\n}\n.ui-widget2 {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n}\n#orangeBox { \n width: 300px; height: 150px; padding: 0.5em;\n text-align: center; margin: 0;border:2px solid black; \n}\n#greenBox { \n width: 340px; height: 150px; padding: 0.5em;\n text-align: center; margin: 0; border:2px solid black;\n}\n\n\nA: You can do it like this:\n$(function() {\n $( \"#orangeBox\" ).resizable({\n handles:'n,e,s,w' //top, right, bottom, left\n });\n });\n\nworking example Link in JSFiddle : http://jsfiddle.net/sandenay/hyq86sva/1/\nEdit:\nIf you want it to happen on a button click:\n $(\".btn\").on(\"click\", function(){\n var height = $(\"#orangeBox\").offset().top; // get position from top\n console.log(height);\n $(\"#orangeBox\").animate({\n height: \"+=\"+height+'px'\n }, 1000);\n\n });\n\nand add this in your HTML:\n\n\nWorking fiddle: http://jsfiddle.net/sandenay/hyq86sva/4/\n\nA: Try this in your script :\n$(function() {\n $( \"#orangeBox\" ).resizable({\n handles: 'n, e, s, w' \n });\n });\nHope this helps !!\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/33228091", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: How to align output correctly I have the following value:\nval x = List(((\"Burger and chips\",4.99),4.99,1), ((\"Pasta & Chicken with Salad\",8.99), 8.99,2), ((\"Rice & Chicken with Chips\",8.99), 8.99,2))\n\nafter printing I get this:\nx.foreach(x => println(x._3 + \" x \" + x._1 +\"\\t\\t\\t\\t\"+\"$\"+x._2 * x._3 ))\n\n1 x (Burger and chips,4.99) $4.99\n2 x (Pasta & Chicken with Salad,8.99) $17.98\n2 x (Rice & Chicken with Chips,8.99) $17.98\n\nHowever i want this result instead:\n1 x (Burger and chips,4.99) $4.99\n2 x (Pasta & Chicken with Salad,8.99) $17.98\n2 x (Rice & Chicken with Chips,8.99) $17.98\n\nI know the text size is causing the problem but is there a way around it??\nThanks\n\nA: Scala's \"f interpolator\" is useful for this:\nx.foreach { \n case (text, price, amount) => println(f\"$amount x $text%-40s $$${price*amount}\") \n}\n\n// prints:\n1 x (Burger and chips,4.99) $4.99\n2 x (Pasta & Chicken with Salad,8.99) $17.98\n2 x (Rice & Chicken with Chips,8.99) $17.98\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/51408565", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: 2 Spring TransactionManager on the same datasource: Pre-bound JDBC Connection found i have a problem with a Spring TransactionManager. I have two JpaTransactionManager that insist on the same datasource. when I use the second transactionManager I take the error: Pre-bound JDBC Connection found! JpaTransactionManager does not support running within DataSourceTransactionManager if told to manage the DataSource itself.\nHow can I run both the transaction manager?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/33497005", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Live USB installation hanging on startup - Vivid, Acer Aspire V I'm trying to install Ubuntu 15.04 and it keeps hanging at the point where it says\nStarting Wait for Plymouth boot screen to Quit\n\nI've tried two different iso downloads (md5 is correct) and two different memory sticks. Yet, scanning the disk says that there are errors in two files (with both sticks and both iso's).\nI'm really at a loss as to why this might happen. Any suggestions?\nEdit: 14.04.2 seems to work fine (except for click pad, network and graphics issues). I'd like to know if this is a hardware problem, as when it comes to upgrading it would be a real problem if later versions are not compatible with my hardware.\n\nA: To install the newest version of Ubuntu from Live USB I used a program that installed Ubuntu on the USB first and made it bootable\nLink: This will install the newest version of Ubuntu on your USB drive for you\n", "meta": {"language": "en", "url": "https://askubuntu.com/questions/637338", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: \u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u0438\u0435 \u043c\u0430\u0441\u0441\u0438\u0432\u044b \u0432 stl \u0425\u043e\u0447\u0443 \u0441\u043e\u0437\u0434\u0430\u0442\u044c \u043a\u0432\u0430\u0434\u0440\u0430\u0442\u043d\u0443\u044e \u043c\u0430\u0442\u0440\u0438\u0446\u0443 \u0441 \u043f\u043e\u043c\u043e\u0449\u044c\u044e stl \u0438 \u0447\u0442\u043e\u0431\u044b \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044c \u0441\u0430\u043c \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u043b \u043c\u0430\u0441\u0441\u0438\u0432. \n\u041f\u043e\u043a\u0430 \u043a\u043e\u0434 \u0442\u0430\u043a\u043e\u0439:\n#define _CRT_SECURE_NO_WARNINGS \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nint main () {\n setlocale(LC_ALL, \"Rus\");\n int e;\n cin >> e;\n vector > e;\n e.push_back(vector());\n\n for (int i = 0; i < e.size(); i++) {\n cout << e[i] << \" \";\n }\n cout << endl;\n _getch();\nreturn 0;\n} \n\n\u041f\u0438\u0448\u0435\u0442 \u043e\u0448\u0438\u0431\u043a\u0438 \u043d\u0430\u0434 \u0435 \"\u0432\u044b\u0440\u0430\u0436\u0435\u043d\u0438\u0435 \u0434\u043e\u043b\u0436\u043d\u043e \u0438\u043c\u0435\u0442\u044c \u0442\u0438\u043f \u043a\u043b\u0430\u0441\u0441\u0430\" \u0438 \u0433\u0434\u0435 \u0435[i] - \u0432\u044b\u0440\u0430\u0436\u0435\u043d\u0438\u0435 \u0434\u043e\u043b\u0436\u043d\u043e \u0438\u043c\u0435\u0442\u044c \u0442\u0438\u043f \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f \u043d\u0430 \u043e\u0431\u044a\u0435\u043a\u0442.\n\u0411\u044b\u043b\u0438 \u0440\u0430\u0437\u043d\u044b\u0435 \u043e\u0448\u0438\u0431\u043a\u0438, \u0431\u0440\u0430\u043b\u0430 \u0447\u0430\u0441\u0442\u044c \u0440\u0435\u0448\u0435\u043d\u0438\u0439 c \u044d\u0442\u043e\u0433\u043e \u0441\u0430\u0439\u0442\u0430 \u0445\u0434 \u041d\u043e \u0442\u0430\u043a \u0438 \u0434\u043e \u043a\u043e\u043d\u0446\u0430 \u043d\u0435 \u043f\u043e\u043d\u044f\u043b\u0430 \u043a\u0430\u043a \u0441\u043e\u0437\u0434\u0430\u0442\u044c \u0434\u0432\u0443\u043c\u0435\u0440\u043d\u044b\u0439 \u043c\u0430\u0441\u0441\u0438\u0432, \u0447\u0442\u043e\u0431\u044b \u043f\u043e\u0442\u043e\u043c \u0437\u0430\u043f\u0438\u0445\u043d\u0443\u0442\u044c \u0442\u0443\u0434\u0430 \u0446\u0438\u043a\u043b \u043d\u0430 \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0443 \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0432\u0432\u0435\u0434\u0435\u043d\u043d\u044b\u0445 \u0441\u0442\u0440\u043e\u043a \u0438 \u0441\u0442\u043e\u043b\u0431\u0446\u043e\u0432.\n\u0411\u044b\u043b\u043e \u0431\u044b \u043a\u043b\u0430\u0441\u0441\u043d\u043e \u0435\u0449\u0435 \u0433\u0434\u0435 \u043c\u043e\u0436\u043d\u043e \u043f\u0440\u043e\u0447\u0438\u0442\u0430\u0442\u044c \u0431\u043e\u043b\u0435\u0435 \u043f\u043e\u0434\u0440\u043e\u0431\u043d\u0443\u044e \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044e \u043e\u0431 \u044d\u0442\u043e\u0439 \u0431\u0438\u0431\u043b\u0438\u043e\u0442\u0435\u043a\u0435, \u0442\u043a \u0442\u0430\u043c \u0435\u0449\u0435 \u0435\u0441\u0442\u044c \u043f\u0440\u043e\u0434\u043e\u043b\u0436\u0435\u043d\u0438\u044f \u0437\u0430\u0434\u0430\u043d\u0438\u044f \u0445\u0434\n\nA: \u0418\u043c\u0435\u043d\u0430 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445 \u0432 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0435 \u0434\u043e\u043b\u0436\u043d\u044b \u0431\u044b\u0442\u044c \u0440\u0430\u0437\u043d\u044b\u043c\u0438. \u0417\u0430\u0447\u0435\u043c \u0412\u044b \u043f\u0438\u0448\u0438\u0442\u0435:\nint e;\n...\nvector> e;\n\n\u0414\u043b\u044f \u043d\u0430\u0447\u0430\u043b\u0430 \u0438\u0437\u043c\u0435\u043d\u0438\u0442\u0435 \u043d\u0430\u0437\u0432\u0430\u043d\u0438\u044f \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445, \u043c\u043e\u0436\u043d\u043e \u0434\u0430\u0436\u0435 \u043d\u0430 \u0431\u043e\u043b\u0435\u0435 \u0437\u0432\u0443\u0447\u0430\u0449\u0438\u0435 \u0438\u043c\u0435\u043d\u0430.\n\u0421\u0442\u0440\u043e\u043a\u043e\u0439 e.push_back(vector()); \u0412\u044b \u0434\u043e\u0431\u0430\u0432\u043b\u044f\u0435\u0442\u0435 \u043f\u0443\u0441\u0442\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443 \u0432 \u0432\u0430\u0448\u0443 \"\u043c\u0430\u0442\u0440\u0438\u0446\u0443\", \u0432\u043c\u0435\u0441\u0442\u043e \u0442\u043e\u0433\u043e, \u0447\u0442\u043e\u0431\u044b \u0438\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0435\u0451. \u041f\u043e\u043f\u0440\u043e\u0431\u0443\u0439\u0442\u0435 \u0434\u043b\u044f \u0438\u043d\u0438\u0446\u0438\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u0438 \u0434\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u043e \u0441\u0442\u0440\u043e\u043a \u0438 \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u043e \u0437\u0430\u043f\u043e\u043b\u043d\u0438\u0442\u044c \u043a\u0430\u0436\u0434\u044b\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442, \u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440 \u0442\u0430\u043a:\nvector> v(rowCount); // \u0441\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u0441\u0440\u0430\u0437\u0443 rowCount \u0441\u0442\u0440\u043e\u043a\n\n\nfor (int i = 0; i < v.size(); i++) // \u043f\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u0435\u043c \u0441\u0442\u0440\u043e\u043a\u0438\n{\n v[i].resize(colCount); // \u0440\u0430\u0441\u0448\u0438\u0440\u044f\u0435\u043c i-\u0443\u044e \u0441\u0442\u0440\u043e\u043a\u0443 \u0434\u043e \u0440\u0430\u0437\u043c\u0435\u0440\u0430 colCount\n\n for (int j = 0; j < v[i].size(); j++) // \u043f\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u0435\u043c \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u044b i-\u0442\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438\n {\n cin >> v[i][j]; // \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u0435\u043c \u044d\u043b\u0435\u043c\u0435\u043d\u0442 i-\u0442\u043e\u0439 \u0441\u0442\u0440\u043e\u043a\u0438 j-\u043e\u0433\u043e \u0441\u0442\u043e\u043b\u0431\u0446\u0430\n }\n}\n\n\u0414\u043b\u044f \u0432\u044b\u0432\u043e\u0434\u0430 \u043d\u0435\u043b\u044c\u0437\u044f \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c:\ncout << v[i];\n\n\u0412 \u044d\u0442\u043e\u043c \u0441\u043b\u0443\u0447\u0430\u0435 \u0412\u044b \u043f\u044b\u0442\u0430\u0435\u0442\u0435\u0441\u044c \u0432\u044b\u0432\u0435\u0441\u0442\u0438 \u0432\u0435\u0441\u044c \u0432\u0435\u043a\u0442\u043e\u0440-\u0441\u0442\u0440\u043e\u043a\u0443, \u0432 \u0442\u043e \u0432\u0440\u0435\u043c\u044f \u043a\u0430\u043a \u0432\u0430\u0448\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0430 \u043d\u0435 \u0443\u043c\u0435\u0435\u0442 \u044d\u0442\u043e\u0433\u043e \u0434\u0435\u043b\u0430\u0442\u044c. \u0421\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u043e, \u0412\u0430\u043c \u043d\u0443\u0436\u043d\u043e \u043f\u0435\u0440\u0435\u0431\u0440\u0430\u0442\u044c \u043a\u0430\u0436\u0434\u044b\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442. \u0412\u044b\u0432\u043e\u0434 \u043d\u0430 \u044d\u043a\u0440\u0430\u043d \u0430\u043d\u0430\u043b\u043e\u0433\u0438\u0447\u0435\u043d \u0432\u0432\u043e\u0434\u0443. \u0418\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0439\u0442\u0435 \u0432\u043b\u043e\u0436\u0435\u043d\u043d\u044b\u0435 \u0446\u0438\u043a\u043b\u044b, \u043a\u0430\u043a \u0432 \u043f\u0440\u0438\u043c\u0435\u0440\u0435 \u0441 \u0432\u0432\u043e\u0434\u043e\u043c.\n\u041f\u043e \u043f\u043e\u0432\u043e\u0434\u0443 \"\u043f\u043e\u0447\u0438\u0442\u0430\u0442\u044c\" \u043f\u0430\u0440\u0443 \u043f\u043e\u043b\u0435\u0437\u043d\u044b\u0445 \u0441\u0441\u044b\u043b\u043e\u043a:\n\n\n*\n\n*cplusplus.com/vector\n\n*en.cppreference.com/container/vector\n", "meta": {"language": "ru", "url": "https://ru.stackoverflow.com/questions/974239", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: which is the better way of coding Might seem like a silly question. I just wanted to know which is better way of coding.\nOption 1:\nif(a==null) {\n a=getA();\n return a;\n} else {\n return a;\n}\n\nOption 2:\nif(a==null) {\n a=getA();\n}\nreturn a;\n\nvariable a is a static variable used to cache the getA() and avoid calling it multiple times.\n\nA: There's a 3rd alternative which is even shorter - using the ternary conditional operator :\nreturn a != null ? a : getA();\n\nEDIT: I assumed a is a local variable, and therefore doesn't have to be assigned if it's null. If, on the other hand, it's an instance variable used as a cache (to avoid calling getA() multiple times), you need to assign the result of getA() to a, in which case I'd use your second alternative, since it's shorter, and thus clearer (you can still use the ternary conditional operator with assignment - return a != null ? a : (a = getA()); - but I find that less clear).\n\nA: I prefer the second choice as there is only one return statement, and this can help debugging (you only need to put in one breakpoint rather than two). Also you're arguably duplicating code in the first choice.\nBut in this instance I'd prefer using the ternary conditional:\nreturn a == null ? getA() : a;\n\nA: I prefer the second option, The best practice is have only one return statement in a method. That will be the more readable code.\n\nA: The second is more concise, and could be better because of this, but this is a subjective matter and no-one can give you a particularly objective answer. Whatever you like or fits into your teams coding standards is the answer.\nAs has been pointed out, there is a shorter way to do this:\nreturn a!=null ? a : getA();\n\nbut again, it entirely depends on what you and your team prefer. Personally I prefer the second way you showed to this, as it is more readable (in my opinion).\n\nA: I'm assuming for a second that a is a class member and that getA() is a method that creates an instance of a.\nThe best solution should be to push this logic in the called method. In other words, rather than have:\nvoid someFunction() {\n // logic\n if(a==null) {\n a=getA();\n }\n return a;\n}\n\nA getA() {\n // creation logic of instance A\n return newAInstance;\n}\n\nYou should have:\nvoid someFunction() {\n // logic\n\n return getA();\n}\n\nA getA() {\n if(a == null) {\n // creation logic of instance A\n }\n return a;\n}\n\nThe cost of the method call is minimal and worth not having to deal with when a will be instantiated.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/34988589", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: Improving Winforms performance with large number of controls Are there any ways to improve performance when constructing several forms with large numbers of controls (500+)?\nOur controls are laid out in a label + 6 text box per row configuration, as shown below:\n\nWe have used the following containers to structure our controls:\n\n*\n\n*DevExpress' XtraLayoutControl\n\n*Panels around each row and moving manually\n\n*Common table control\n\nWe can't use a grid as the text boxes have to be hidden on a case-by-case basis and our forms have to look fairly close to the printouts. Also, each row has it's own data type, so we need to add validation and editors for each.\nThe table control is the most performant, where each form takes around 2 seconds to load.\nAs each of these will represent a document in our software and we allow users to open multiple documents at once, we are trying to find a way to improve the performance.\nOne suggestion was to cache the actual form and have a state object that stores the data. However, we allow the user to see more than one document at once.\nAnother suggestion was to load the document in parts and show each part as it becomes loaded. This isn't ideal as we are known for having a document that looks almost exactly like the printout.\nAre there any other strategies available, or should we just bight the bullet at tell our customers that this program will be slower than it's VB6 predecessor?\nAn example of the form design we're redeveloping is here: Link\n\nA: Complex datatype handling and stuff is to you, this is a 5 minute before-lunch sample to show how much winforms sucks and how much WPF rules:\nnamespace WpfApplication5\n{\n\npublic partial class MainWindow : Window\n{\n private List _items;\n public List Items\n {\n get { return _items ?? (_items = new List()); }\n }\n\n public MainWindow()\n {\n InitializeComponent();\n\n Items.Add(new Item() {Description = \"Base metal Thickness\"});\n\n for (var i = 32; i > 0; i--)\n {\n Items.Add(new Item() {Description = \"Metal Specification \" + i.ToString()});\n }\n\n Items.Add(new Item() { Description = \"Base metal specification\" });\n\n DataContext = this;\n }\n}\n\npublic class Item: INotifyPropertyChanged\n{\n private List _values;\n public List Values\n {\n get { return _values ?? (_values = new List()); }\n }\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n public string Description { get; set; }\n\n protected virtual void OnPropertyChanged(string propertyName)\n {\n var handler = PropertyChanged;\n if (handler != null) \n handler(this, new PropertyChangedEventArgs(propertyName));\n }\n\n public Item()\n {\n Values.Add(\"Value1\");\n Values.Add(\"Value2\");\n Values.Add(\"Value3\");\n Values.Add(\"Value4\");\n Values.Add(\"Value5\");\n Values.Add(\"Value6\");\n }\n}\n}\n\nXAML:\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\nI see that you have several other requirements here, such as hiding texboxes and stuff. It doesn't matter if these rows are a different data type, you just need to do a ViewModel (which in this case would be my public class Item, which hold the data you want to show in the screen, and let the user be able to interact with.\nFor example, you could replace the List inside the Item class with something more complex, and add some properties like public bool IsVisible {get;set;} and so on.\nI strongly suggest you take a look at WPF (at least for this screen in particular).\nCopy and paste my code in a new -> WPF project and you can see the results for yourself.\n\nA: We can't use a grid as the text boxes have to be hidden on a case-by-case basis.\nI don't understand why this precludes the use of a DataGridView. A specific DataGridViewCell can be made read-only by setting the ReadOnly property to true. You could then use the DataGridView.CellFormatting event to hide the value of the read-only cells. If I recall correctly, the code would be similar to this:\nprivate void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n DataGridView grid = (DataGridView)sender;\n if (grid[e.ColumnIndex, e.RowIndex].ReadOnly)\n {\n e.Value = string.Empty;\n e.FormattingApplied = true;\n }\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/14565773", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: How to Custom Datagridview Sort Like this I have a windows Datagridview with Column values\nid\n---\n0\n0\n0\n5\n2\n7\n\nI want ascending sort of this but zero containg cells will be under.\nLike this-\n2\n5\n7\n0\n0\n0\n\n\nA: Since you haven't mentioned the datasource of your DataGridView i show an approach with a collection. For example with an int[] but it works with all:\nint[] collection = { 0, 0, 0, 5, 2, 7 };\nint[] ordered = collection.OrderBy(i => i == 0).ThenBy(i => i).ToArray();\n\nThis works because the first OrderBy uses a comparison which can either be true or false. Since true is \"higher\" than false all which are not 0 come first. The ThenBy is for the internal ordering of the non-zero group.\nIf that's too abstract, maybe you find this more readable:\nint[] ordered = collection.OrderBy(i => i != 0 ? 0 : 1).ThenBy(i => i).ToArray();\n\n\nA: If you are not using data source for your grid, then you can use DataGridView.SortCompare event like this\nvoid yourDataGridView_SortCompare(object sender, DataGridViewSortCompareEventArgs e)\n{\n if (e.Column.Name == \"Id\" && e.CellValue1 != null && e.CellValue2 != null)\n {\n var x = (int)e.CellValue1;\n var y = (int)e.CellValue2;\n e.SortResult = x == y ? 0 : x == 0 ? 1 : y == 0 ? -1 : x.CompareTo(y);\n e.Handled = true;\n }\n}\n\nDon't forget to attach the event handler to your grid view.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/35200095", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: JavaScript JQuery hide/show function so lately i have been working on a little bit of js. \nso, basically, my problem is that i need to hide whatever is passed in the parameters or show it if it already hidden.\nHere is my code:\n\n\nhowever, it doesn't work.... it is sending the alerts, and everything is correct, however, it does not hide or show the table....\nbut, if i try doing this:\n\n\nIt works! why is it like that? because im going to have many tables on the website and other things that need to be hidden and shown and i dont want to make a new function for each.. :/\nPlease help me! \nTHANKS!!\n\nA: Very Simple use toggle() intead of show()/hide(), toggle() makes element visible if it is hide and hide it if it is visible.\n\n\nIf you want to hard code the Element ID than use following script\n\n\nCheers, and dont forgot to vote up my answer\n:)\n\nA: If you're passing an element reference in, use that as your selector:\nfunction toggleReport(table){\n $(table).toggle();\n}\n\nNote I'm using .toggle(), which will do exactly what you're attempting to do manually. If you wanted to log the new state, you can do so in the callback:\nfunction toggleReport( table ) {\n $( table ).toggle('fast', function(){\n console.log( \"Element is visible? \" + $(this).is(\":visible\") );\n });\n}\n\nNote, if you're passing in the ID of the element, your selector will need to be modified:\n$( \"#\" + table ).toggle();\n\n\nA: There's a prebuilt Jquery function for this.\n\nA: You can use toggle function to achieve this....\n$(selector).toggle();\n\n\nA: demo http://jsfiddle.net/uW3cN/2/\ndemo with parameter passed http://jsfiddle.net/uW3cN/3/\nGood read API toggle: http://api.jquery.com/toggle/\ncode\nfunction toggleReport(){\n//removed the argument\n$('#table_1').toggle();\n\n}\n\n\u200banother sample rest html is in here http://jsfiddle.net/uW3cN/3/\nfunction toggleReport(tableid){\n//removed the argument\n$('#'+tableid).toggle();\n\n}\n\n\u200b\n\nA: The mistake you made in your original function is that you did not actually use the parameter you passed into your function.You selected \"#table\" which is simply selecting a element on the page with the id \"table\". It didn't reference your variable at all.\nIf your intention was to pass an ID into the selector should be written, jQuery(\"#\" + table). If table is instead a reference to a DOM element, you would write jQuery(table) (no quotes and no pound sign). \n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/10748783", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Internal div doesn't fit external div. Both have padding: 10px. Both have width:100% My internal div though set at width: 100% does not fill the external div. I think it's because of the padding, but I'm not sure. How can I get the internal div to fit the width of the external div? Thanks.\nmyjsfiddle\nHTML:\n\n\n Clinical Molecular Incident Reporting System\n {% load staticfiles %}\n \n\n\n
\n\n\n\nCSS:\nhtml,body {font-family: Verdana; font-size: 16px;}\n\n#content {\n width: 90%; \n margin-left: auto; \n margin-right: auto; \n background-color: #F6F6EF;\n box-sizing: border-box;\n ms-box-sizing: border-box;\n webkit-box-sizing: border-box;\n moz-box-sizing: border-box;\n padding: 0px 10px 10px 10px;\n}\n\n#pagetop {\n width: 100%; \n background-color: #04B4AE; \n font-family: Verdana; \n box-sizing: border-box;\n ms-box-sizing: border-box;\n webkit-box-sizing: border-box;\n moz-box-sizing: border-box;\n padding: 10px;\n}\n\n#pagetop a:link {color:#000; text-decoration: none;} /* unvisited link */\n#pagetop a:visited {color:#000; text-decoration: none;} /* visited link */\n#pagetop a:hover {color:#000; text-decoration: underline;} /* mouse over link */\n#pagetop a:active {color:#000; text-decoration: none;} /* selected link */ \n\n#navigation{padding-left: 15px;}\n\n#user-info {float: right;}\n\n\nA: Remove width and add negative left&right margins for #pagetop.\n#pagetop {\n margin: 0 -10px; \n width: auto; /* default value, just remove width: 100% */\n}\n\nhttps://jsfiddle.net/hmv753s4/1/\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/30401594", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: R-call multiple variables with same beginning If 9 variables exist that all begin with, say, \"hand\", I want to be able to pass all of them in a script by shorthand. Using SAS, I do it as follows:\nhand: \nUsing this, I can run analyses on all variables beginning with \"hand\" by passing it this way. My question: what is the syntax equivalent in R? \n\nA: There is no base R equivalent short hand\nGenerally, if you have a data.frame, you can simply create the appropriate character vector from the names\n# if you have a data.frame called df\nhands <- grep('^hands', names(df), value = TRUE)\n# you can now use this character vector\n\nIf you are using dplyr, it comes with a number of special functions for use within select\neg:\nlibrary(dplyr)\ndf <- tbl_df(df)\nselect(df, starts_with(\"hands\"))\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/35544288", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Find all vectors $(x,y)$ whose image under rotation $\\frac\\pi3$ is $(y,x)$ Find all vectors (x,y) whose image under rotation through the angle $\\pi/3$ about the origin is (y,x). \nUsing the appropriate rotation matrix I found that x=y. What do I need to do now to find the answer? \n\nA: Let $(x\u2019,y\u2019)$ be the vector after the rotation. Then,\n$$x\u2019=y=x\\cos\\frac\\pi3 -y\\sin\\frac\\pi3$$\nwhich leads to \n$$\\frac yx=\\frac{\\cos\\frac\\pi3}{1+\\sin\\frac\\pi3}\n=\\frac{\\sin\\frac\\pi6}{1+\\cos\\frac\\pi6} \n= \\frac{2\\sin\\frac\\pi{12}\\cos\\frac\\pi{12}}{2\\cos^2\\frac\\pi{12}} \n=\\tan\\frac\\pi{12}$$\nThus, all the vectors that satisfy the requirement are\n$(x,y)=t(1,\\tan\\frac\\pi{12})$.\n\nA: Algebraic approach: Rotating a vector by $\\pi/3$ corresponds to multiplying by the matrix $$A=\\begin{bmatrix}\\cos\\pi/3&-\\sin\\pi/3\\\\\\sin\\pi/3&\\cos\\pi/3\\end{bmatrix}=\\begin{bmatrix}\\frac12&-\\frac{\\sqrt3}2\\\\\\frac{\\sqrt3}2&\\frac12\\end{bmatrix}$$\nAnd flipping the coordinates corresponds to multiplying by the matrix $$B=\\begin{bmatrix}0&1\\\\1&0\\end{bmatrix}$$So given a vector $v$, we want $Av=Bv$, which is to say $(A-B)v=0$. So that's what you have to do: Find the kernel of $A-B$.\nGeometric approach: Flipping the coordinates means mirroring across the line $x=y$. So now you have to think: Which vectors end up in the same place under the reflection as they do under the rotation?\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/3497641", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: htaccess : redirection all subdomain to main https www domain i'm stuck using htaccess redirection, mixing some answers [1] [2] about htaccess redirection.\nMy goal is to redirect every subdomain (not www) to my main one ( starting with https://www. ), keeping the Request_URI (like specified folder) as it is.\nHere is what i've done:\nRewriteEngine On\n\nRewriteCond %{HTTP_HOST} ^(.+)\\.mydomain\\.fr$ [NC]\n# OR : RewriteCond .* ^(.+)\\.%{HTTP_HOST}%{REQUEST_URI}$ [NC]\n\nRewriteCond %{HTTP_HOST} !^www\\.mydomain\\.fr$ [NC]\nRewriteRule ^ https://www.mydomain.fr%{REQUEST_URI} [L,R=301,QSA]\n\nThis config do redirect (strong text are bad redirection) :\n\n\n*\n\n*test.mydomain.fr => https://www.mydomain.fr\n\n*test.mydomain.fr/foo => https://www.mydomain.fr/foo\n\n*mydomain.fr => https://www.mydomain.fr\n\n*https://foo.mydomain.fr => https://foo.mydomain.fr\n\n*www.mydomain.fr => http://www.mydomain.fr\nSwapping \nRewriteCond %{HTTP_HOST} !^www\\.mydomain\\.fr$ [NC]\nto \nRewriteCond %{HTTP_HOST} !^https://www\\.mydomain\\.fr [NC] gave me an error of bad redirection.\nMy thoughts was to check if the HTTP_HOST is in format https://www.mydomain, if not redirect to the good URL with REQUEST info\n RewriteRule ^ https://www.mydomain.fr/%{REQUEST_URI}\nWhy is there a bad redirection ?\nDo I have to write 2 set of Condition and Rule to check first the subdomain, then the HTTPS ? (I'm currently trying to make the redirection using one rule and several conditions, this may not be the best practice)\nEDIT : My goal is to have these redirection:\n\n\n*\n\n*test.mydomain.fr => https://www.mydomain.fr\n\n*test.mydomain.fr/foo => https://www.mydomain.fr/foo\n\n*mydomain.fr => https://www.mydomain.fr\n\n*https://foo.mydomain.fr => https://www.mydomain.fr\n\n*www.mydomain.fr => https://www.mydomain.fr\nThanks in advance for any answers/ideas.\nEDIT 2:\nI've tried the Larzan answer on THIS question, and it seems to do what i want except one thing : If my URL in my browser is something like https://foobar.mydomain.fr, the browser shows me a big red warning about security, and i have to accept the risk, then the redirection is done to https://www.mydomain.fr. How can i removed this warning ?\n#First rewrite any request to the wrong domain to use the correct one (here www.)\nRewriteCond %{HTTP_HOST} !^www\\.mydomain\nRewriteRule ^(.*)$ https://www.mydomain.fr%{REQUEST_URI} [L,R=301]\n\n#Now, rewrite to HTTPS:\nRewriteCond %{HTTPS} off\nRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n\n\nA: Replace both of your rules with this single rule:\nRewriteEngine On\n\nRewriteCond %{HTTPS} off [OR]\nRewriteCond %{HTTP_HOST} !^www\\.mydomain\\.fr$ [NC]\nRewriteRule ^ https://www.mydomain.fr%{REQUEST_URI} [L,R=301,NE]\n\nTest the change after completely clearing your browser cache.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/41019319", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}}
{"text": "Q: Can atomic counter in trigger lead to \"could not serialize access due to concurrent update\"? I have the following code:\ncreate table users (id serial primary key, comments_counter integer default 0);\ncreate table comments (id serial primary key, user_id integer references users(id) not null)\n\ncreate or replace function users_comments_counter()\nreturns trigger as $$\nbegin\n update users set comments_counter = comments_counter + 1\n where id = NEW.user_id;\n return null;\nend;\n$$ language plpgsql;\n\ncreate trigger users_comments_counter_trg\nafter insert on comments\nfor each row execute procedure users_comments_counter();\n\nIs it possible that inserting a row to the comments table will throw could not serialize access due to concurrent update?\n\nOr maybe in other words: is it possible to use such counter (with ANY of transaction isolation levels) while avoiding situation where \"retry\" (due transaction serialization error) is needed, and data consistency is guaranteed (counter will behave as expected - will be incremented only if comment row will be successfuly inserted).\n\nA: The actions taken in the trigger are part of the transaction that fires it. This means that the counter increment will happen only if the whole transaction (or the subtransaction defined by a SAVEPOINT) succeeds. This way we can say that the above trigger will increment the counter atomically, from the point of view of the INSERT INTO comments statement.\nIf this is all you have inside the transaction (INSERT and the increment), you are safe from concurrency issues, and the default isolation level (READ COMMITTED) is enough.\nFurthermore, depending on how the INSERT is issued, you might even spare the trigger, which would save you some overhead. In order to do this, the following conditions must be met:\n\n\n*\n\n*you can wrap the INSERT INTO comments and UPDATE users statements into a transaction\n\n*there is no other way adding a comment than the transaction in the previous point (i. e. no manual editing of the data by an administrator or similar)\n\n", "meta": {"language": "en", "url": "https://dba.stackexchange.com/questions/124231", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "4"}}
{"text": "Q: ShowShareSheet creates black/blank screen Using DELPHI XE4/XE5. \n\nUsing an ActionList and Tbutton that is linked to the aciton: ActionShowShareSheet, the picture above is my result. I can not find a lot of troubleshooting around or many examples regarding the topic. I am trying to share an image with informational text - nothing to fancy - either by email or whichever the desired social sharing service is preferred by the user. \nYes, I have looked at the example provided by Delphi, and even attempted copying and pasting the same controls/components from that example. \nedit ---\nOkay, so I tested in in the iPad as well, it appears to show the popver modal but no items are shown to share with. So I am now facing two problems:\n1. ShowActionShareSheet does not display properly with an iPhone device/simulator\n2. I have nothing to share with, or I can't. I have signed into Facebook as a test via the iOS device settings and it still does not work properly. \nHelp ! Thanks\n\nA: ~ Simple solution. Just doesn't work in the simulator. \n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/18773780", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Using scipy.fmin. TypeError: 'numpy.float64' object is not iterable I'm trying to use scipy.fmin (docs here) and I can't figure out why it isn't working. My code:\ndef moveMolecule(array):\n x0 = [0, 0, 0]\n minV = fmin(calculateV,x0)\n\nWhere calculateV is:\ndef calculateV(array):\n# Calculation of LJ potential using possible radii\n# Returns potential in kJ/mol as an list with closest neighbor(s)\npoints = tuple(map(tuple, array))\nradius = []\nV = []\n\n# Query tree for nearest neighbors using KD tree\n# Returns indices of NN\nfor n in points:\n output = [i for i in points if i != n]\n tree = spatial.KDTree(output)\n index = tree.query_ball_point(x=n, r=3)\n for i in index:\n radius.append(euclideanDist(tree.data[i], n))\n\n# Calculate potential for NNs\nfor r in radius:\n V.append((4 * _e) * (((_d / r) ** 12) - ((_d / r) ** 6)))\nreturn V\n\nI keep getting the error TypeError: 'numpy.float64' object is not iterable. CalculateV runs fine by itself. I thought the error was that I wasn't returning a function, so I tried doing:\n# Calculate potential for NNs\nfor r in radius:\n val = ((4 * _e) * (((_d / r) ** 12) - ((_d / r) ** 6)))\n V.append(val)\nreturn val\n\nBut I'm still getting the same error. Seems the issues is with:\npoints = tuple(map(tuple, array))\n\nBut I don't understand why. Any help would be greatly appreciated!\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/40695917", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: MS Excel Function: Get data from a cell of a particular column and the current row I just want to say up front that I have very little skill in Excel.\nActually, I never use it.\nWhat I have been trying to do is create a function that gets the value of a cell of a particular column and the current row.\n\nFor example, I want the value of cell:\nColumn: B\nRow: ROW()\n\nWhat I will ultimately use this to do is average cells in a row.\nIf there's a better way to do that, feel free to give suggestions, although it would still be neat to learn how to do this if it's possible. =)\nI apologize if I messed up in presenting or posting my question; aside from Excel, I'm also new to stackoverflow.\n\nA: To get the content of cell (B,ROW()) do:\n= INDIRECT(CONCATENATE(\"B\", ROW()))\n\nIf you just want to calculate the average of a given line of numbers (e.g. first 10 cells in row 2):\n= AVERAGE(A2:J2)\n\nThe ':' represents an area from the upper left corner (A2) to the lower right (J2).\nAs mentioned by @MattClarke, you can use =AVERAGE(ROW_NUMBER:ROW_NUMBER) to calculate the average of a whole row (in this case row ROW_NUMBER) where you don't know the exact number of data fields. Pay attention not to use this formula in that exact row (row ROW_NUMBER) to avoid a circular reference. (Thanks @MattClarke for the hint!)\n\nA: Getting the average across a fixed range of cells is pretty easy: just use a formula like =average(A4:H4) where the parameter specifies the first and last cell. If you want the average of a whole row and you don't know how many columns of data there are, then you can use something like =average(8:8), where the number 8 is the row number of the data to be averaged.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/20109567", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Move Ubuntu server from 64gb SD to 16gb USB I'm tearing my hair out trying to figure this out.\nI've recently built myself a home server to store and save all my media. I installed Ubuntu server 12.04LTS and setup a bunch of stuff on a 64gb SD card i had spare. I've since bought a 16gb USB3 stick to take over the OS so i can use the SD card again. I had assumed moving the OS from drive to drive would be a fairly easy process...\nFirst i learned that you can't easily clone from a large drive to a small one. The total OS is only taking up 5gb of space at present, and even with a 3gb swap partition there's still more than enough raw space on the 16gb drive.\nI tried using dd which just filled the usb with a 16gb EXT4 partition then failed. I resized the EXT4 partition on the SD card to 9gb and left the remaining space unpartitioned. Tried dd again which just created another 16gb EXT4 partition before complaining the drive was full.\nClonezilla also failed, i forget the exact error message but it was still complaining that it doesn't have enough space on the destination drive (this was after it had been formatted and was only copying the 9gb EXT4 partition.\nSo, suggestions please!\n\nA: Problem is sudo dd if=/dev/sda of=/dev/sdb copies whole device not caring what partitions and how many are there.\nSolution is add count parameter \nsudo dd if=/dev/sda of=/dev/sdb count=...\n\nto find count number \nfdisk -u -l /dev/sda \n\nwhere sda is the disk you are copying from\nas count use number in the End column of last partition you want to copy. And make sure you are copying from/to correct devices.\nOther possibility should be (i am pretty sure this works would like some confirmation) copying the partition table first like its described here\nhttps://unix.stackexchange.com/questions/19047/how-can-i-quickly-copy-a-gpt-partition-scheme-from-one-hard-drive-to-another/19051#19051\nand then copy just the partition you want with \nsudo dd if=/dev/sda1 of=/dev/sdb1\n\nassuming you want to copy first partition\n", "meta": {"language": "en", "url": "https://askubuntu.com/questions/359918", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: how to defuse this binary bomb phase 4 I am having trouble this piece of code in assembly language.\nEssentially I have to input 2 numbers that matches 2 numbers the code is comparing with. \nOn line 0x08048c47 in phase_4, it compares the first input with 2, so I know the first input has to be 2. It then moves 4 spaces from the first input to next input, which then gets 2 subtracted from it. Now the (input-2) is compared with 2. It will continue the instruction if the inputs are below than or equal to 2. I've tested this with numbers 2,3,4 which pass the comparison. Other numbers greater than 4 and less than 2 do not pass the comparison and will cause the bomb to explode.\nI'm stuck on this part because the value being returned from func4 is not the same was the value represented at 0x08048c6e in phase_4, which is 8(%esp). On my computer when I debug it, it shows that it is 8, and the answers to my inputs 2,3,4 are 40, 60, 80 respectively.\ndisas func4\n0x08048bda <+0>: push %edi\n0x08048bdb <+1>: push %esi\n0x08048bdc <+2>: push %ebx\n0x08048bdd <+3>: mov 0x10(%esp),%ebx\n0x08048be1 <+7>: mov 0x14(%esp),%edi\n0x08048be5 <+11>: test %ebx,%ebx\n0x08048be7 <+13>: jle 0x8048c14 \n0x08048be9 <+15>: mov %edi,%eax\n0x08048beb <+17>: cmp $0x1,%ebx\n0x08048bee <+20>: je 0x8048c19 \n0x08048bf0 <+22>: sub $0x8,%esp\n0x08048bf3 <+25>: push %edi\n0x08048bf4 <+26>: lea -0x1(%ebx),%eax\n0x08048bf7 <+29>: push %eax\n0x08048bf8 <+30>: call 0x8048bda \n0x08048bfd <+35>: add $0x8,%esp\n0x08048c00 <+38>: lea (%edi,%eax,1),%esi\n0x08048c03 <+41>: push %edi\n0x08048c04 <+42>: sub $0x2,%ebx\n0x08048c07 <+45>: push %ebx\n0x08048c08 <+46>: call 0x8048bda \n0x08048c0d <+51>: add $0x10,%esp\n0x08048c10 <+54>: add %esi,%eax\n0x08048c12 <+56>: jmp 0x8048c19 \n0x08048c14 <+58>: mov $0x0,%eax\n0x08048c19 <+63>: pop %ebx\n0x08048c1a <+64>: pop %esi\n0x08048c1b <+65>: pop %edi\n0x08048c1c <+66>: ret \n\n\n\ndisas phase_4\n0x08048c1d <+0>: sub $0x1c,%esp\n0x08048c20 <+3>: mov %gs:0x14,%eax\n0x08048c26 <+9>: mov %eax,0xc(%esp)\n0x08048c2a <+13>: xor %eax,%eax\n0x08048c2c <+15>: lea 0x4(%esp),%eax\n0x08048c30 <+19>: push %eax\n0x08048c31 <+20>: lea 0xc(%esp),%eax\n0x08048c35 <+24>: push %eax\n0x08048c36 <+25>: push $0x804a25f\n0x08048c3b <+30>: pushl 0x2c(%esp)\n0x08048c3f <+34>: call 0x8048810 <__isoc99_sscanf@plt>\n0x08048c44 <+39>: add $0x10,%esp\n0x08048c47 <+42>: cmp $0x2,%eax\n0x08048c4a <+45>: jne 0x8048c58 \n0x08048c4c <+47>: mov 0x4(%esp),%eax\n0x08048c50 <+51>: sub $0x2,%eax\n0x08048c53 <+54>: cmp $0x2,%eax\n0x08048c56 <+57>: jbe 0x8048c5d \n0x08048c58 <+59>: call 0x8049123 \n0x08048c5d <+64>: sub $0x8,%esp\n0x08048c60 <+67>: pushl 0xc(%esp)\n0x08048c64 <+71>: push $0x6\n0x08048c66 <+73>: call 0x8048bda \n0x08048c6b <+78>: add $0x10,%esp\n0x08048c6e <+81>: cmp 0x8(%esp),%eax\n0x08048c72 <+85>: je 0x8048c79 \n0x08048c74 <+87>: call 0x8049123 \n0x08048c79 <+92>: mov 0xc(%esp),%eax\n0x08048c7d <+96>: xor %gs:0x14,%eax\n0x08048c84 <+103>: je 0x8048c8b \n0x08048c86 <+105>: call 0x8048790 <__stack_chk_fail@plt>\n0x08048c8b <+110>: add $0x1c,%esp\n0x08048c8e <+113>: ret \n\n\nA: 8(%esp) is the first number, under the framework of x86.\nenter 40 2 or 60 3 or 80 4 should work.\nEquivalent to the following logic\n#include \n#include \n\nvoid explode_bomb()\n{\n printf(\"explode bomb.\\n\");\n exit(1);\n}\n\nunsigned func4(int val, unsigned num)\n{\n int ret;\n\n if (val <= 0)\n return 0;\n\n if (num == 1)\n return 1;\n\n ret = func4(val - 1, num);\n ret += num;\n val -= 2;\n ret += func4(val, num);\n return ret;\n}\n\nvoid phase_4(const char *input)\n{\n unsigned num1, num2;\n\n if (sscanf(input, \"%u %u\", &num1, &num2) != 2)\n explode_bomb();\n\n if (num2 - 2 > 2)\n explode_bomb();\n\n if (func4(6, num2) != num1)\n explode_bomb();\n}\n\nint main()\n{\n phase_4(\"40 2\");\n phase_4(\"60 3\");\n phase_4(\"80 4\");\n printf(\"success.\\n\");\n return 0;\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/55028487", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}}
{"text": "Q: How can you make a function that returns a function in ocaml for an example, if a function receives a function as a factor and iterates it twice\nfunc x = f(f(x))\nI have totally no idea of how the code should be written\n\nA: You just pass the function as a value. E.g.:\nlet apply_twice f x = f (f x)\n\nshould do what you expect. We can try it out by testing on the command line:\nutop # apply_twice ((+) 1) 100\n- : int = 102\n\nThe (+) 1 term is the function that adds one to a number (you could also write it as (fun x -> 1 + x)). Also remember that a function in OCaml does not need to be evaluated with all its parameters. If you evaluate apply_twice only with the function you receive a new function that can be evaluated on a number:\nutop # let add_two = apply_twice ((+) 1) ;;\nval add_two : int -> int = \nutop # add_two 1000;;\n- : int = 1002\n\n\nA: To provide a better understanding: In OCaml, functions are first-class\nvalues. Just like int is a value, 'a -> 'a -> 'a is a value (I\nsuppose you are familiar with function signatures). So, how do you\nimplement a function that returns a function? Well, let's rephrase it:\nAs functions = values in OCaml, we could phrase your question in three\ndifferent forms:\n[1] a function that returns a function\n[2] a function that returns a value\n[3] a value that returns a value\nNote that those are all equivalent; I just changed terms.\n[2] is probably the most intuitive one for you.\nFirst, let's look at how OCaml evaluates functions (concrete example):\nlet sum x y = x + y\n(val sum: int -> int -> int = )\n\nf takes in two int's and returns an int (Intuitively speaking, a\nfunctional value is a value, that can evaluate further if you provide\nvalues). This is the reason you can do stuff like this:\nlet partial_sum = sum 2\n(int -> int = )\n\n\nlet total_sum = partial_sum 3 (equivalent to: let total_sum y = 3 + y)\n(int = 5)\n\npartial_sum is a function, that takes in only one int and returns\nanother int. So we already provided one argument of the function,\nnow one is still missing, so it's still a functional value. If that is\nstill not clear, look into it more. (Hint: f x = x is equivalent to\nf = fun x -> x) Let's come back to your question. The simplest\nfunction, that returns a function is the function itself:\nlet f x = x \n(val f:'a -> 'a = )\nf \n('a -> 'a = )\n\nlet f x = x Calling f without arguments returns f itself. Say you\nwanted to concatenate two functions, so f o g, or f(g(x)):\nlet g x = (* do something *)\n(val g: 'a -> 'b)\nlet f x = (* do something *)\n(val f: 'a -> 'b)\nlet f_g f g x = f (g x)\n(val f_g: ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = )\n\n('a -> 'b): that's f, ('c -> 'a): that's g, c: that's x.\nExercise: Think about why the particular signatures have to be like that. Because let f_g f g x = f (g x) is equivalent to let f_g = fun f -> fun g -> fun x -> f (g x), and we do not provide\nthe argument x, we have created a function concatenation. Play around\nwith providing partial arguments, look at the signature, and there\nwill be nothing magical about functions returning functions; or:\nfunctions returning values.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/71513663", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: No element found for selector: #react-select-17-option-0 (dropdown menu) I am trying to select a dropdown menu from a page but unable to select one of the options using puppetteer. I have checked the element selector. the page is only 1 frame this is the html source code enter image description here\nWhen I click on await page.click('input[id=\"react-select-7-input\"]') I get the dropdown in a screenshot but in the html instead of the value of the input being changed it adds a div with \"Regular Passport\" which is option 2\nenter image description here\n\nA: Well today it worked! I have no idea what was happening maybe the page had a bug?\nthis piece of code did it which I tried yesterday!\nawait page.click('#react-select-7-input');\nawait delay(wait_time);\nawait page.click('#react-select-7-option-2');\nawait delay(wait_time);\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/72861850", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}}
{"text": "Q: Listview repeating items with infinite scroll on Android I built a listview and implemented an infinite scroll, the listview is limited to show 5 items per load until it reaches the end, but it is duplicating the initial 5 items, I'll add some image so you can understand better:\n \nHow can I fix it?\npublic View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n\n\n // TODO Auto-generated method stub\n rootView = inflater.inflate(R.layout._fragment_clientes, container, false);\n\n rootView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT ));\n\n\n try {\n\n lv = (ListView) rootView.findViewById(R.id.listaClientes);\n\n clientes = new ArrayList();\n final ClientViewAdapter ad = new ClientViewAdapter(getActivity(), this, clientes);\n\n lv.setVerticalFadingEdgeEnabled(true);\n lv.setVerticalScrollBarEnabled(true);\n\n lv.setOnScrollListener(new EndlessScrollListener(){\n @Override\n public void onLoadMore(int page, int totalItemsCount) {\n new LoadMoreClientTask(progressBar,FragmentClientes.this,ad,getActivity()).execute(page);\n }\n });\n\n lv.addFooterView(footerLinearLayout);\n\n\n lv.setAdapter(ad);\n new LoadMoreClientTask(progressBar,this,ad,getActivity()).execute(1);\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return rootView;\n }\n\nThe Adapter:\npublic class ClientViewAdapter extends BaseAdapter {\n\n private Activity activity;\n private FragmentClientes frag;\n private List cliente;\n private static LayoutInflater inflater=null;\n\n public ClientViewAdapter(Context context, FragmentClientes fragmentClientes, List clientes) {\n this.inflater = LayoutInflater.from( context );\n this.cliente = clientes;\n\n frag = fragmentClientes;\n\n }\n\n public int getCount() {\n\n return cliente.size();\n }\n\n public Object getItem(int position) {\n return position;\n }\n\n public long getItemId(int position) {\n return position;\n }\n\n public View getView(int position, View convertView, ViewGroup parent) {\n\n View vi=convertView;\n ViewHolder holder;\n if(convertView == null){\n vi = inflater.inflate(R.layout.fragment_cliente_item, null);\n holder=new ViewHolder();\n holder.id = (TextView)vi.findViewById(R.id.clienteId);\n holder.nome = (TextView)vi.findViewById(R.id.clienteNome);\n holder.tipo = (TextView)vi.findViewById(R.id.clienteTipo);\n\n vi.setTag(holder);\n }else{\n holder = (ViewHolder)vi.getTag();\n }\n\n ClienteModel item = new ClienteModel();\n item = cliente.get(position);\n\n holder.id.setText(String.valueOf(item.getClientes_id()));\n holder.nome.setText(item.getNome());\n holder.tipo.setText(item.getTipo());\n\n return vi;\n }\n\n public void setData(List clientes){\n this.cliente.addAll(clientes);\n this.notifyDataSetChanged();\n }\n\n public class ViewHolder\n {\n TextView id;\n TextView nome;\n TextView tipo;\n\n }\n}\n\nAnd the LoadMoreTask snippet that gets the data from the database:\n protected Boolean doInBackground(Integer... parameters) {\n int npagina = parameters[0];\n cliente= new ArrayList();\n\n try {\n\n Repositorio mRepositorio = new Repositorio(context);\n\n\n List listaDeClientes = mRepositorio.getClientes(npagina,5,\"\");\n\n cliente = listaDeClientes;\n\n System.out.println(\"pagina \" + npagina);\n\n }catch (Exception e){\n e.printStackTrace();\n return false;\n }\n return true;\n }\n\nFunction getClientes:\n public List getClientes(Integer pagina, Integer limit, String consulta) throws SQLException {\n\n Integer offset = pagina * limit - limit;\n\n\n List listaDeRegistros = new ArrayList();\n\n\n\n if(consulta.isEmpty()) {\n query = \"SELECT * FROM \" + tabelaCLIENTES + \" WHERE credencial_id = \" + mSessao.getString(\"id_credencial\") + \" LIMIT \" + offset + \", \" + limit;\n }else {\n query = \"SELECT * FROM \" + tabelaCLIENTES + \" WHERE (credencial_id = \" + mSessao.getString(\"id_credencial\") + \") and (nome LIKE '%\"+consulta+\"%') LIMIT \" + offset + \", \" + limit;\n }\n\n System.out.println(query);\n\n try {\n\n Cursor mCursor = bd.rawQuery(query, null);\n\n if (mCursor.getCount() > 0) {\n if (mCursor.moveToFirst()) {\n do {\n ClienteModel mClienteModel = new ClienteModel();\n\n mClienteModel.setClientes_id(mCursor.getInt(mCursor.getColumnIndex(ClienteModel.Coluna.CLIENTES_ID)));\n mClienteModel.setId_rm(mCursor.getInt(mCursor.getColumnIndex(ClienteModel.Coluna.ID_RM)));\n mClienteModel.setCredencial_id(mCursor.getInt(mCursor.getColumnIndex(ClienteModel.Coluna.CREDENCIAL_ID)));\n mClienteModel.setNome(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna.NOME)));\n mClienteModel.setTipo(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna.TIPO)));\n mClienteModel.setInformacao_adicional(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna.INFORMACAO_ADICIONAL)));\n mClienteModel.set_criado(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna._CRIADO)));\n mClienteModel.set_modificado(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna._MODIFICADO)));\n mClienteModel.set_status(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna._STATUS)));\n\n listaDeRegistros.add(mClienteModel);\n\n } while (mCursor.moveToNext());\n }\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return listaDeRegistros;\n }\n\n\nA: When you are hitting the end to load more, your load code is just re-loading the same 5 entries. You need to check what you have already loaded and validate if it is the end or not to stop adding entries.\n\nA: try this one (exchange limit with offset):\nquery = \"SELECT * FROM \" + tabelaCLIENTES + \" WHERE credencial_id = \" + mSessao.getString(\"id_credencial\") + \" LIMIT \" + limit + \", \" + offset;\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/25880815", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Docker Build Error: executor failed running [/bin/sh -c npm run build]: exit code: 1 with NextJS and npm I have a NextJS app with the following Dockerfile.production:\nFROM node:16-alpine AS deps\n\nENV NODE_ENV=production\n\nRUN apk add --no-cache libc6-compat\nWORKDIR /app\n\nCOPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./\nRUN \\\n if [ -f yarn.lock ]; then yarn --frozen-lockfile; \\\n elif [ -f package-lock.json ]; then npm ci; \\\n elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \\\n else echo \"Lockfile not found.\" && exit 1; \\\n fi\n\nFROM node:16-alpine AS builder\n\nENV NODE_ENV=production\n\nWORKDIR /app\n\nCOPY --from=deps /app/node_modules ./node_modules\nCOPY . .\n\nRUN npm run build\n\nFROM node:16-alpine AS runner\nWORKDIR /app\n\nENV NODE_ENV production\n\nRUN addgroup --system --gid 1001 nodejs\nRUN adduser --system --uid 1001 nextjs\n\nCOPY --from=builder /app/public ./public\n\nCOPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./\nCOPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static\n\nUSER nextjs\n\nCMD [\"node\", \"server.js\"]\n\nThis is my docker-compose.production.yml:\n\nservices:\n app:\n image: wayve\n build:\n dockerfile: Dockerfile.production\n ports:\n - 3000:3000\n\nWhen I run docker-compose -f docker-compose.production.yml up --build --force-recreate in my terminal (at the root) I get the following build error:\nfailed to solve: executor failed running [/bin/sh -c npm run build]: exit code: 1\nI do not see any issues with my docker-compose file or my Dockerfile. How can I fix this issue? TYA\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/75042423", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}}
{"text": "Q: Using only part of a pattern in SSH Config Hostname I have an SSH config like the one below, which works great for:\nssh b21\nssh 23\nssh s267\n\nExample .ssh/config (hostname passed is slotted in at %h):\nhost s*\n HostName atrcu%h.example.com\n User example\n Port 22\nhost b*\n HostName atrcx%h.example.com\n User example\n Port 22\nhost ??*\n HostName atvts%h.example.com\n User example\n Port 2205\n\nbut I'd like to include the username in the host:\nssh b21ex\n\nwhich would ssh to:\nexample@atvts21.example.com\n\nbut instead will:\natvts21ex.example.com\n\nis their any way to cut/modify %h as it's passed and perhaps have the connection match more patterns to get a username along the way?\n\nA: You can do what you describe in the examples with the match specification instead of host. It's another way to specify a host, or a set of hosts.\nFor example:\nMatch user u* host t*\n Hostname %hest.dev\n User %r\n\nThis will match against a user pattern and a target host pattern.\nThe command line will then be something like ssh u@t, resulting in this substitution: u@test.dev.\nHere's a snippet from the ssh debug output:\n\ndebug2: checking match for 'user u* host t*' host t originally t\ndebug3: /Users/_/.ssh/config line 2: matched 'user \"u\"' \ndebug3: /Users/_/.ssh/config line 2: matched 'host \"t\"' \ndebug2: match found\n...\ndebug1: Connecting to test.dev port 22.\ndebug1: Connection established.\n...\nu@test.dev's password:\n\n\nmatch can match against a couple of other things (and there's an option to execute a shell command) but otherwise it's just like host. The ssh client options that go in there are the same ones (e.g. you can specify and IdentityFile that will be used with the matching spec)\nYou can read more in the man page:\nssh_config\n\nA: I think you will have to create separate HostName/User entries for each possible abbreviation match. You could then use %r to access separate identity files for each user. This would allow you to skip using user@host for login at the expense of creating a more complex configuration file.\nYou might have better luck writing a script or shell alias that unmunges your abbreviations and hands them to ssh ready to go.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/17169292", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "12"}}
{"text": "Q: How to assert json path value is greater than value? Given the following JSON that is returned from a REST call:\n{\"Statistik Eintraege\":\n[{\"Wert\":\"1\",\"Anzahl\":41},\n{\"Wert\":\"\",\"Anzahl\":482},\n{\"Wert\":\"-3\",\"Anzahl\":1},\n{\"Wert\":\"-1\",\"Anzahl\":3},\n{\"Wert\":\"-2\",\"Anzahl\":3}],\n\"Statistik Typ\":\"BlahStatistik\"}\n\n... I want to verify that'Anzahl' of Wert='' is greater than 400 (is in this example: 482).\nWhat I tried in my java integration test is:\n.andExpect(jsonPath(\"$..[?(@.Wert == '')].Anzahl\", greaterThan(400)));\n\nThe exception:\n\njava.lang.ClassCastException: class net.minidev.json.JSONArray cannot be cast to class java.lang.Comparable (net.minidev.json.JSONArray is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')\n\n at org.hamcrest.comparator.ComparatorMatcherBuilder$1.compare(ComparatorMatcherBuilder.java:22)\n at org.hamcrest.comparator.ComparatorMatcherBuilder$ComparatorMatcher.describeMismatchSafely(ComparatorMatcherBuilder.java:86)\n at org.hamcrest.TypeSafeMatcher.describeMismatch(TypeSafeMatcher.java:82)\n at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:18)\n at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:74)\n at org.springframework.test.web.servlet.result.JsonPathResultMatchers.lambda$value$0(JsonPathResultMatchers.java:87)\n at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)\n at \n\nWhat else could I try?\n\nA: The JsonPath operator [?()] selects all elements matching the given expression. Therefore, the result is a json array.\nIn the example [?(@.Wert == '')] matches all json nodes with the field Wert having an empty value. Your json sample has only single item matching the predicate, but in general there could be multiple. To fix you have either to define a more specific expression matching only a single element or to adjust the matcher to work on a collection.\nMatching collection:\n.andExpect(jsonPath(\"$..[?(@.Wert == '')].Anzahl\", everyItem(greaterThan(400))))\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/68410880", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}}
{"text": "Q: Parse 't'/'f' as booleans during CSV mapping Consider I have a CSV as such:\nname,city,active\nabc,bcde,t\nxyz,ghj,f\n\nIf I wanted to map this to a model how would I convert the 't' or 'f' to proper booleans. I am using jackson-dataformat-csv mapping to do this \nCsvSchema csvSchema = CsvSchema.emptySchema().withHeader().withNullValue(\"\");\nCsvMapper csvMapper = new CsvMapper();\ncsvMapper.setPropertyNamingStrategy(SNAKE_CASE);\ncsvMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\nMappingIterator iterator = csvMapper.readerWithTypedSchemaFor(Object.class).with(csvSchema).readValues(fileFromResponse);\nList