{"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
\n\n
\n
\n
\n
\n
\n {React.cloneElement(formStep, {currentLanguage: languageReg})}\n
\n
\n
\n
\n
\n
\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
{language.businessInfoConfig}
\n
{language.businessBoxDesc}
\n
\n
\n
\n {language.businessDesc}\n
\n
\n
\n \n
\n
\n \n
\n\n
\n \n
\n\n
\n \n
\n\n
\n \n
\n\n
\n \n
\n\n
\n\n \n
\n
\n \n
\n
\n
\n
\n
\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
{language.personalInfoConfig}
\n
{language.personalBoxDesc}
\n
\n
\n
\n {language.personalDesc}\n
\n
\n \n
\n
\n \n
\n\n
\n \n
\n\n
\n \n
\n
\n\n
\n \n
\n\n
\n \n
\n\n
\n \n
\n
\n \n
\n\n
\n
\n
\n
\n
\n
\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

This is the order table

\n <%- include (\"./partials/messages\"); %>\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
#CustomerAddressCityStateZipPhoneStatus
1
\n
\n
\n\n\n\nA: server.js\nconst express = require('express')\nconst mongoose = require('mongoose')\nconst Shipment= require('./models/shipment')\nconst app = express()\n\nmongoose.connect('mongodb://localhost/myFirstDatabase ', {\n useNewUrlParser: true, useUnifiedTopology: true\n})\n\napp.set('view engine', 'ejs')\napp.use(express.urlencoded({ extended:false }))\n\napp.get('/', async (req,res) => {\n const data= await Shipment.find()\n res.render('index', { data: data})\n})\n\napp.listen(process.env.PORT || 5000);\n\nindex.ejs\nbelow is part of your ejs file\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n <% data.forEach((e, index)=> { %> \n \n \n \n \n \n \n \n \n \n \n <% }) %> \n \n
#CustomerAddressCityStateZipPhoneStatus
<%= index %><%= e.Customer %><%= e.Address %><%= e.City %><%= e.State %><%= e.Zip %><%= e.Phone %><%= e.Status %>
\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\"photobucket\"\n\"something\"\n\"something\"\n\"photobucket\"\n\nthis returns \n$ grep -o ']*src=\"[^\"]*photobucket[^>]*>' infile\n\n\"something\"\n\"something\"\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 \n \n

{{ item.name }}

\n \n

{{ item.id }}

\n

{{ item.categories[0].name }}

\n

{{ item.name }}

\n\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 \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 Clinical Molecular Incident Reporting System\n \n {% if user.is_authenticated %}\n search incidents | \n report incident | \n resolve incident\n {{ user.username }} | logout \n {% else %}\n Login \n {% endif %}\n \n
\n {% block content %}\n {% endblock content %}\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 data = iterator.readAll();\n\nCurrently the mapping fails with this error message:\nCannot deserialize value of type `java.lang.Boolean` from String \"t\": only \"true\" or \"false\" recognized\n\nIs there any way I can specify in the schema that 't' or 'f' should be taken as booleans. Or is there another way I can deserialize it?\n\nA: You could register a custom JacksonModule with a mapper for Boolean type:\nprivate val YNToBooleanDeserializer = object : JsonDeserializer() {\n override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Boolean {\n return p.readValueAs(String::class.java) == \"t\"\n }\n}\n\nto register, use:\ncsvObjectMapper.registerModule(SimpleModule().addDeserializer(Boolean::class.java, YNToBooleanDeserializer))\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/48023491", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: Why do we need gulp over karma? I am new to gulp and karma tool.I have searched google and worked on small testcases and executed successfully. \nIn karma we are configuring the unit testcases js files that are to be tested and run using the command 'start karma karma.conf.js'\nIn gulp we are configuring the karma config file and execute using the command 'gulp test'\nwhat benefits we are getting while running a gulp test over karma directly?\n\nA: One advantage of using gulp is that you can then orchestrate more complicated tasks based on that task. For example, you might want a gulp task that first builds the project then executes the unit tests. You could then execute that with one command rather than two commands.\nHowever if you're only running the gulp task that runs karma then there won't be any advantage in using gulp (other than the command being easier to type).\nYou can look at the Gulp Recipes page to see other tasks you can accomplish with gulp.\n\nA: The only thing I can really think of is getting gulp to source all the appropriate 3rd party JS files required to run the tests using something like wiredep. For example\nvar gulp = require('gulp'),\n Server = require('karma').Server,\n bowerDeps = require('wiredep')({\n dependencies: true,\n devDependencies: true\n }),\n testFiles = bowerDeps.js.concat([\n 'src/**/*.js',\n 'test/**/*.js'\n ]);\n\ngulp.task('test', function(done) {\n new Server({\n configFile: 'karma.conf.js',\n files: testFiles,\n singleRun: true\n }, function(exitStatus) {\n if (exitStatus) {\n console.warn('Karma exited with status', exitStatus);\n }\n done();\n }).start();\n});\n\nOtherwise, you have to maintain the files array in your karma.conf.js file manually.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/34033971", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: How to mock getWcmMode() using mockito In AEM, there is a Java USE class wherein following code is present getWcmMode().isEdit()\nNow, I am struggling to mock this object using mockito in Test java class. Is there any way we can do that?\n\nA: getWcmMode() is a final method in WCMUsePojo, mockito does not support mocking final methods by default.\nyou will have to enable it by creating a file named org.mockito.plugins.MockMaker in classpath (put it in the test resources/mockito-extensions folder) and put the following single line\nmock-maker-inline\n\nthen you can use when to specify function return values as usual-\n @Test\n public void testSomeComponetnInNOTEDITMode() {\n //setup wcmmode\n SightlyWCMMode fakeDisabledMode = mock(SightlyWCMMode.class);\n when(fakeDisabledMode.isEdit()).thenReturn(false);\n\n //ComponentUseClass extends WCMUsePojo\n ComponentUseClass fakeComponent = mock(ComponentUseClass.class);\n when(fakeComponent.getWcmMode()).thenReturn(fakeDisabledMode);\n\n assertFalse(fakeComponent.getWcmMode().isEdit());\n\n //do some more not Edit mode testing on fakeComponent.\n\n }\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/46719848", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Query post if has two of the categories I'm banging my head here. I can't seem to figure out what's wrong with this it works although if a post has more than two categories is doesn't seem to show. What is wrong here?\n
\n \n
\n 'post',\n 'category__and' => array(117,123),\n );\n\n // The Query\n $the_query_1 = new WP_Query( $args_1 ); ?>\n\n have_posts() ) {\n while ( $the_query_1->have_posts() ) {\n $the_query_1->the_post(); ?>\n\n \n \">\n \n \n
\n\n \n
\n
\n\n\nA: You need to edit line 7. \n'category__and' => array(117,123),\n\nThe category__and parameter doesn't use a string for the category IDs. Write the array like this:\n 'category__and' => array(\n '117',\n '123'\n )\n);\n\n", "meta": {"language": "en", "url": "https://wordpress.stackexchange.com/questions/319445", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Url parameter read twice so language service cant pick Updated\nI am working on angular5 application where I need to take some data from URL query string.\nI am able to get the data but somehow I am getting undefined value which is converted into my expected value later. I want to use this data from query string to decided what language is to be used. \nTranslate service is working fine if I hardcode .The code is working fine if I hardcode the value in translate.use('en'); I want to assign this value by reading from query string\nSo basically I want translate.use(this.id) (this.id from url to be passed from query string).\napp.component\n import {Component} from '@angular/core';\nimport {TranslateService} from '@ngx-translate/core';\nimport { ActivatedRoute } from '@angular/router';\n\n@Component({\n selector: 'app-root',\n template: `\n
\n

{{ 'HOME.TITLE' | translate }}

\n \n
\n\n `,\n})\nexport class AppComponent {\n id: string;\n constructor(public translate: TranslateService,private route: ActivatedRoute) {\n translate.addLangs(['en', 'fr']);\n translate.setDefaultLang('en');\n\n //const browserLang = translate.getBrowserLang();\n //translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');\n const browserLang = translate.getBrowserLang();\n translate.use('en');\n }\n ngOnInit() {\n this.route.queryParams.subscribe(params => {\n console.log(params);\n this.id = params['id'];\n })\n}\n}\n\nCalling way- http://localhost:4200/?id=en or http://localhost:4200/?id=fr\napp.module\nimport { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport {HttpClient, HttpClientModule} from '@angular/common/http';\nimport {TranslateModule, TranslateLoader} from '@ngx-translate/core';\nimport {TranslateHttpLoader} from '@ngx-translate/http-loader';\nimport { RouterModule, Routes } from '@angular/router'\n\n// AoT requires an exported function for factories\nexport function HttpLoaderFactory(httpClient: HttpClient) {\n return new TranslateHttpLoader(httpClient);\n}\n\n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,RouterModule.forRoot([]),\n HttpClientModule,\n TranslateModule.forRoot({\n loader: {\n provide: TranslateLoader,\n useFactory: HttpLoaderFactory,\n deps: [HttpClient]\n }\n })\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }\n\nI also have i18n folder with json translations.\nThe code is working fine if I hardcode the value in translate.use('en');\nI want to assign this value by reading from query string \nSo basically I want translate.use(this.id) (this.id from url to be passed from query string).\n\n\nA: Angular does not use ? in routing, instead it uses ; for multiple parameters\n\nThe optional route parameters are not separated by \"?\" and \"&\" as they\n would be in the URL query string. They are separated by semicolons \";\"\n This is matrix URL notation\u2014something you may not have seen before.\n\nIn your case, you are passing a single parameter. So Your route should be similar to \n{path: ':param1' component: AppComponent}\n\nThen you would be able to access the param1 using the code written in ngOnInit method. The code should be as shown below\nngOnInit() {\n this.activatedRoute.params.subscribe(params=>console.log(params['param1']));\n}\n\nIf you are planning to use query parameters, then you should use queryParams from ActivateRoute and url should be http://localhost:4216/?param1=en and use below code to access data\nngOnInit(){\n this.activatedRoute.queryParams.subscribe(params=>console.log(params['param1']));\n}\n\nAlso including a working example\n\nA: It was a silly mistake.\nTh code was fine but What I was doing was using ng onit to get data from purl string and constructor to inject translation service and was trying to exchange data between thhose two .Since I could not get any way/getting error ,I added both in constructor and removed onit for getting url parameter(I know Silly!)\nimport {Component} from '@angular/core';\nimport {TranslateService} from '@ngx-translate/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { AppGlobals } from '../app/app.global';;\n\n@Component({\n selector: 'app-root',\n template: `\n
\n

{{ 'HOME.TITLE' | translate }}

\n \n
\n\n `,\n providers: [ AppGlobals]\n})\nexport class AppComponent {\n param1: string;\n\n constructor(public translate: TranslateService,private route: ActivatedRoute,private _global: AppGlobals) {\n console.log('Called Constructor');\n this.route.queryParams.subscribe(params => {\n this.param1 = params['param1'];\n\n translate.use(this.param1);\n });\n // this.route.queryParams.subscribe(params => {\n\n // this._global.id = params['id'];\n //console.log('hello'+this._global.id);\n\n //})\n\n //translate.addLangs(['en', 'fr']);\n //translate.setDefaultLang('en');\n\n //const browserLang = translate.getBrowserLang();\n //translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');\n //const browserLang = translate.getBrowserLang();\n console.log('hello'+this._global.id);\n translate.use(this._global.id);\n }\n ngOnInit() {\n\n}\n\n\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/50834611", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: FragmentManager has been destroyed EDIT: It seems that this only happens if my previous activity is in landscape, and the setRequestedOrientation() is portrait, what could possibly be the problem?\nI have a code in an activity, which starts a Volley request to a REST API to retrieve some data, and have a callback which will start a fragment if the data was successfully retrieved. However this only works in portrait mode, in landscape mode, it will throw exception with \"Fragment Manager Has Been Destroyed\".\nI can't seem to find the root of this problem, therefore I can't try any alternative solutions.\nThis is my onCreate() method of this activity:\n@Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setRequestedOrientation(SettingsManager.getOrientationSettings(this));\n setContentView(R.layout.activity_settings);\n\n findViews();\n setListeners();\n getSettings();\n }\n\ngoSettings() will retrieve the data, set requested orientation will either be ActivityInfo.SCREEN_ORIENTATION_PORTRAIT or ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE.\nMy loadFirstPage() method:\n private void loadFirstPage() {\n VMSSettingsPageOneFragment fragment = new VMSSettingsPageOneFragment();\n FragmentManager fm = getSupportFragmentManager();\n\n fm.beginTransaction()\n .replace(R.id.settings_fragment_container, fragment)\n .commit();\n }\n\nThe error message:\nE/FileUtils: File Write Exception\n java.lang.IllegalStateException: FragmentManager has been destroyed\n at androidx.fragment.app.FragmentManager.enqueueAction(FragmentManager.java:1853)\n at androidx.fragment.app.BackStackRecord.commitInternal(BackStackRecord.java:321)\n at androidx.fragment.app.BackStackRecord.commit(BackStackRecord.java:286)\n at com.timeteccloud.icomm.platformVMS.settingsActivity.VMSSettingsActivity.loadFirstPage(VMSSettingsActivity.java:87)\n\n\nA: You can implement a check before committing the fragment transaction, something as follows.\n public boolean loadFragment(Fragment fragment) {\n //switching fragment\n if (fragment != null) {\n FragmentTransaction transaction = fm.beginTransaction();\n transaction.replace(R.id.main_frame_layout, fragment);\n\n if (!fm.isDestroyed())\n transaction.commit();\n return true;\n }\n return false;\n }\n\n\nA: maybe you can use parentFragmentManager.beginTransaction() instead of childFragmentManager in code will look like\ndialog.show(parentFragmentManager.beginTransaction(), BaseFragment.TAG_DIALOG)\n\n\nA: Hi you can just use it like this way\ndeclare a handler\nHandler handler = new Handler()\n\nand Then put commit in to post delayed of handler\n// this is a hack to fix fragment has been destroyed issue do not put Transaction.replace\n // into handler post delayed\n handler.postDelayed({\n // transaction.addToBackStack(null)\n transaction.commit()\n },500)\n\n\nDo not place other things in post delayed ie. adding fragment to transaction (or replace transaction.replace(fragment,containerid,tag))\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/58814735", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "7"}} {"text": "Q: Can we have moveable interface Items? I would very much like to have the ability to move items in the right hand column according to my liking and have the state saved for my next login, much like the iGoogle interface.\nThis is simply because when I drill down into a tag on SO, I would prefer not to have to scroll down past related tags to see my chosen interesting tags.\nI wonder if anyone else has had similar thoughts, or thinks this is a good idea?\n\nA: So... you want to turn Stack Overflow into a portal? \nWell, it is my homepage.....\n", "meta": {"language": "en", "url": "https://meta.stackexchange.com/questions/56280", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: Problem with 'string match' and variable I've been searching for hours and trying multiple things. This is the expect code snippet which works.\n foreach line [split $expect_out(buffer) \\r\\n] {\n if {[string match {*word*} $line]} {\n send_user \"$line\\r\\n\"\n set acctnum [exec echo $line | cut -d\\. -f1]\n send_user \"$acctnum\\n\\r\"\n }\n }\n\nThe output is:\n2. word\n2\n\n\"word\" without the asterisks and \"word\" with an asterisk on either end does not work. I need this to be a variable which is provided on the command line. I have found no combination which will work with a variable.\nPlease provide suggestions to get this to work.\n\nA: I found the answer in Match a string with a substring in Expect scripting. I believe I had looked at that question before, but didn't read closely enough. The answer is to replace the curly braces with double quotes.\n foreach line [split $expect_out(buffer) \\r\\n] {\n if {[string match \"*$varname*\" $line]} {\n send_user \"$line\\r\\n\"\n set acctnum [exec echo $line | cut -d\\. -f1]\n send_user \"$acctnum\\n\\r\"\n }\n }\n\n", "meta": {"language": "en", "url": "https://unix.stackexchange.com/questions/609729", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: for each not updating variables When using the AS3 for each construct I find that I can't update the members of the array that im iterating.\nfor each( obj:Object in array ){\n obj = new Object();\n}\n\nwhen I loop over the array again they will still have the same values as before the loop.\nAm I stuck with using tradition for-loops in this situation or is there a way to make the updates stick.\n\nA: As Daniel indicated, you are instantiating a new object to the obj reference instead of the array element. Instead, access the array by ordinal:\nvar array:Array = [{}, {}, {}];\n\nfor (var i:uint = 0; i < array.length; i++)\n{\n array[i] = {};\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/17073211", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Output of Restricted Boltzmann Machine energy function I'm just starting to learn about Restricted Boltzmann Machines (RBMs). So far I understand that they try to predict/output the inputs that are fed to them. If the RBM is trained on input where each record is a vector, then the RBM should likewise learn to output a vector.\nWhile reading about RBMs, I keep coming across references to an \"energy function\", which I don't really understand, but my guess is that it represents the formula of a trained RBM. While reading through Geoffrey Hinton's tutorial I came across the following:\n\nWhat confuses me about this paragraph is that it seems to suggest that the energy function outputs a scalar not a vector, which is inconsistent with my understanding above. Does it not actually output a scalar? Does an energy function not actually represent the architecture of a trained RBM and the means of calculating an output/prediction? Also, the article goes on to state that the variables a and b correspond to biases. If they're actually biases, why are they being multiplied with the vectors v and h? Aren't biases always supposed to be added only?\n\nA: The Restricted Boltzmann Machine is an Energy - based model. The energy function produces a scalar value which basically corresponds to the configuration of the model and it is an indicator of the probability of the model being in that configuration. If the model is configured to favor low energy, then configurations leading to low energy will have a higher probability. Learning the model means looking for configurations that modify the shape of the energy function to drive to low energy configurations. As far as the biases go you basically calculate the dot product between the biases and the corresponding units (visible or hidden) to calculate their contribution to the energy function.\n", "meta": {"language": "en", "url": "https://stats.stackexchange.com/questions/215662", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: play video in app through video out http://www.google.com/products/catalog?oe=UTF-8&gfns=1&q=iphone+video+out+cable&um=1&ie=UTF-8&cid=17045329161497634089&ei=JpU1TcymOcnogQfC25C7Cw&sa=X&oi=product_catalog_result&ct=result&resnum=5&ved=0CCgQ8wIwBA#\nI want to know if its possible to play video from an app through a lead like this onto a TV or something similar. I've heard that the functionality is not available in apps. Is this true?\nIf its not true and its perfectly possible what exactly is possible? Is it possible to push a different video output to the external TV as that that is on the device?\nThanks\nTom\n\nA: I suppose that cable will have the same functionality as a connector for a projector or second display right? \nIf that is the case then the answer is: IS POSSIBLE.\nBut, everything that is want to show in the second display have to be explicitly done by you. There is no mirroring system or something alike. \nRead here, there is a sample app also :)\nhttp://mattgemmell.com/2010/06/01/ipad-vga-output\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/4724600", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: QGIS/QField - Joining updated and new features to original shapefile I am currently working in QGIS 2.18 with Qfield to collect address information.\nI currently have a list of addresses (.csv) that were given as part of the project which contains a variety of information, including point XY co-ordinate for each address (although these appear to be wrong and need geocoding.)I have made this into a shapefile for use in QField offline editing.\nSamplers will use Qfield and walk around each town, moving the existing address point features to within buildings polygons at the correct addresses and updating the attributes of each point with the required information. They will also be adding new point features for those addresses which are currently not in the existing address list. \nEach evening, I download the QField shapefiles from each of the samplers containing the updated existing points and the new points that they have taken in the day. \nIf it was just a case of updating the old points with the new attribute information, I understand that I can join across a common field and repopulate each field with the new information provided. I have tried this, however with multiple files to add (5 samplers/folders a day) and manually repopulating the old columns with the updated fields is taking an enormous amount of time especially as I need the new XY coordinate for each feature.\nIt also means that my original shapefile is getting confusing as I have so many joined columns. \nAs they will also be adding new point features, I cannot find a way to add these new points without updating the .csv itself and re-adding it to QGIS as they do not have a common column with the original .csv to be included in the join above. \nCan anyone suggest the ideal/most efficient way of using the shapefiles from each sampler to update the attributes for each existing point feature as well as including the newly created ones? \nI chose QField as QGIS is the software i'm most comfortable working in. If there is a significantly easier alternative to Qfield for gathering and integrating the new data then yes I am more than happy to try others but they would have to be free.\n\nA: As topic starter indicated free alternatives are allowed, I recommend to try NextGIS software:\nNextGIS Mobile + nextgis.com cloud + QGIS (NextGIS Connect plugin).\nThis software allow you to automatic synchronize your field data and desktop GIS. \nThe steps to get this functionality are follows:\n\n\n*\n\n*Register at nextgis.com and create your free web GIS (instructions).\n\n*Install NextGIS Connect plugin in QGIS. Add your web GIS to plugin (instructions).\n\n*Upload your Shape files to your web GIS.\n\n*Install NextGIS Mobile on your mobile device and add layers from your web GIS. Check if layer is synced with web GIS (two arrows near the layer icon in layers list or check in web GIS settings) \n\n*Go to field and add/modify your spatial data. No internet connection required to edit spatial data (the sync will perform when you mobile device get connection to the cloud).\n\n*Additionally you can create WFS service on you layer in web GIS and open it in QGIS. The edits in QGIS will transfer to NextGIS Mobile and vice versa.\n\n\nAll this software are Open source. In this scenario the free plan is enough to achieve synchronization functionality. \nDisclosure: I'm developer at NextGIS.\n", "meta": {"language": "en", "url": "https://gis.stackexchange.com/questions/303401", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: How to aggregate timestamp data in Spark to smaller time frame I'm working on a project using New York taxi data. The data contain records for pickup location (PULocationID), and the timestamp (tpep_pickup_datetime) for that particular pick-up record.\n\nI want to aggregate the data to be hourly for each location. The aggregation should have an hourly count of pick-ups per location.\n\nA: The information you provided is a bit lacking. From what I understood, these could be possible aggregation options.\nUsing date_trunc\nfrom pyspark.sql import functions as F\n\ndf = df.groupBy(\n F.date_trunc('hour', 'tpep_pickup_datetime').alias('hour'),\n 'PULocationID',\n ).count()\n\ndf.show()\n# +-------------------+------------+-----+\n# | hour|PULocationID|count|\n# +-------------------+------------+-----+\n# |2020-01-01 00:00:00| 238| 1|\n# |2020-01-01 02:00:00| 238| 2|\n# |2020-01-01 02:00:00| 193| 1|\n# |2020-01-01 01:00:00| 238| 2|\n# |2020-01-01 00:00:00| 7| 1|\n# +-------------------+------------+-----+\n\nUsing window\nfrom pyspark.sql import functions as F\n\ndf = df.groupBy(\n F.window('tpep_pickup_datetime', '1 hour').alias('hour'),\n 'PULocationID',\n ).count()\n\ndf.show(truncate=0)\n# +------------------------------------------+------------+-----+\n# |hour |PULocationID|count|\n# +------------------------------------------+------------+-----+\n# |[2020-01-01 02:00:00, 2020-01-01 03:00:00]|238 |2 |\n# |[2020-01-01 01:00:00, 2020-01-01 02:00:00]|238 |2 |\n# |[2020-01-01 00:00:00, 2020-01-01 01:00:00]|238 |1 |\n# |[2020-01-01 02:00:00, 2020-01-01 03:00:00]|193 |1 |\n# |[2020-01-01 00:00:00, 2020-01-01 01:00:00]|7 |1 |\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/72827699", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: How can I get the derivative of these two functions? I have searched about the derivatives and approximated them by hand but they do not match up to what I am getting when i try to calculate them. Sorry If I cannot annotate them correctly, I hope you can understand my meaning...\nEquation 1\n$$f(x) = \\frac{I}{\\sqrt{x/tn}}$$\nwhere $I$ and $tn$ are constants. I have gotten the answer of...\n$$f(x) = -\\frac{I^2 \\cdot tn}{x^2}$$\nbut it is not adding up when I graph it out...while my hand approximation is much closer\n\nA: With the tip from above we get for the first derivative $$i\\cdot t_n\\frac{-1}{2}x^{-3/2}$$\nAnalogously we can write for the second equation\n$$f(x)=-i^2\\cdot t_nx^{-2}$$ Thus, we get $$f'(x)=2\\cdot i^2\\cdot t_nx^{-3}$$ After the exponential rule $$ (x^n)'=nx^{n-1} $$\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/2194788", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Declaring a global CSS variable generates error in Dreamweaver As found here I am trying to declare a golbal CSS variable in a root element. The html displays correctly and I cannot find any error except the one Dreamweaver tells me:\n\n*\n\n*\"Expected RBRACE at line 5, col 3\"\n\n*\"Expected RBRACE at line 6, col 3\"\n\n*...\n\nIt seems as I could ignore DW here, but it leaves a bad feeling in my gut. Am I missing something obvious, or is DW wrong?\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/69884165", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: file_get_contents \u043d\u0435 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 \u0438\u0437 \u043a\u043b\u0430\u0441\u0441\u0430 \u0412\u0441\u0435\u043c \u043f\u0440\u0438\u0432\u0435\u0442! \u0421\u0442\u043e\u043b\u043a\u043d\u0443\u043b\u0441\u044f \u0441\u043e \u0441\u0442\u0440\u0430\u043d\u043d\u043e\u0439 \u043f\u0440\u043e\u0431\u043b\u0435\u043c\u043e\u0439. \u0413\u0440\u0443\u0436\u0443 \u043a\u043e\u043d\u0444\u0438\u0433\u0438 YML, \u0437\u0430\u0431\u0438\u0440\u0430\u044e \u0444\u0430\u0439\u043b\u0438\u043a \u0447\u0435\u0440\u0435\u0437 file_get_contents \u043d\u0430 \u043f\u0430\u0440\u0441\u0438\u043d\u0433 \u043d\u0430\u043f\u0440\u044f\u043c\u0443\u044e \u0438\u0437 \u0438\u043d\u0434\u0435\u043a\u0441\u0430 - \u0432\u0441\u0435 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 \u0437\u0430\u043c\u0435\u0447\u0430\u0442\u0435\u043b\u044c\u043d\u043e. \u0410 \u0432\u043e\u0442 \u0438\u0437-\u043f\u043e\u0434 \u043c\u043e\u0435\u0433\u043e \u043a\u043b\u0430\u0441\u0441\u0430 \u043a\u043e\u043d\u0442\u0435\u043a\u0441\u0442\u0430 \u043e\u043d \u043d\u0435 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442. \u0414\u043e\u0448\u043b\u043e \u0434\u043e \u043c\u0430\u0440\u0430\u0437\u043c\u0430 - \u0437\u0430\u043a\u043e\u043c\u043c\u0435\u043d\u0442\u0438\u043b \u0432\u0435\u0441\u044c \u0444\u0443\u043d\u043a\u0446\u0438\u043e\u043d\u0430\u043b, \u043e\u0441\u0442\u0430\u0432\u0438\u043b \u043f\u0443\u0441\u0442\u043e\u0439 \u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u043e\u0440 \u0438 \u0441\u0434\u0435\u043b\u0430\u043b \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u0443\u044e \u043f\u0443\u0431\u043b\u0438\u0447\u043d\u0443\u044e \u0444\u0443\u043d\u043a\u0446\u0438\u044e \u0441 \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u0435\u043c \u0444\u0430\u0439\u043b\u0430 \u0438 \u043f\u043e\u043f\u044b\u0442\u0430\u043b\u0441\u044f \u0432\u044b\u0432\u0435\u0441\u0442\u0438 \u0435\u0433\u043e \u0441\u043e\u0434\u0435\u0440\u0436\u0438\u043c\u043e\u0435 \u0447\u0435\u0440\u0435\u0437 echo \u043d\u0430 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0443. \u041d\u0435 \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442. \u0421 \u0447\u0435\u043c \u044d\u0442\u043e \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0441\u0432\u044f\u0437\u0430\u043d\u043e? \u0421\u043f\u0430\u0441\u0438\u0431\u043e\n\nA: file_get_content \u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 \u043d\u043e\u0440\u043c\u0430\u043b\u044c\u043d\u043e. \u041f\u0440\u043e\u0441\u0442\u043e \u0432\u044b \u043d\u0435 \u043d\u0430\u0443\u0447\u0438\u043b\u0438\u0441\u044c \u0435\u0449\u0435 \u041e\u041e\u041f. \u041f\u0440\u043e\u0447\u0438\u0442\u0430\u0439 \u043f\u0440\u043e \u043e\u0431\u043b\u0430\u0441\u0442\u044c \u0432\u0438\u0434\u0438\u043c\u043e\u0441\u0442\u0438 http://php.net/manual/ru/language.oop5.visibility.php \u0412\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u0435\u0449\u0435 \u0433\u0434\u0435-\u0442\u043e \u043e\u0448\u0438\u0431\u043a\u0430 - \u0441\u043e\u0432\u0435\u0442\u0443\u044e \u0432\u044b\u043b\u043e\u0436\u0438\u0442\u044c \u043b\u0438\u0441\u0442\u0438\u043d\u0433 \u043a\u043e\u0434\u0430 \u0441\u044e\u0434\u0430 \u0438\u043b\u0438 \u043d\u0430 pastebin.com\n", "meta": {"language": "ru", "url": "https://ru.stackoverflow.com/questions/589340", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}} {"text": "Q: Get Date Filter on PivotTable row I'm creating PivotTables in Excel 2016. The first Row field is a Date. A few months ago I managed to apply a Date Filter to this row field, as shown below. But I am now unable to reproduce this: No matter how I access filters for that row field in a new PivotTable I can only choose between Label and Value filters.\nI have confirmed that the Number Format of the DateEntry row field is of type Date. How do I get the PivotTable to offer a Date Filter like this?\n\n", "meta": {"language": "en", "url": "https://superuser.com/questions/1411886", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to form a correct MySQL connection string? I am using C# and I am trying to connect to the MySQL database hosted by 00webhost.\nI am getting an error on the line connection.Open():\n\nthere is no MySQL host with these parameters.\n\nI have checked and everything seems to be okay.\nstring MyConString = \"SERVER=mysql7.000webhost.com;\" +\n \"DATABASE=a455555_test;\" +\n \"UID=a455555_me;\" +\n \"PASSWORD=something;\";\n\nMySqlConnection connection = new MySqlConnection(MyConString);\n\nMySqlCommand command = connection.CreateCommand();\nMySqlDataReader Reader;\n\ncommand.CommandText = \"INSERT Test SET lat=\" + \nOSGconv.deciLat + \",long=\" + OSGconv.deciLon;\n\nconnection.Open();\nReader = command.ExecuteReader();\n\nconnection.Close();\n\nWhat is incorrect with this connection string?\n\nA: string MyConString = \"Data Source='mysql7.000webhost.com';\" +\n\"Port=3306;\" +\n\"Database='a455555_test';\" +\n\"UID='a455555_me';\" +\n\"PWD='something';\";\n\n\nA: Here is an example:\nMySqlConnection con = new MySqlConnection(\n \"Server=ServerName;Database=DataBaseName;UID=username;Password=password\");\n\nMySqlCommand cmd = new MySqlCommand(\n \" INSERT Into Test (lat, long) VALUES ('\"+OSGconv.deciLat+\"','\"+\n OSGconv.deciLon+\"')\", con);\n\ncon.Open();\ncmd.ExecuteNonQuery();\ncon.Close();\n\n\nA: try creating connection string this way:\nMySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();\nconn_string.Server = \"mysql7.000webhost.com\";\nconn_string.UserID = \"a455555_test\";\nconn_string.Password = \"a455555_me\";\nconn_string.Database = \"xxxxxxxx\";\n\nusing (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))\nusing (MySqlCommand cmd = conn.CreateCommand())\n{ //watch out for this SQL injection vulnerability below\n cmd.CommandText = string.Format(\"INSERT Test (lat, long) VALUES ({0},{1})\",\n OSGconv.deciLat, OSGconv.deciLon);\n conn.Open();\n cmd.ExecuteNonQuery();\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/10505952", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "19"}} {"text": "Q: If there was no gravity, in what direction would an object float? On Earth, an object less dense than a fluid (e.g. water) would float up to the top surface of the liquid usually against gravity. If there was no gravity, would it still do the same?\nRephrased question: In what direction would an object float in a fluid of uniform density if the object has a lesser density than the fluid?\n\nA: Here's another possibility: \nAssuming there is a lot of water held in place by an atmosphere, some sort of thin crust, or anything else that can keep water liquid while preventing evaporation into the vacuum of space, the water would form a spherical planetoid under its own gravity. \nSay the radius of the water planetoid is $R$ and the water density does not vary much under its own weight. Then a small but macroscopic body of volume $V$ and mass density $\\rho = m/V \\le \\rho_{\\text{water}}$ (that is, too massive to be affected by Brownian motion) will always float to the sphere's surface. \nThe general rule is that it will move in the direction of its apparent weight in the water: it should float to the surface if its local weight is lower then that of the water it displaces, it should fall to the center otherwise. But whatever the gravitational field $\\bf g$ is at some location within the water sphere, for a small body the floating condition reads \n$$\nm {\\bf g} \\le \\rho_{\\text{water}} V {\\bf g} \\;\\;\\; \\Rightarrow \\;\\;\\; m \\le \\rho_{\\text{water}} V\n$$\nor \n$$\n\\rho \\le \\rho_{\\text{water}} \n$$\nNote that the conclusion holds even if the density of water does increase under its own weight. All we need to do is account for $\\rho_{\\text{water}}(r )$.\n\nIf you'd like to consider explicitly the gravitational field of a water sphere of uniform density $\\rho_{\\text{water}}$, assuming Newtonian gravitation, apply Gauss' Law for a concentric sphere or radius $r \\le R$ within its volume: \n$$\n (4\\pi r^2)\\; |{\\bf g}| = -4\\pi G \\left(\\frac{4\\pi r^3}{3}\\right) \\rho_{\\text{water}}\n$$\nso \n$$\n{\\bf g} = - \\frac{4\\pi G}{3} \\rho_{\\text{water}} {\\bf r}\n$$ \n\nA: No gravity means your liquid would form a sphere, unless you put it in a box.\nIt would float in whatever direction the forces created by differential heating, or any other turbulence inducing force, sends it in.\nUltimately, if you read about Einstein's work on Brownian Motion, in absolutely calm fluid, it's direction would be decided by the random motions of the molecules of the denser liquid.\n\nThis is a simulation of the Brownian motion of a big particle (dust particle) that collides with a large set of smaller particles (molecules of a gas) which move with different velocities in different random directions.\n\u00a0\n\nA: To answer the apparent discrepancy with the earlier question/answer head-on:\n\"How much does an object float?\" is not really a standard phrasing, but the responder to the earlier question seems to have understood it as \"how much of the object will stick up above a water surface in an equilibrium?\" Then the answer is \"it floats just as much\", because the equilibrium is still an equilibrium when we dial gravity down. (And even this is not strictly true, because surface tension will become relatively more important and change the floating position).\nHowever, even though the equilibrium is the same, the forces that pull the system towards the equilibrium position will be smaller, so if you reduce gravity, it will take longer for the object to reach the equilibrium. As the gravitational strength goes towards zero, the time until everything settles down goes to infinity. And right when it reaches zero, a lot of new additional equilibria arise.\n", "meta": {"language": "en", "url": "https://physics.stackexchange.com/questions/272978", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "11"}} {"text": "Q: Installing SSL On apache2 & Ubuntu 14.04 I'm trying to install ssl on my apache2.4.7 ubuntu 14.04 server \nI'm following the digital ocean tutorial here\nbut it keeps redirecting me to the normal http version. This is my 000-default.conf in sites-available (even when I delete the whole content it still loads my website)\n\nServerName xxxxxx.com\nServerAdmin webmaster@localhost\nDocumentRoot /var/www/html\n\nSSLEngine on\nSSLCertificateFile /etc/apache2/ssl/xxxxxx.com.crt\nSSLCertificateKeyFile /etc/apache2/ssl/xxxxxx.com.key\nSSLCertificateChainFile/etc/apache2/ssl/intermediate.crt \n\nErrorLog ${APACHE_LOG_DIR}/error.log\nCustomLog ${APACHE_LOG_DIR}/access.log combined \n\n\n\nA: Looks like you have a process running on the 443 port so when apache tries to get on that, it fails. \nnetstat -tlpn | grep 443\nuse that to find out which process is using it. It should give you process id as well. \nservice stop \nor \nkill to kill the process that is using your 443 port. Clear your apache logs and restart apache. \n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/32218634", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Sql injection mysql_real_escape_string I have a dilemma how should I mysql_real_escape_string() my variables without inserting them into the database \\n, \\r, \\x00 when someone uses \" ' or
on my comment field, I tried with preg_replace instead of mysql_real_escape_string, but seems I don't know exactly how to allow all the chars and signs I want. \n\nA: mysql_real_escape_string only escapes values so that your queries don't break, it also protects against SQL injection if used correctly.\nIf you don't want certain characters you will need to use additional functions to strip them before you apply mysql_real_escape_string.\n[insert obligatory \"use prepared statements\" comment]\nEx:\n$string = \"My name is\nJohn\";\n\n$filtered_string = str_replace(\"\\n\", \" \", $string); // filter\n$escaped = mysql_real_escape_string($filtered_string); // sql escape\nmysql_query(\"INSERT INTO `messages` SET `message` = '\" . $escaped . \"'\");\n\n\nA: You should be able to use str_replace to help with this:\nmysql_real_escape_string(str_replace(array(\"\\n\", \"\\r\\n\", \"\\x00\", '\"', '\\''), '', $input));\n\nHaving said that, it is a good idea to switch to mysqli or PDO for database read / write. Both of these allow prepared statements, which reduce the risk of SQL injections.\nHere's an example of PDO:\n$stmt = $PDOConnection->prepare('INSERT INTO example_table (input_field) VALUES (:input_field)');\n$stmt->bindParam(':input_field', $input);\n$stmt->execute();\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/14283556", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Spring MockWebServiceServer handling multiple async requests I have multiple async soap requests and I need to mock the responses of those requests. However, it seems the order of the expected requests matter and I was wondering if there were any workarounds.\nI came across this example using MockRestServiceServer where it uses the ignoreExpectOrder() method. \n\nA: You can write your own implementation of the ResponseCreator that sets up a number of URI and responses (for asynchronous requests) and return the matching response based on the input URI. I've done something similar and it is works.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/52935325", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to express the type for a constant? I have to write some functions with a significant amount of constant in it in a relatively small amount of lines.\n( Don't bother about the way I wrote the formula, it's there to simply express the fact that I have a lot of constants in a small package, this specific example is small too, in practice I have a minimum of 6-7 constants for each function )\nT foo( T x )\n{\n return k1 * k2 * x - k3;\n}\n\nAssuming that I'm not interested in declaring the constants as static ( it will also cause problems with the naming convention in my specific case ) const T k1 = 42; , I would like to find an alternative .\nA viable alternative can be\nT foo( T x )\n{\n return uint32_t{42} * uint32_t{21} * x - uint32_t{33};\n}\n\nAt this point there are 2 main problems:\n\n\n*\n\n*I'm not sure if this kind of declaration will create an entire object or just \"a number\"\n\n*it's a C++ only solution and I'm writing really simple functions that should be C99+ compatible .\n\n\nWhy I would like to do this ?\nIt's simple, the values for this constants are highly variable, really small values or big values, with really small values there is a significant amount of space wasted, plus this constants are math constants so they will never change and I can optimize this section right from the first release.\nThere is also another aspect, the default type for numeric constants is a signed integer, I would like to go for an unsigned integer type of arbitrary size.\nThe problem with the static declaration const T k1 = 42; outside the functions, is that different constants have the same name, the value of the constant is different because the function is different, but the name of the constant, mathematically speaking, is the same, so with this solution I'll end up having multiple declarations of the same variable in the same scope. That's why I can't use names or this kind of declarations .\nDo you have any idea for writing this in a way that is compatible with both C++ and C ?\n\nA: In C, for integers, you add 'U', 'L', or 'LL' to numbers to make them unsigned, long, or long long in a few combinations\na = -1LL; // long long\nb = -1U; // unsigned\nc = -1ULL; // unsigned long long\nd = -1LLU; // unsigned long long\ne = -1LU; // unsigned long\nf = -1UL; // unsigned long\n\nOne other option, in C, is to cast. The compiler, very probably, will do the right thing :)\nreturn (uint32)42 - (int64)10;\n\nBut probably the best option, as pointed by ouah in the comments below, is to use Macros for integer constants (C99 Standard 7.18.4)\na = UINT32_C(-1); // -1 of type uint_least32_t\nb = INT64_C(42); // 42 of type int_least64_t\n\n\nA: Is there something wrong this?\ninline T foo(T x)\n{\n int k1 = 42;\n int k2 = 21;\n int k3 = 33;\n\n return 1ull * x * k1 * k2 - k3;\n}\n\nYour comments on the other answer suggest you are unsure about which types to use for the constants.\nI don't see what the problem is with just using any type in which that constant is representable.\nFor the calculation expression, you would need to think about the size and signed-ness of intermediate calculations. In this example I start with 1ull to use unsigned arithmetic mod 2^64. If you actually wanted arithmetic mod 2^32 then use 1ul instead, and so on.\nCan you elaborate on what you meant by \"space wasted\"? It sounds as if you think there is some problem with using 64-bit ints. What sort of \"space\" are you talking about?\nAlso, to clarify, the reason you don't want to declare k1 global is because k1 has a different value in one function than it does in another function? (As opposed to it having the same value but you think it should have a different data type for some reason).\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/23660950", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: How to allow your app with usage access? From android lollipop, the app that wants to access usage of other apps needs to be enabled by security. Rather than manually enabling it manually by Settings -> Security -> Apps with usage access, I want to enable it programmatically. I cannot find a clear answer anywhere. Can anyone help me on this one?\n\nA: Try this in your activity:\n@Override\nprotected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (!isAccessGranted()) {\n Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);\n startActivity(intent);\n }\n}\n\n\nprivate boolean isAccessGranted() {\n try {\n PackageManager packageManager = getPackageManager();\n ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);\n AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);\n int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,\n applicationInfo.uid, applicationInfo.packageName);\n return (mode == AppOpsManager.MODE_ALLOWED);\n\n } catch (PackageManager.NameNotFoundException e) {\n return false;\n }\n}\n\n\nA: try this code i hope help you \nif (Build.VERSION.SDK_INT >= 21) {\n UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);\n long time = System.currentTimeMillis();\n List stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 10, time);\n\n if (stats == null || stats.isEmpty()) {\n Intent intent = new Intent();\n intent.setAction(Settings.ACTION_USAGE_ACCESS_SETTINGS);\n context.startActivity(intent);\n }\n }\n\n\nA: Add this permission in your manifest\nuses-permission android:name=\"android.permission.PACKAGE_USAGE_STATS\"\nand continue with this answer\nhttps://stackoverflow.com/a/39278489/16126283\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/38573857", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: How do I create a list of dates, before doing a LEFT JOIN? I am using BigQuery SQL. I have the following tables:\nTable \"public.org\" (records all organisations)\n Column \u2502 Type \u2502 Modifiers\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n code \u2502 character varying(6) \u2502 not null\n name \u2502 character varying(200) \u2502 not null \n setting \u2502 integer \u2502 not null \n\n Table \"public.spending\" (records spending on chemical by org by month)\n Column \u2502 Type \u2502 Modifiers\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n org_id \u2502 character varying(6) \u2502 not null\n month \u2502 date \u2502 not null\n chemical_id \u2502 character varying(9) \u2502 not null\n actual_cost \u2502 double precision \u2502 not null\n\nAnd I want to calculate the spending on a particular chemical by month, by organisation. The complication is if there was no spending by an organisation on that chemical in a month, there is simply no entry in the spending table, rather than a zero entry. However, I would like output (a null or zero result, I don't mind which).\nRight now I have this, which gives me total spending for all organisations including those that had no entries, but does not separate spending out by month:\nSELECT\n org.code AS code,\n org.name AS name,\n num.actual_cost as actual_cost\nFROM (\n SELECT\n code,\n name\n FROM\n org\n WHERE\n setting=4) AS orgs\nLEFT OUTER JOIN EACH (\n SELECT\n org_id,\n SUM(actual_cost) AS actual_cost\n FROM\n spending\n WHERE\n chemical_id='1202010U0AAAAAA'\n GROUP BY\n org_id) AS num\nON\n num.org_id = orgs.code\n\nSo now I need to extend it to do a LEFT JOIN by month and organisation. I know that I can get the unique months in the spending table by doing this:\nSELECT month FROM spending GROUP BY month\n\n(NB BigQuery doesn't support UNIQUE.)\nBut how do I get all the unique rows for month and organisation, and only then do a LEFT JOIN onto the spending?\n\nA: If we are talking about calendar months there we have only 12 options (Jan => Dec).\nJust compile a static table or in the query itself as 12 selects that form a table, and use that to join.\nselect * from \n(select 1 as m),\n(select 2 as m),\n....\n(select 12 as m)\n\nyou might also be interested in the Technics mentioned in other posts :\n\n\n*\n\n*How to extract unique days between two timestamps in BigQuery?\n\n*Hits per day in Google Big Query\n\nA: I'm not sure if this works in bigquery, but this is the structure of a query that does what you want:\nselect org.name, org.code, m.month, sum(s.actual_cost)\nfrom org cross join\n (select month from public.spending group by month) m left join\n pubic.spending s\n on s.ord_ig = org.code and s.month = m.month\nwhere prescribing_setting = 4\ngroup by org.name, org.code, m.month;\n\n\nA: I would suggested following steps for you to get through:\nSTEP 1 - identify months range (start and finish)\nmonth is assumed to be presented in format YYYY-MM-01\nif it is in different format - code should be slightly adjusted\nSELECT \n MIN(month) as start, \n MAX(month) as finish\nFROM public.spending\n\nAssume Result of Step 1 is \n'2014-10-01' as start, '2015-05-01' as finish\nStep 2 - produce all months in between Start and Finish\nSELECT DATE(DATE_ADD(TIMESTAMP('2000-01-01'), pos - 1, \"MONTH\")) AS month\nFROM (\n SELECT ROW_NUMBER() OVER() AS pos, * FROM (FLATTEN((\n SELECT SPLIT(RPAD('', 1000, '.'),'') AS h FROM (SELECT NULL)),h\n))) nums \nCROSS JOIN (\n SELECT '2014-10-01' AS start, '2015-05-01' AS finish // <<-- Replace with SELECT from Step 1\n) range\nWHERE pos BETWEEN 1 AND 1000\nAND DATE(DATE_ADD(TIMESTAMP('2000-01-01'), pos - 1, \"MONTH\")) \n BETWEEN start AND finish\n\nSo, now - Result of Step 2 is \nmonth \n2014-10-01 \n2014-11-01 \n2014-12-01 \n2015-01-01 \n2015-02-01 \n2015-03-01 \n2015-04-01 \n2015-05-01\n\nIt has all months, even if some are missed in public.spending table in between start and finish \nI think the rest is trivial and you have already main code for it.\nLet me know if this is not accurate and you need help in completing above steps\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/34179398", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Class to test if date is valid using Int input with boolean output, and how to test (java) I have an assignment for class in which I have to create a class (called FunWithCalendars) that takes in 3 int values (month, day, and year) and uses 1 boolean method (isValid) to check if the overall date is valid, which uses 3 other helper methods (isLeapYear, isValidMonth, isValidDay) to determine whether the day and month given are valid. I now want to test my file in Eclipse.\nSo far I've learned to test classes/methods with this code ( Im a newbie, so this is the only way I know):\npublic class driverFunWithCalendars {\n public static void main(String [] args ) {\n FunWithCalendars test = new FunWithCalendars () ;\n System.out.println( test.FunWithCalendars () );\n\nHowever, Im not understanding how I'm supposed to test the boolean method for a true or false when I have to enter int values that aren't defined in the method. The error in the code above is at \"new FunWithCalendars () ;\" and \"(test.funwithcalendars () );\".\nHere's my main code:\npublic class FunWithCalendars\n{\n private int month, day, year;\n \n public FunWithCalendars( int m, int d, int y )\n {\n month = m;\n day = d;\n year = y;\n }\n \n public boolean isValid ( boolean isValidMonth, boolean isValidDay ) \n { \n if ( isValidMonth && isValidDay ) \n {\n return true;\n }\n else \n {\n return false;\n }\n \n }\n \n \n \n public boolean isLeapYear (int year) \n {\n \n if ( (year / 400) == 0 ) \n {\n return true;\n }\n else if ( ((year / 4) == 0) && ((year/100) !=0))\n {\n return true;\n }\n else \n {\n return false;\n }\n }\n \n public boolean isValidMonth ( int month ) \n {\n if ( month >= 1 && month <= 12 ) \n {\n return true;\n }\n else \n {\n return false;\n }\n }\n \n public boolean isValidDay ( int month, int day, int year, boolean isLeapYear ) \n {\n if ( (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && ((day<=31) && (day>=1)) ) \n {\n return true;\n }\n else if ( (month == 4 || month == 6 || month == 9 || month == 11) && ((day<=30) && (day>=1)) ) \n {\n return true;\n }\n else if ( (month == 2) && ( isLeapYear = true) && ((day<=29) && (day>=1)) ) \n {\n return true;\n }\n else if ( (month == 2) && ( isLeapYear = false) && ((day<=28) && (day>=1)) ) \n {\n return true;\n }\n else \n {\n return false;\n }\n }\n \n}\n \n\n}\n}\n\nBasically, I just want to know how I can test my code with 3 int values ( a date, or month, day year) to see if the date is valid or not using my isValid method. I'm really sorry if my question is unclear, or the assignment in the way I explained is confusing but like I said Im a newbie to Java and to Stackoverflow questions and I have yet to understand Java to the point that I can ask more efficient and concise questions, but I really hope some of you can help me. Ill also attach a transript of my original assignment, which may be less confusing and helpful to you if you're trying to help me:\n/*\nThe calendar we use today is the Gregorian Calendar, devised by Italian astronomer Aloysius Lilius and decreed by Pope Gregory XIII on February 24th, 1582. In the Gregorian Calendar, the average length of a year is exactly 365.2425 days. We can make that happen with some rather complex \"leap year\" rules:\nIf a year is divisible by 4, it's a leap year\u2026 unless it's divisible by 100, in which case it's not a leap year\u2026 unless it's divisible by 400, in which case it's a leap year.\nOkay, that's confusing. Let's try again:\nA year is a leap year if:\na. It's divisible by 400\nb. It's divisible by 4 and it's not divisible by 100.\nBased on those rules, 1512, 1600, and 2000 were leap years. 1514, 1700, and 1900 were not.\n(And you thought leap year was just every four years! That was the case with Julius Caesar's calendar\u2014which was wrong, because adding a 366th day every four years would give us an average year length of 365.25 days instead of the far more accurate 365.2425 days. 0.0075 days per year doesn't sound like a lot, but in the 1500s astronomers noticed that predictable events, such as the solstice and equinox, were \"off\" by about 10 days. Hence the new, improved calendar.)\nIn the Gregorian Calendar, the number of days per month are as follows:\nMonth Name Days\n1 January 31\n2 February 28 or 29\n3 March 31\n4 April 30\n5 May 31\n6 June 30\n7 July 31\n8 August 31\n9 September 30\n10 October 31\n11 November 30\n12 December 31\nBased on the Gregorian Calendar's leap year rules, and the usual number of days per month, complete the class FunWithCalendars. You will need:\nThree int field variables to keep track of the month, day, and year.\nThe constructor of FunWithCalendars, which will take in values for the month, day, and year, and assign them to field variables. (This is written for you, you may use the starter file FunWithCalendars.java ).\nThe method:\nboolean isValid()\nwhich will return a true or false. A true result means that the month and day are valid values for that year.\nYou will need three helper methods:\nboolean isLeapYear()\nwhich will return a true only if the year represents a leap year.\nYou also need:\nboolean isValidMonth()\nwhich will return a true only if the month field is between 1 and 12. And finally:\nboolean isValidDay()\nwhich will return a true only if that day exists in that month in the given year. Remember to check for a leap year when checking to see if 29 is valid in February!\nAgain, we expect a true from isValid() if and only if we get a true from isValidMonth() and from isValidDay(). (We will assume that all years are valid.)\nTests:\n7/20/2010 is valid.\n13/1/2009 is not valid. (13 is not a valid month.)\n11/31/2009 is not valid. (That day does not exist in that month.)\n2/29/2007 is not valid. (2007 was not a leap year.)\n2/29/2000 is valid. (2000 was a leap year.)\n*/\nThanks to anyone who can help!\n\nA: Let\u2019s take the first test as an example:\n\nTests:\n7/20/2010 is valid.\n\nSo in your driver class/test class construct a FunWithCalendars object denoting July 20 2010. The constructor takes three arguments for this purpose. Next call its isValid method. I believe that the idea was that you shouldn\u2019t need to pass the same arguments again. Your isValid method takes two boolean arguments. Instead I believe that it should take no arguments and itself call the two helper methods passing the values that are already inside the FunWithCalendars object. So before you can get your driver class to work, I believe you have to fix your design on this point.\nOnce you get the call to isValid() to work, store the return value into a variable. Compare it to the expected value (true in this case). If they are equal, print a statement that the test passed. If they are not equal, print a statement containing both the expected and the observed value.\nDo similarly for the other tests. Don\u2019t copy-paste the code, though. Instead wrap it in a method and call the method for each test case, passing as arguments the data needed for that particular test. Remember to include the expected result as an argument so the method can compare.\nEdit:\n\n\u2026 My confusion is in how to construct an object (in general, and also\nspecifically FunWithCalendars), how to call the isValid method and\nhave it not take any arguments, how to have the isValid method call\nthe two helper methods which pass the values that are in the\nFunWIthCalendars object.\n\nIt\u2019s basic stuff, and I don\u2019t think Stack Overflow is a good place to teach basic stuff. Let\u2019s give it a try, only please set your expectations low.\nHow to construct an object: You\u2019re already doing this in your driver class using the new operator:\n FunWithCalendars test = new FunWithCalendars () ;\n\nOnly you need to pass the correct arguments to the constructor. Your constructor takes three int arguments, so it needs to be something like:\n FunWithCalendars test = new FunWithCalendars(7, 20, 2020);\n\nHow to call the isValid method and have it take no arguments, after the above line:\n boolean calculatedValidity = test.isValid();\n\nThis stores the value returned from isValid() (false or true) into a newly created boolean variable that I have named calculatedValidity. From there we may check whether it has the expected value, act depending on it and/or print it. The simplest thing is to print it, for example:\n System.out.println(\"Is 7/20/2020 valid? \" + calculatedValidity);\n\nCalling with no arguments requires that the method hasn\u2019t got any parameters:\npublic boolean isValid () \n{ \n\nHow to have isValid() call the two helper methods: You may simple write the method calls en lieu of mentioning the parameters that were there before. Again remember to pass the right arguments:\n if (isValidMonth(month) && isValidDay(month, day, year, isLeapYear(year)) ) \n\nIn the method calls here I am using the instance variables (fields) of the FunWithCalendars object as arguments. This causes the method to use the numbers that we entered through the constructor and to use the three helper methods.\nI have run your code with the above changes. My print statement printed the expected:\n\nIs 7/20/2020 valid? true\n\n\nPS I am on purpose not saying anything about possible bugs in your code. It\u2019s a lot better for you to have your tests tell you whether there are any.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/64423047", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: I want to upload multiple files using Django I want to upload multiple files or a folder in form , The html form uploads the multiple files successfully but when it comes to django handling it is showing me night-mares in day light . \nI have created my html form like this\n\n\nI have created a model like this \nclass Report(models.Model):\n name = models.CharField(max_length=60)\n report = models.CharField(max_length=10)\n task = models.CharField(max_length=60)\n date = models.DateField(null=True)\n start_time = models.TimeField()\n end_time = models.TimeField()\n no_of_hours = models.CharField(max_length=20)\n team_lead = models.CharField(max_length=30)\n today_progress = models.CharField(max_length = 1000)\n file_input = models.FileField(upload_to='documents/')\n concern = models.CharField(max_length=1000)\n next_plan = models.CharField(max_length=1000)\n next_plan_file = models.FileField(upload_to='next/')\n\nAnd views.py like this\n\ndef save(request):\n report_object = Report()\n report_object.name = request.POST[\"name\"]\n report_object.report = request.POST[\"report\"]\n report_object.task = request.POST[\"task\"]\n report_object.date = request.POST[\"date\"]\n report_object.start_time = request.POST[\"start_time\"]\n report_object.end_time = request.POST[\"end_time\"]\n report_object.no_of_hours = request.POST[\"no_of_hours\"]\n report_object.team_lead = request.POST[\"team_lead\"]\n report_object.today_progress = request.POST[\"today_progress\"]\n report_object.file_input = request.FILES.[\"file_input\"]\n report_object.concern = request.POST[\"concern\"]\n report_object.next_plan = request.POST[\"next_plan\"]\n report_object.next_plan_file = request.FILES.[\"upload_next\"]\n report_object.save()\n return redirect('/')\n\n\nI pass the file into the model i have created but only the last file gets inserted and shown in Admin Panel\nNow I get only last file (if I select 3 files then get 3rd file). How to get all files or folder ?\nAnd even want to show in Django Admin Panel\n\nA: Try this and check out this works!!\nReplace\nfile=request.FILES.get('file')\n\nwith\nfiles = request.FILES.getlist('file')\n\nyou have to loop through each element in your view\nif form.is_valid():\n name = form.cleaned_data['name']\n for f in files:\n File.objects.create(name=name, file=f)\n return HttpResponse('OK')\n\nHere name is your model field and saving all uploaded files in name field\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/62132613", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How prejudice affects our lives? VS how does prejudice affect our lives? I'm writting an essay and I have a question...\nWhich one of these questions is correct?\n\n*\n\n*How prejudice affects our lives?\n\n*How does prejudice affect our lives?\n\n", "meta": {"language": "en", "url": "https://ell.stackexchange.com/questions/296238", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Working with images in C++ or C The first thing is that I am a beginner. Okay?\nI've read related answers and questions, but please help me with this problem:\nHow can I open an JPEG image file in C++, convert it to a grayscale image, get its histogram, resize it to a smaller image, crop a particular area of it, or show a particular area of it?\nFor these tasks, is C or C++ faster in general?\nWhat libraries are simplest and fastest? The running time is very important.\nThanks.\n\nA: There are many good libraries for working with images in C and C++, none of which is clearly superior to all others. OpenCVwiki, project page has great support for some of these tasks, while ImageMagickwiki, project page is good at others. The JPEG group has its own implementation of JPEG processing functions as well. These are probably good resources to start from; the API documentation can guide you more specifically on how to use each of these.\nAs for whether C or C++ libraries are bound to be faster, there's no clear winner between the two. After all, you can always compile a C library in C++. That said, C++ libraries tend to be a bit trickier to pick up because of the language complexity, but much easier to use once you've gotten a good feel for the language. (I am a bit biased toward C++, so be sure to consider the source). I'd recommend going with whatever language you find easier for the task; neither is a bad choice here, especially if performance is important.\nBest of luck with your project!\n\nA: well for basic image manipulations you could also try Qt's QImage class (and other). This gives you basic functionality for opening, scaling, resizing, cropping, pixel manipulations and other tasks.\nOtherwise you could as already said use ImageMagick or OpenCV. OpenCV provides a lot of examples with it for many image manipulation/image recognition tasks...\nHope it helps...\n\nA: here is an example using magick library.\nprogram which reads an image, crops it, and writes it to a new file (the exception handling is optional but strongly recommended):\n#include \n#include \nusing namespace std;\nusing namespace Magick;\nint main(int argc,char **argv)\n{\n // Construct the image object. Seperating image construction from the\n // the read operation ensures that a failure to read the image file\n // doesn't render the image object useless.\n Image image;\n\n try {\n // Read a file into image object\n image.read( \"girl.jpeg\" );\n\n // Crop the image to specified size (width, height, xOffset, yOffset)\n image.crop( Geometry(100,100, 100, 100) );\n\n // Write the image to a file\n image.write( \"x.jpeg\" );\n }\n catch( Exception &error_ )\n {\n cout << \"Caught exception: \" << error_.what() << endl;\n return 1;\n }\n return 0;\n}\n\ncheck many more examples here\n\nA: libgd is about the easiest, lightest-weight solution.\ngdImageCreateFromJpeg\ngdImageCopyMergeGray\ngdImageCopyResized\n\nOh, and it's all C.\n\nA: If running time is really important thing then you must consider image processing library which offloads processing job to GPU chip, such as:\n\n\n*\n\n*Core Image (Osx)\n\n*OpenVIDIA (Windows)\n\n*GpuCV (Windows, Linux)\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/4906736", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "5"}} {"text": "Q: Android: Disable texture filtering/interpolation on AnimationDrawable I have a frame-by-frame AnimationDrawable that I'd like to scale without Android's default, blurry interpolation. (It's pixel art and looks better with nearest-neighbor.) Can I set a flag? Override onDraw? Anything to tell the GPU not to use texture filtering?\nDo I need to scale up each individual bitmap in the animation instead? This seems like a waste of CPU and texture memory.\nCode example:\n// Use a view background to display the animation.\nView animatedView = new View(this);\nanimatedView.setBackgroundResource(R.anim.pixel_animation);\nAnimationDrawable animation = (AnimationDrawable)animatedView.getBackground();\nanimation.start();\n\n// Use LayoutParams to scale the animation 4x.\nfinal int SCALE_FACTOR = 4;\nint width = animation.getIntrinsicWidth() * SCALE_FACTOR;\nint height = animation.getIntrinsicHeight() * SCALE_FACTOR;\ncontainer.addView(animatedView, width, height);\n\n\nA: This seems to work, as long as you can assume that all the frames in an AnimationDrawable are BitmapDrawables:\nfor(int i = 0; i < animation.getNumberOfFrames(); i++) {\n Drawable frame = animation.getFrame(i);\n if(frame instanceof BitmapDrawable) {\n BitmapDrawable frameBitmap = (BitmapDrawable)frame;\n frameBitmap.getPaint().setFilterBitmap(false);\n }\n}\n\n\nA: If you know the texture ID of the texture that's being rendered, at any time after it's created and before it's rendered you should be able to do:\nglBindTexture(GL_TEXTURE_2D, textureId);\nglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\nglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\nIf this is the only texture being rendered then you can do that anywhere from your render thread and it will get picked up without having to explicitly glBindTexture().\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/23750139", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Use the pumping lemma to show that the following languages are not regular languages L = {anbm | n = 2m} Use the pumping lemma to show that the following languages are not regular languages L = {an bm | n = 2m} \n\nA: Choose a string a^2p b^p. The pumping lemma says we can write this as w = uvx such that |uv| <= p, |v| < 0 and for all natural numbers n, u(v^n)x is also a string in the language. Because |uv| <= p, the substring uv of w consists entirely of instances of the symbol a. Pumping up or down by choosing a value for n other than one guarantees that the number of a's in the resulting string will change, while the number of b's stays the same. Since the number of a's is twice the number of b's only when n = 1, this is a contradiction. Therefore, the language cannot be regular.\n\nA: L={anbm|n=2m} Assume that L is regular Language Let the pumping length be p L={a2mbm} Since |s|=3m > m (total string length) take a string s S= aaaaa...aabbb....bbb (a2mbm times taken) Then, u = am-1 ; v= a ; w= ambm. && |uv|<=m Now If i=2 then S= am-1 a2 ambm = a2m-1bm Since here we are getting an extra a in the string S which is no belong to the given language a2mbm our assumption is wrong Therefore it is not a regular Language\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/62106698", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Declaring constants with the nameof() the constant as the value Scenario\nI have a class for declaring string constants used around a program:\npublic static class StringConstants\n{\n public const string ConstantA = \"ConstantA\";\n public const string ConstantB = \"ConstantB\";\n // ...\n}\n\nEssentially, it doesn't matter what the actual value of the constant is, as it used when assigning and consuming. It is just for checking against.\nThe constant names will be fairly self-explanatory, but I want to try and avoid using the same string values more than once.\n\nWhat I would like to do\nI know that nameof() is evaluated at compile-time, so it is entirely possible to assign the const string's value to the nameof() a member.\nIn order to save writing these magic strings out, I have thought about using the nameof() the constant itself.\nLike so:\npublic static class StringConstants\n{\n public const string ConstantA = nameof(ConstantA);\n public const string ConstantB = nameof(ConstantB);\n // ...\n}\n\n\nQuestion...\nI guess there is no real benefit of using the nameof(), other than for refactoring?\nAre there any implications to using nameof() when assigning constants?\nShould I stick to just using a hard-coded string?\n\nA: Whilst I think the use of nameof is clever, I can think of a few scenarios where it might cause you a problem (not all of these might apply to you):\n1/ There are some string values for which you can't have the name and value the same. Any string value starting with a number for example can't be used as a name of a constant. So you will have exceptions where you can't use nameof.\n2/ Depending how these values are used (for example if they are names of values stored in a database, in an xml file, etc), then you aren't at liberty to change the values - which is fine until you come to refactor. If you want to rename a constant to make it more readable (or correct the previous developer's spelling mistake) then you can't change it if you are using nameof.\n3/ For other developers who have to maintain your code, consider which is more readable:\npublic const string ConstantA = nameof(ContantA);\n\nor\npublic const string ConstantA = \"ConstantA\";\n\nPersonally I think it is the latter. In my opinion if you go the nameof route then that might give other developers cause to stop and wonder why you did it that way. It is also implying that it is the name of the constant that is important, whereas if your usage scenario is anything like mine then it is the value that is important and the name is for convenience.\nIf you accept that there are times when you couldn't use nameof, then is there any real benefit in using it at all? I don't see any disadvantages aside from the above. Personally I would advocate sticking to traditional hard coded string constants.\nThat all said, if your objective is to simply to ensure that you are not using the same string value more than once, then (because this will give you a compiler error if two names are the same) this would be a very effective solution. \n\nA: I think nameof() has 2 advantages over a literal strings:\n1.) When the name changes, you will get compiler errors unless you change all occurences. So this is less error-prone.\n2.) When quickly trying to understand code you didn't write yourself, you can clearly distinguish which context the name comes from. Example:\nViewModel1.PropertyChanged += OnPropertyChanged; // add the event handler in line 50\n\n...\n\nvoid OnPropertyChanged(object sender, string propertyName) // event handler in line 600\n{\n if (propertyName == nameof(ViewModel1.Color))\n {\n // no need to scroll up to line 50 in order to see\n // that we're dealing with ViewModel1's properties\n ...\n }\n}\n\n\nA: Using the nameof() operator with public constant strings is risky. As its name suggests, the value of a public constant should really be constant/permanent. If you have public constant declared with the nameof() and if you rename it later then you may break your client code using the constant. In his book Essential C# 4.0, Mark Michaelis points out: (Emphasis is mine)\n\npublic constants should be permanent because changing their value will\nnot necessarily take effect in the assemblies that use it. If an\nassembly references constants from a different assembly, the value of\nthe constant is compiled directly into the referencing assembly.\nTherefore, if the value in the referenced assembly is changed but the\nreferencing assembly is not recompiled, then the referencing assembly\nwill still use the original value, not the new value. Values that\ncould potentially change in the future should be specified as readonly\ninstead.\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/40888699", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "10"}} {"text": "Q: Magento connect's order delivery date extension disable required dates I used Magento connects Order Delivery Date extension to allow the buyer to set the date, when they should receive the goods. Now i want to disable some dates on the calendar that shows at checkout page. Can i use general JQuery calendar date disable at this point? If i can not what is the way it should be done? Any helps would be appreciated.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/20964588", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: \u0420\u0430\u0437\u0431\u0438\u0442\u044c \u0441\u0442\u0440\u043e\u043a\u0443 \u043d\u0430 \u0441\u043b\u043e\u0432\u0430 \u0421++ \u0423 \u043c\u0435\u043d\u044f \u0435\u0441\u0442\u044c \u043a\u043e\u0434\nstd::string tmp;\nstd::stringstream ss(input);\nstd::vector words;\n\nwhile(std::getline(ss,tmp, ' ')){\n words.push_back(tmp);\n}\n\n\nfor(long unsigned int i = 0; i < words.size(); i++){\n std::cout << words[i] << std::endl;\n}\n\n\u0421\u0442\u0440\u043e\u043a\u0443 \u043f\u043e \u0442\u0438\u043f\u0443 \"one two three\" \u0440\u0430\u0437\u0431\u0438\u0432\u0430\u0435\u0442 \u043a\u0430\u043a \u043d\u0430\u0434\u043e,\u043d\u043e \u043a\u0430\u043a \u043c\u043d\u0435 \u0442\u0443\u0442 \u0443\u0447\u0435\u0441\u0442\u044c \u0437\u0430\u043f\u044f\u0442\u044b\u0435 \u0434\u043e\u043f\u0443\u0441\u0442\u0438\u043c,\u043a \u043f\u0440\u0438\u043c\u0435\u0440\u0443 \u0441\u0442\u0440\u043e\u043a\u0430 one,two three\"\n\nA: \u0418\u043c\u0435\u043d\u043d\u043e \u043a\u0430\u043a\u043e\u0439 \u0441\u0438\u043d\u0442\u0430\u043a\u0441\u0438\u0447\u0435\u0441\u043a\u0438\u0439 \u0430\u043d\u0430\u043b\u0438\u0437\u0430\u0442\u043e\u0440 \u0432\u0430\u043c \u043d\u0443\u0436\u0435\u043d \u043d\u0435 \u0434\u043e \u043a\u043e\u043d\u0446\u0430 \u043f\u043e\u043d\u044f\u0442\u043d\u043e. \u041d\u043e std::istream::operator>> \u0438 \u0442\u0430\u043a \u0441\u0447\u0438\u0442\u044b\u0432\u0430\u0435\u0442 \u0434\u043e \u0441\u0438\u043c\u0432\u043e\u043b\u0430 \u0440\u0430\u0437\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044f, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 std::getline \u043d\u0435 \u043d\u0443\u0436\u043d\u0430. \u0415\u0441\u043b\u0438 \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0431\u0440\u0430\u0442\u044c \u043a\u043e\u043d\u0435\u0447\u043d\u044b\u0435 \u0437\u0430\u043f\u044f\u0442\u044b\u0435, \u0442\u043e:\nwhile (ss >> tmp) { \n if (tmp.back() == ',')\n tmp.pop_back();\n words.push_back(tmp);\n}\n\n\u0415\u0441\u043b\u0438 \u0445\u043e\u0442\u0438\u0442\u0435 \u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0442\u044c tmp \u043f\u043e \u043a\u0430\u043a\u043e\u043c\u0443 \u0442\u043e \u0441\u0438\u043c\u0432\u043e\u043b\u0443(\u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440, \u0435\u0441\u043b\u0438 \u0437\u0430\u043f\u044f\u0442\u044b\u0435 \u0435\u0441\u0442\u044c \u0432 \u043b\u044e\u0431\u043e\u043c \u043c\u0435\u0441\u0442\u0435 \u0441\u043b\u043e\u0432\u0430), \u0442\u043e\u0433\u0434\u0430 \u0442\u0443\u0442 \u043c\u043e\u0436\u043d\u043e \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u043e\u0434\u0438\u043d \u0438\u0437 \u043c\u043d\u043e\u0433\u043e\u0447\u0438\u0441\u043b\u0435\u043d\u043d\u044b\u0445 \u0432\u0430\u0440\u0438\u0430\u043d\u0442\u043e\u0432. \u0427\u0438\u0441\u0442\u043e \u0434\u043b\u044f \u0434\u0435\u043c\u043e\u043d\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0441 \u043f\u0440\u0438\u043c\u0435\u043d\u0435\u043d\u0438\u0435\u043c std::getline \u043c\u043e\u0436\u043d\u043e \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u043d\u0435 \u0441\u0430\u043c\u044b\u0439 \u0443\u0434\u0430\u0447\u043d\u044b\u0439 \u0432\u0430\u0440\u0438\u0430\u043d\u0442:\nwhile (ss >> tmp) { \n std::istringstream s(tmp); \n bool valid = true;\n while (std::getline(s, tmp, ','))\n {\n valid = false;\n words.push_back(tmp);\n }\n if (valid) {\n if (tmp.back() == ',')\n tmp.pop_back();\n words.push_back(tmp);\n }\n}\n\n\u0415\u0441\u043b\u0438 \u0432\u0430\u043c \u043d\u0443\u0436\u043d\u043e \u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0430\u0442\u044c \u0441\u0442\u0440\u043e\u043a\u0443, \u0442\u043e \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0439\u0442\u0435 \u043c\u0435\u0442\u043e\u0434\u044b \u043a\u043b\u0430\u0441\u0441\u0430 _ \u044d\u0442\u043e \u0441\u0430\u043c\u044b\u0439 \u044d\u0444\u0444\u0435\u043a\u0442\u0438\u0432\u043d\u044b\u0439 \u0441\u043f\u043e\u0441\u043e\u0431. \u0414\u043b\u044f \u0440\u0430\u0437\u0431\u0438\u0435\u043d\u0438\u044f \u0441\u0442\u0440\u043e\u043a\u0438 \u043f\u043e \u043d\u0435\u0441\u043a\u043e\u043b\u044c\u043a\u0438\u043c \u0440\u0430\u0437\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044f\u043c, \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0439\u0442\u0435 std::string::find_first_of. \u041a\u0430\u043a \u044d\u0442\u043e \u0441\u0434\u0435\u043b\u0430\u0442\u044c? \u0412 \u0441\u0430\u0439\u0442\u0435 \u0431\u044b\u0432\u0430\u043b\u0438 \u0442\u0430\u043a\u0438\u0435 \u0432\u043e\u043f\u0440\u043e\u0441\u044b, \u0442\u0430\u043a \u0447\u0442\u043e \u043d\u0430 \u043d\u0438\u0445 \u0443\u0436\u0435 \u043e\u0442\u0432\u0435\u0447\u0430\u043b\u0438. \u041f\u043e\u0438\u0449\u0438\u0442\u0435, \u043f\u043e\u043a\u043e\u043f\u0430\u0439\u0442\u0435\u0441\u044c \u0438 \u043d\u0430\u0439\u0434\u0435\u0442\u0435, \u0430 \u043b\u0443\u0447\u0448\u0435 \u043f\u044b\u0442\u0430\u0439\u0442\u0435\u0441\u044c \u0440\u0435\u0448\u0430\u0442\u044c \u0441\u0430\u043c\u043e\u0441\u0442\u043e\u044f\u0442\u0435\u043b\u044c\u043d\u043e.\n\nA: \u043e\u0442\u043a\u0440\u043e\u0439\u0442\u0435 \u0434\u043b\u044f \u0441\u0435\u0431\u044f strtok\n\u0440\u0430\u0431\u043e\u0442\u0430\u0435\u0442 \u0434\u043b\u044f \u0432\u0441\u0435\u0445 \u0440\u0430\u0437\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u0435\u0439\nstd::string input = \"one,two three four, five\\nsix seven , eight\";\nstd::cout << \"input: \\n\" << input << '\\n';\nstd::stringstream ss(input);\n\nstd::vector words; \nconst char* const delimeters = \", \";\nstd::string line;\nwhile (std::getline(ss, line))\n{\n char* token = std::strtok(line.data(), delimeters); \n while (token != nullptr)\n { \n words.push_back(token); \n token = std::strtok(nullptr, delimeters); \n }\n}\n\nstd::cout << \"words: \\n\";\nfor (long unsigned int i = 0; i < words.size(); i++)\n{\n std::cout << words[i] << std::endl;\n}\n\n", "meta": {"language": "ru", "url": "https://ru.stackoverflow.com/questions/1469554", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to obtain list of devices and their parameters using HKLM\\SYSTEM\\CurrentControlSet\\Enum? How to obtain the content and the main parameters of devices using registry section HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Enum?\nWell, I need to scan registry tree, containing ..\\Enum\\{SomeID}\\{OneMoreID}\\{MyDearValue}, which should contain some description, i.e. \"KINGSTON 100500TB Flash of God\". And the main question is: how to obtain all of this string descriptions, using WinAPI and C++?\n\nA: Use the Win32 Registry functions.\nhttp://msdn.microsoft.com/en-us/library/windows/desktop/ms724875(v=vs.85).aspx\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/14426521", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Linq to sql table dynamically with ExecuteQuery VB I am using VB Framework 4.0 and Linq to sql.\nI want to choose dynamycally the name of table. I have used the library namedtable.dll and I have mapped all the tables of database and it's Ok.\nMy problem is when I try to execute executequery. Here my code.\nImports Microsoft.VisualBasic\nImports System.Data.Linq\nImports Prototype.NamedTable.Data\nImports Prototype.NamedTable.Utility\n\n Public Class tipos\n\n Private _conexion As String = \"conexion\"\n\n Public Sub New()\n\n End Sub\n\n ...........\n\n Public Function getConsulta(byval tableName as String) As IList(Of TIPOS)\n\n Dim context As New DataContext(_conexion)\n\n sql = \" select COD, NAME from \" & tableName\n\n Dim a = context.ExecuteQuery(Of TIPOS)(sql)\n\n Return sql.ToList\n\n End Function\n End Class\n\nbut I have an error: \"El tipo 'TIPOS' debe declarar un constructor predeterminado (sin par\u00e1metros) para que pueda construirse durante la asignaci\u00f3n.\" that in English is: \n\"The type 'Type TIPOS' must declare a default (parameterless) constructor in order to be constructed during mapping\"\nI have defined \"TIPOS\" in other file:\nPublic Interface TIPOS\n Property COD Integer\n Property NAME As String\nEnd Interface\n\nPublic Class ITIPO : Implements TIPO\n Private _cod As Integer\n Private _name As String\n\n\n Public Property COD As Integer Implements TIPO.COD\n Get\n Return _cod\n End Get\n Set(ByVal value As Integer)\n _cod = value\n End Set\n End Property\n\n Public Property NAME As String Implements TIPO.NAME\n Get\n Return _name\n End Get\n Set(ByVal value As String)\n _name = value\n End Set\n End Property\n\nEnd Class\n\nI need help!\nSorry for my English.\n\nA: The solution can be found on codeproject.com in article \"Dynamic Table Mapping for LINQ-to-SQL.\" Below is a static class you can use. Please see the article for instructions on what you must do to use the 4 different generic methods. Here is an invocation example:\npublic interface IResult\n{\n [Column(IsPrimaryKey = true)]\n int Id { get; set; }\n\n [Column]\n string Name { get; set; }\n\n [Column]\n double Value { get; set; }\n}\n\npublic void TestThis()\n{\n var connectionString = \"Data Source=.\\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True;Pooling=False\";\n var context = new DataContext(connectionString);\n var table = context.GetTable(\"YourTableName\");\n var query = from r in table where r.Id == 108 select r;\n var list = query.ToList();\n}\n\nClass Code:\nnamespace Prototype.NamedTable\n{\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Data.Linq;\nusing System.Data.Linq.Mapping;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Reflection.Emit;\n\n/// \n/// The utility.\n/// \npublic static class Utility\n{\n #region Constants and Fields\n\n /// \n /// The named types.\n /// \n private static readonly Dictionary NamedTypes = new Dictionary();\n\n /// \n /// The _assembly builder.\n /// \n private static AssemblyBuilder _assemblyBuilder;\n\n /// \n /// The _module builder.\n /// \n private static ModuleBuilder _moduleBuilder;\n\n #endregion\n\n #region Properties\n\n /// \n /// Gets or sets a value indicating whether Verbose.\n /// \n public static bool Verbose { get; set; }\n\n #endregion\n\n #region Public Methods\n\n /// \n /// The clear.\n /// \n public static void Clear()\n {\n _assemblyBuilder = null;\n NamedTypes.Clear();\n }\n\n /// \n /// Retrieve a table from the data context which implements ITable<TEntity> by T and use ITable<TBack>\n /// \n /// \n /// Entity Type\n /// \n /// \n /// Backing Type\n /// \n /// \n /// Data Context\n /// \n /// \n /// \n public static ATable GetTable(this DataContext context) where TEntity : class\n where TBack : class\n {\n // Create the backup table\n Table refer = context.GetTable();\n\n // Prepare the cloning method\n Delegate cloneFrom = CompileCloning(typeof(TEntity), typeof(TBack));\n\n // Construct the table wrapper\n return new ATable(refer, cloneFrom);\n }\n\n /// \n /// Retrieve a table from the data context which implements ITable<TEntity> uses specific backing table\n /// \n /// \n /// Entity Type\n /// \n /// \n /// Data context\n /// \n /// \n /// Table name\n /// \n /// \n /// \n public static ATable GetTable(this DataContext context, string name) where TEntity : class\n {\n // Create/Retrieve a type definition for the table using the TEntity type\n Type type = DefineEntityType(typeof(TEntity), name);\n\n // Create the backup table using the new type\n ITable refer = context.GetTable(type);\n\n // Prepare the cloning method\n Delegate cloneFrom = CompileCloning(typeof(TEntity), type);\n\n // Construct the table wrapper\n return new ATable(refer, cloneFrom);\n }\n\n /*\n /// \n /// The log.\n /// \n /// \n /// The format.\n /// \n /// \n /// The args.\n /// \n public static void Log(string format, params object[] args)\n {\n if (!Verbose)\n {\n return;\n }\n\n Console.Write(\"*** \");\n\n if ((args == null) || (args.Length == 0))\n {\n Console.WriteLine(format);\n }\n else\n {\n Console.WriteLine(format, args);\n }\n }*/\n\n #endregion\n\n #region Methods\n\n /// \n /// Clone an attribute\n /// \n /// \n /// \n /// \n /// \n private static CustomAttributeBuilder CloneColumn(object attr)\n {\n Type source = attr.GetType();\n Type target = typeof(ColumnAttribute);\n\n var props = new List();\n var values = new List();\n\n // Extract properties and their values\n foreach (PropertyInfo prop in source.GetProperties())\n {\n if (!prop.CanRead || !prop.CanWrite)\n {\n continue;\n }\n\n props.Add(target.GetProperty(prop.Name));\n values.Add(prop.GetValue(attr, null));\n }\n\n // Create a new attribute using the properties and values\n return new CustomAttributeBuilder(\n target.GetConstructor(Type.EmptyTypes), new object[0], props.ToArray(), values.ToArray());\n }\n\n /// \n /// Make a delegate that copy content from \"source\" to \"dest\"\n /// \n /// \n /// Source Type\n /// \n /// \n /// Destination Type\n /// \n /// \n /// Executable delegate\n /// \n private static Delegate CompileCloning(Type source, Type dest)\n {\n // Input parameter\n ParameterExpression input = Expression.Parameter(source);\n\n // For every property, create a member binding\n List binds =\n source.GetProperties().Select(\n prop =>\n Expression.Bind(\n dest.GetProperty(\n prop.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly), \n Expression.MakeMemberAccess(input, prop))).Cast().ToList();\n\n // Expression of creating the new object\n MemberInitExpression body = Expression.MemberInit(\n Expression.New(dest.GetConstructor(Type.EmptyTypes)), binds);\n\n // The final lambda\n LambdaExpression lambda = Expression.Lambda(body, input);\n\n // MJE\n //Log(\"{0}\", lambda.ToString());\n\n // Return the executable delegate\n return lambda.Compile();\n }\n\n /// \n /// Create a class based on the template interface\n /// \n /// \n /// \n /// \n /// \n /// \n /// \n private static Type DefineEntityType(Type template, string name)\n {\n // Prepare the builders if not done\n if (_assemblyBuilder == null)\n {\n _assemblyBuilder =\n AppDomain.CurrentDomain.DefineDynamicAssembly(\n new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);\n\n _moduleBuilder = _assemblyBuilder.DefineDynamicModule(\"Types\");\n }\n\n // Check if there is already a type created for that table\n if (NamedTypes.ContainsKey(name))\n {\n return NamedTypes[name];\n }\n\n // Create the new type\n TypeBuilder tbuilder = null;\n if (template.IsInterface)\n {\n tbuilder = DefineInterfaceChild(name, template);\n }\n else\n {\n tbuilder = DefineOverriddenChild(name, template);\n }\n\n Type final = tbuilder.CreateType();\n\n NamedTypes[name] = final;\n\n return final;\n }\n\n /// \n /// The define interface child.\n /// \n /// \n /// The name.\n /// \n /// \n /// The template.\n /// \n /// \n /// \n private static TypeBuilder DefineInterfaceChild(string name, Type template)\n {\n TypeBuilder tbuilder = _moduleBuilder.DefineType(\n name, TypeAttributes.Public, typeof(Object), new[] { template });\n\n // Default constructor\n tbuilder.DefineDefaultConstructor(MethodAttributes.Public);\n\n // Attach Table attribute\n var abuilder = new CustomAttributeBuilder(\n typeof(TableAttribute).GetConstructor(Type.EmptyTypes), \n new object[0], \n new[] { typeof(TableAttribute).GetProperty(\"Name\") }, \n new object[] { name });\n tbuilder.SetCustomAttribute(abuilder);\n\n List properties = template.GetProperties().ToList(); // May require sorting\n\n // Implement all properties));\n foreach (PropertyInfo prop in properties)\n {\n // Define backing field\n FieldBuilder fbuilder = tbuilder.DefineField(\n \"_\" + prop.Name, prop.PropertyType, FieldAttributes.Private);\n\n // Define get method\n MethodBuilder pgbuilder = tbuilder.DefineMethod(\n \"get_\" + prop.Name, \n MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig\n | MethodAttributes.Virtual | MethodAttributes.Final, \n prop.PropertyType, \n Type.EmptyTypes);\n\n // Define get method body { return _field; }\n ILGenerator ilg = pgbuilder.GetILGenerator();\n ilg.Emit(OpCodes.Ldarg_0);\n ilg.Emit(OpCodes.Ldfld, fbuilder);\n ilg.Emit(OpCodes.Ret);\n\n // Define set method\n MethodBuilder psbuilder = tbuilder.DefineMethod(\n \"set_\" + prop.Name, \n MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig\n | MethodAttributes.Virtual | MethodAttributes.Final, \n null, \n new[] { prop.PropertyType });\n\n // Define set method body { _field = value; }\n ILGenerator ils = psbuilder.GetILGenerator();\n ils.Emit(OpCodes.Ldarg_0);\n ils.Emit(OpCodes.Ldarg_1);\n ils.Emit(OpCodes.Stfld, fbuilder);\n ils.Emit(OpCodes.Ret);\n\n // Define the property\n PropertyBuilder pbuilder = tbuilder.DefineProperty(\n prop.Name, PropertyAttributes.None, CallingConventions.Standard, prop.PropertyType, null);\n\n // Set get/set method\n pbuilder.SetGetMethod(pgbuilder);\n pbuilder.SetSetMethod(psbuilder);\n\n // Attach Column attribute\n foreach (object attr in prop.GetCustomAttributes(false))\n {\n if (attr is ColumnAttribute || attr is AlterColumnAttribute)\n {\n // MJE\n //Log(\"Create column attribute for {0}\", prop.Name);\n pbuilder.SetCustomAttribute(CloneColumn(attr));\n break;\n }\n }\n }\n\n return tbuilder;\n }\n\n /// \n /// The define overridden child.\n /// \n /// \n /// The name.\n /// \n /// \n /// The template.\n /// \n /// \n /// \n private static TypeBuilder DefineOverriddenChild(string name, Type template)\n {\n TypeBuilder tbuilder = _moduleBuilder.DefineType(name, TypeAttributes.Public, template);\n\n // Default constructor\n tbuilder.DefineDefaultConstructor(MethodAttributes.Public);\n\n // Attach Table attribute\n var abuilder = new CustomAttributeBuilder(\n typeof(TableAttribute).GetConstructor(Type.EmptyTypes), \n new object[0], \n new[] { typeof(TableAttribute).GetProperty(\"Name\") }, \n new object[] { name });\n tbuilder.SetCustomAttribute(abuilder);\n\n List properties = template.GetProperties().ToList(); // May require sorting\n\n // Implement all properties));\n foreach (PropertyInfo prop in properties)\n {\n // Define get method\n MethodBuilder pgbuilder = tbuilder.DefineMethod(\n \"get_\" + prop.Name, \n MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig\n | MethodAttributes.Virtual | MethodAttributes.Final, \n prop.PropertyType, \n Type.EmptyTypes);\n\n // Define get method body { return _field; }\n ILGenerator ilg = pgbuilder.GetILGenerator();\n ilg.Emit(OpCodes.Ldarg_0);\n ilg.Emit(OpCodes.Call, template.GetMethod(\"get_\" + prop.Name));\n ilg.Emit(OpCodes.Ret);\n\n // Define set method\n MethodBuilder psbuilder = tbuilder.DefineMethod(\n \"set_\" + prop.Name, \n MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig\n | MethodAttributes.Virtual | MethodAttributes.Final, \n null, \n new[] { prop.PropertyType });\n\n // Define set method body { _field = value; }\n ILGenerator ils = psbuilder.GetILGenerator();\n ils.Emit(OpCodes.Ldarg_0);\n ils.Emit(OpCodes.Ldarg_1);\n ils.Emit(OpCodes.Call, template.GetMethod(\"set_\" + prop.Name));\n ils.Emit(OpCodes.Ret);\n\n // Define the property\n PropertyBuilder pbuilder = tbuilder.DefineProperty(\n prop.Name, PropertyAttributes.None, CallingConventions.Standard, prop.PropertyType, null);\n\n // Set get/set method\n pbuilder.SetGetMethod(pgbuilder);\n pbuilder.SetSetMethod(psbuilder);\n\n // Attach Column attribute\n foreach (object attr in prop.GetCustomAttributes(false))\n {\n if (attr is ColumnAttribute || attr is AlterColumnAttribute)\n {\n // MJE\n //Log(\"Create column attribute for {0}\", prop.Name);\n pbuilder.SetCustomAttribute(CloneColumn(attr));\n break;\n }\n }\n }\n\n return tbuilder;\n }\n\n #endregion\n\n /// \n /// A table wrapper implements ITable<TEntity> backed by other ITable object\n /// \n /// \n /// \n public class ATable : ITable\n where TEntity : class\n {\n #region Constants and Fields\n\n /// \n /// Cloning method\n /// \n private readonly Delegate _clone;\n\n /// \n /// Backing table\n /// \n private readonly ITable _internal;\n\n #endregion\n\n #region Constructors and Destructors\n\n /// \n /// Initializes a new instance of the class. \n /// Construct from backing table\n /// \n /// \n /// \n /// \n /// \n public ATable(ITable inter, Delegate from)\n {\n this._internal = inter;\n this._clone = from;\n }\n\n #endregion\n\n #region Properties\n\n /// \n /// Gets ElementType.\n /// \n public Type ElementType\n {\n get\n {\n // Use the backing table element\n return this._internal.ElementType;\n }\n }\n\n /// \n /// Gets Expression.\n /// \n public Expression Expression\n {\n get\n {\n // Use the backing table expression\n return this._internal.Expression;\n }\n }\n\n /// \n /// Gets Provider.\n /// \n public IQueryProvider Provider\n {\n get\n {\n // Use the backing table provider\n return this._internal.Provider;\n }\n }\n\n #endregion\n\n #region Implemented Interfaces\n\n #region IEnumerable\n\n /// \n /// The get enumerator.\n /// \n /// \n /// \n /// \n /// \n IEnumerator IEnumerable.GetEnumerator()\n {\n throw new NotImplementedException();\n }\n\n #endregion\n\n #region IEnumerable\n\n /// \n /// The get enumerator.\n /// \n /// \n /// \n /// \n /// \n public IEnumerator GetEnumerator()\n {\n throw new NotImplementedException();\n }\n\n #endregion\n\n #region ITable\n\n /// \n /// The attach.\n /// \n /// \n /// The entity.\n /// \n /// \n /// \n public void Attach(TEntity entity)\n {\n throw new NotImplementedException();\n }\n\n /// \n /// The delete on submit.\n /// \n /// \n /// The entity.\n /// \n public void DeleteOnSubmit(TEntity entity)\n {\n // Directly invoke the backing table\n this._internal.DeleteOnSubmit(entity);\n }\n\n /// \n /// The insert on submit.\n /// \n /// \n /// The entity.\n /// \n public void InsertOnSubmit(TEntity entity)\n {\n // Input entity must be changed to backing type\n object v = this._clone.DynamicInvoke(entity);\n\n // Invoke the backing table\n this._internal.InsertOnSubmit(v);\n }\n\n #endregion\n\n #endregion\n }\n\n /// \n /// The alter column attribute.\n /// \n public class AlterColumnAttribute : Attribute\n {\n #region Constants and Fields\n\n /// \n /// The _can be null.\n /// \n private bool _canBeNull = true;\n\n /// \n /// The _update check.\n /// \n private UpdateCheck _updateCheck = UpdateCheck.Always;\n\n #endregion\n\n #region Properties\n\n /// \n /// Gets or sets AutoSync.\n /// \n public AutoSync AutoSync { get; set; }\n\n /// \n /// Gets or sets a value indicating whether CanBeNull.\n /// \n public bool CanBeNull\n {\n get\n {\n return this._canBeNull;\n }\n\n set\n {\n this._canBeNull = value;\n }\n }\n\n /// \n /// Gets or sets DbType.\n /// \n public string DbType { get; set; }\n\n /// \n /// Gets or sets Expression.\n /// \n public string Expression { get; set; }\n\n /// \n /// Gets or sets a value indicating whether IsDbGenerated.\n /// \n public bool IsDbGenerated { get; set; }\n\n /// \n /// Gets or sets a value indicating whether IsDiscriminator.\n /// \n public bool IsDiscriminator { get; set; }\n\n /// \n /// Gets or sets a value indicating whether IsPrimaryKey.\n /// \n public bool IsPrimaryKey { get; set; }\n\n /// \n /// Gets or sets a value indicating whether IsVersion.\n /// \n public bool IsVersion { get; set; }\n\n /// \n /// Gets or sets UpdateCheck.\n /// \n public UpdateCheck UpdateCheck\n {\n get\n {\n return this._updateCheck;\n }\n\n set\n {\n this._updateCheck = value;\n }\n }\n\n #endregion\n }\n}\n}\n\n\nA: Linq-to-Sql cannot materialize interfaces. It needs a class specification to know what instances it should create from a query. The exception message is elusive, to say the least. I don't know why it isn't more to the point.\nNote that the class you want to materialize must have been mapped, or: it must be in the dbml. I say this because your ITIPO class is not partial, which makes me wonder how you can make it implement an interface (well, maybe you just slimmed down the code).\nSide note: don't use all capitals for class names, and prefix an interface specification with \"I\", not a class.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/13911036", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: android kotlin shared preferences unresolved reference getSharedPreferences error I am learning Kotlin by trying to build a small app that find and and remember last connected BLE device. To recognize the last connected device I decide to save its MAC address using shared preferences (is that the best way to do that is also a question). I use a tutorial online and it worked well (I didn't remember the page) but today when I open the project to continue the job it gives me error - unresolved reference getSharedPreferences. My question is what is the problem - I get lost :) Here is the class where I have the error row 23.\nimport android.content.Context\nimport android.content.SharedPreferences\ninterface PreferencesFunctions {\nfun setDeviceMAC(deviceMAC: String)\nfun getDeviceMAC(): String\nfun setLastConnectionTime(lastConnectionTime: String)\nfun getLastConnectionTime(): String\nfun clearPrefs()\n\n}\nclass PreferenceManager(context: ScanResultAdapter.ViewHolder) : PreferencesFunctions{\nprivate val PREFS_NAME = \"SharedPreferences\"\nprivate var preferences: SharedPreferences\n\ninit {\n preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)\n}\n\noverride fun setDeviceMAC(deviceMAC: String) {\n preferences[DEVICE_MAC] = deviceMAC\n}\n\noverride fun getDeviceMAC(): String {\n return preferences[DEVICE_MAC] ?: \"\"\n}\n\noverride fun setLastConnectionTime(lastConnectionTime: String) {\n preferences[LAST_CONNECTION_TIME] = lastConnectionTime\n}\n\noverride fun getLastConnectionTime(): String {\n return preferences[LAST_CONNECTION_TIME] ?: \"\"\n}\n\noverride fun clearPrefs() {\n preferences.edit().clear().apply()\n}\n\ncompanion object{\n\n const val DEVICE_MAC = \"yyyyyyy\"\n const val LAST_CONNECTION_TIME = \"zzzzzzz\"\n\n}\n\n}\n\nA: Your arguement context is not a acitivity or fragment, and you need those two to call getSharedPreferences method.\nclass PreferenceManager(context: Context) : PreferencesFunctions{\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/66820897", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}} {"text": "Q: MvvmCross throwing InvalidStackFrameException I am using MvvmCross to develop an ios app. Everything worked fine until suddenly I got the following exception:\nMono.Debugger.Soft.InvalidStackFrameException: The requested operation cannot be completed because the specified stack frame is no longer valid.\n at Mono.Debugger.Soft.VirtualMachine.ErrorHandler (System.Object sender, Mono.Debugger.Soft.ErrorHandlerEventArgs args) [0x00076] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachine.cs:301 \n at Mono.Debugger.Soft.Connection.SendReceive (CommandSet command_set, Int32 command, Mono.Debugger.Soft.PacketWriter packet) [0x000f9] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs:1448 \n at Mono.Debugger.Soft.Connection.StackFrame_GetValues (Int64 thread_id, Int64 id, System.Int32[] pos) [0x00026] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs:2225 \n at Mono.Debugger.Soft.StackFrame.GetValue (Mono.Debugger.Soft.LocalVariable var) [0x0005f] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/StackFrame.cs:122 \n at Mono.Debugging.Soft.VariableValueReference.get_Value () [0x0001a] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging.Soft/VariableValueReference.cs:68 \n at Mono.Debugging.Evaluation.ValueReference.OnCreateObjectValue (Mono.Debugging.Client.EvaluationOptions options) [0x00033] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging/Mono.Debugging.Evaluation/ValueReference.cs:138 \n at Mono.Debugging.Evaluation.ValueReference.CreateObjectValue (Mono.Debugging.Client.EvaluationOptions options) [0x00059] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging/Mono.Debugging.Evaluation/ValueReference.cs:106 Mono.Debugger.Soft.InvalidStackFrameException: The requested operation cannot be completed because the specified stack frame is no longer valid.\n at Mono.Debugger.Soft.VirtualMachine.ErrorHandler (System.Object sender, Mono.Debugger.Soft.ErrorHandlerEventArgs args) [0x00076] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachine.cs:301 \n at Mono.Debugger.Soft.Connection.SendReceive (CommandSet command_set, Int32 command, Mono.Debugger.Soft.PacketWriter packet) [0x000f9] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs:1448 \n at Mono.Debugger.Soft.Connection.StackFrame_GetValues (Int64 thread_id, Int64 id, System.Int32[] pos) [0x00026] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs:2225 \n at Mono.Debugger.Soft.StackFrame.GetValue (Mono.Debugger.Soft.LocalVariable var) [0x0005f] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/StackFrame.cs:122 \n at Mono.Debugging.Soft.VariableValueReference.get_Value () [0x0001a] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging.Soft/VariableValueReference.cs:68 \n at Mono.Debugging.Evaluation.ValueReference.OnCreateObjectValue (Mono.Debugging.Client.EvaluationOptions options) [0x00033] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging/Mono.Debugging.Evaluation/ValueReference.cs:138 \n at Mono.Debugging.Evaluation.ValueReference.CreateObjectValue (Mono.Debugging.Client.EvaluationOptions options) [0x00059] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging/Mono.Debugging.Evaluation/ValueReference.cs:106 \n\nIt is important to say that this only happens on the device, everything works perfectly on the simulator...\nI have fiddled with the code to come to a conclusion once I removed the following code everything worked:\nvar source = new MvxSimpleTableViewSource (MainTable, RecomendationTemplate.Key, RecomendationTemplate.Key);\n MainTable.Source = source;\n var set = this.CreateBindingSet ();\n set.Bind (source).To (vm => vm.Recomendations);\n set.Apply ();\n\nAfter that I have tried to use a difference cell template. I started with an empty one and it worked. but once I added the DelayBind mehtod I kept on getting the following exception... I have no idea how to move forward from here. \n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/21215725", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Sql Server Stored Procedure not executing from MVC I am trying to execute a stored procedure in my Sql Server Database from an Asp.Net MVC project. I have set it up in a way that I can use it for testing purposes, which is why the variable \"procedureTest\" is a constant value (I know that \"2044\" is an existing record in my database). I will change this once I accomplish a successful run. Also, I know that my stored procedure works because I have executed it in Sql Server Management Studio successfully. The procedure has the task of adding ID from one table to another, but I have yet to see it appear in this table. I am not receiving an error in my catch block so I am kind of lost at the moment. I could definitely use your help.\ntry\n{\n using (var connection = new SqlConnection(connectionString))\n {\n connection.Open();\n\n int procedureTest = 2044;\n\n var command = new SqlCommand(\"SELECT ID FROM Images WHERE ID = @id\", connection);\n var paramDate = new SqlParameter(\"@id\", procedureTest);\n command.Parameters.Add(paramDate);\n var reader = command.ExecuteReader();\n\n while (reader.Read())\n {\n var storedProcCommand = new SqlCommand(\"EXEC addToNotificationTable @ID\", connection);\n var paramId = new SqlParameter(\"@ID\", reader.GetInt32(0));\n storedProcCommand.Parameters.Add(paramId);\n command.ExecuteNonQuery();\n }\n }\n}\ncatch (Exception e)\n{\n string exceptionCause = String.Format(\"An error occurred: '{0}'\", e);\n System.IO.File.WriteAllText(@\"C:\\Users\\Nathan\\Documents\\Visual Studio 2013\\Projects\\MVCImageUpload\\uploads\\exception.txt\", exceptionCause);\n} \n\nStored Procedure:\nCREATE PROCEDURE addToNotificationTable @ID int\nAS\nInsert NotificationTable (ID)\nSELECT ID \nFROM Images\nWhere ID = @ID\n\n\nA: Change you code like this\nwhile (reader.Read())\n {\n var storedProcCommand = new SqlCommand(\"EXEC addToNotificationTable @ID\", connection);\n var paramId = new SqlParameter(\"@ID\", reader.GetInt32(0));\n storedProcCommand.Parameters.Add(paramId);\n storedProcCommand.ExecuteNonQuery();\n }\n\n\nA: First of all, you missed to specify the command type. Also using EXEC in SqlCommand is not a proper way.\nPlease try with the below code\nwhile (reader.Read())\n {\n using(SqlCommand storedProcCommand = new SqlCommand(\"addToNotificationTable\", connection)) //Specify only the SP name\n { \n storedProcCommand.CommandType = CommandType.StoredProcedure; //Indicates that Command to be executed is a stored procedure no a query\n var paramId = new SqlParameter(\"@ID\", reader.GetInt32(0));\n storedProcCommand.Parameters.Add(paramId);\n storedProcCommand.ExecuteNonQuery()\n }\n }\n\nSince you are calling the sp inside a while loop, wrap the code in using() { } to automatically dispose the command object after each iteration\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/31530797", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to insert special HTML-symbols with HAML When I'm saying:\n%p= item.price + \" dollars\"\n\nI'm getting\n\n50  ;dollars\n\ninstead of having non-breakable space symbol.\nHow to insert this and another special symbols using HAML ?\n\nA: How about \n%p= item.price + \" dollars\".html_safe\n\n\nA: This answer is for a slightly different question but I found this question searching for it...\nIf you have a submit tag %input{ :type => \"submit\", :value => \" dollars\", :name => \"very_contrived\" } even if you throw an html_safe on the :value it will not evaluate the html.\nThe solution is to use the rails helper... duh \n= submit_tag \" dollars\".html_safe\n\nthis is pretty obvious but it tripped me up. Legacy code + rails upgrade = this kind of stuff :P\n\nA: Use != instead of =\nSee \"Unescaping HTML\" in the haml reference: http://haml.info/docs/yardoc/file.REFERENCE.html#unescaping_html\n\nA: The interpolation option:\n%p= \"#{item.price} dollars\".html_safe\n\n\nA: I tried using html_safe in different ways, but none worked. Using \\xa0 as suggested by ngn didn't work, either, but it got me to try the Unicode escape of the non-breaking space, which did work:\n\"FOO\\u00a0BAR\"\n\nand .html_safe isn't even needed (unless something else in the string needs that, of course).\nThe Ruby Programming Language, first edition, says: \"In Ruby 1.9, double-quoted strings can include arbitrary Unicode escape characters with \\u escapes. In its simplest form, \\u is followed by exactly four hexadecimal digits ...\"\n\nA: You could use \\xa0 in the string instead of  . 0xa0 is the ASCII code of the non-breaking space.\n\nA: I prefer using the character itself with the escaped HTML method with most symbols other than the whitespace characters. That way i don't have to remember all the html codes. As for the whitespace characters i prefer to use CSS, this is a much cleaner way.\n%p&= \"#{item.price} $%&#*@\"\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/6305414", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "45"}} {"text": "Q: Trying to replace values in a data frame with other values I have a list of vectors, L1, and a data frame, df2. I want to take values from df2 and replace the values of L1 with these. For example, when ABCC10 of L1 says \"TCGA_DD_A1EG\", I want to replace this with the value, 2.193205, from row 1 (ABCC10), column 3 (TCGA.DD.A1EG). I want to do this with every value. \nL1 looks like this:\n$ABCC10\n[1] \"TCGA_DD_A1EG\" \"TCGA_FV_A3R2\" \"TCGA_FV_A3I0\" \"TCGA_DD_A1EH\" \"TCGA_FV_A23B\"\n\n$ACBD6\n[1] \"TCGA_DD_A1EH\" \"TCGA_DD_A3A8\" \"TCGA_ES_A2HT\" \"TCGA_DD_A1EG\" \"TCGA_DD_A1EB\"\n\ndf2 looks like this:\n TCGA.BC.A10Q TCGA.DD.A1EB TCGA.DD.A1EG TCGA.DD.A1EH TCGA.DD.A1EI TCGA.DD.A3A6 TCGA.DD.A3A8\nABCC10 2.540764 0.4372165 2.193205 3.265756 0.6060301 2.927072 0.6799514\nACBD6 1.112432 0.4611697 1.274129 1.802985 -0.0475743 1.071064 0.4336301\n TCGA.ES.A2HT TCGA.FV.A23B TCGA.FV.A3I0 TCGA.FV.A3R2\nABCC10 -0.08129554 2.2963764 3.196518 0.8595943\nACBD6 1.76935812 0.3644397 1.392206 1.0282030\n\n\nA: One approach could be like\ndf1 = list(ABCC10 = c(\"TCGA_DD_A1EG\", \"TCGA_FV_A3R2\", \"TCGA_FV_A3I0\", \"TCGA_DD_A1EH\", \"TCGA_FV_A23B\"),\n ACBD6 = c(\"TCGA_DD_A1EH\", \"TCGA_DD_A3A8\", \"TCGA_ES_A2HT\", \"TCGA_DD_A1EG\", \"TCGA_DD_A1EB\"))\n\ndf2 = data.frame(TCGA.BC.A10Q = c(2.540764, 1.112432),\n TCGA.DD.A1EB = c(0.4372165, 0.4611697),\n TCGA.DD.A1EG = c(2.193205, 1.274129),\n TCGA.DD.A1EH = c(3.265756, 1.802985),\n TCGA.DD.A1EI = c(0.6060301, -0.0475743),\n TCGA.DD.A3A6 = c(2.927072, 1.071064),\n TCGA.DD.A3A8 = c(0.6799514, 0.4336301),\n TCGA.ES.A2HT = c(-0.08129554, 1.76935812),\n TCGA.FV.A23B = c(2.2963764, 0.3644397),\n TCGA.FV.A3I0 = c(3.196518, 1.392206),\n TCGA.FV.A3R2 = c(0.8595943, 1.0282030),\n row.names = c('ABCC10', 'ACBD6'))\n\nfor(i in 1:length(df1)){\n for(j in 1:length(df1[[1]])){\n df1[names(df1)[i]][[1]][j] = df2[names(df1)[i],gsub(\"_\",\".\",df1[names(df1)[i]][[1]][j])]\n }\n}\n\nOutput is:\n$ABCC10\n[1] \"2.193205\" \"0.8595943\" \"3.196518\" \"3.265756\" \"2.2963764\"\n\n$ACBD6\n[1] \"1.802985\" \"0.4336301\" \"1.76935812\" \"1.274129\" \"0.4611697\" \n\nHope this helps!\n\nA: Maybe the following will do it.\nFirst, make up some data, a list and a data.frame.\ndf1 <- list(A = letters[1:3], B = letters[5:7])\n\ndf2 <- data.frame(a = rnorm(2), b = rnorm(2), c = rnorm(2),\n e = rnorm(2), f = rnorm(2), g = rnorm(2))\nrow.names(df2) <- c('A', 'B')\n\nNow the code.\nfor(i in seq_along(df1)){\n x <- gsub(\"_\", \".\", df1[[i]])\n inx <- match(x, names(df2))\n df1[[i]] <- df2[i, inx]\n}\ndf1\n\nIn my tests it did what you want. If it doesn't fit your real problem, just say so.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/45947581", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Binding value in JSP page I have a XML value in controller and i'm passing that value to jsp page and binding as shown in the below code.\n \n\nIt is binding the value as shown in the below.\n \n\nBut i want to bind like below without spaces.\n\n\n\nIs there any way to bind like as shown in the above?\n\n\nA: You can perform a manipulation of the xml string in your controller with a little regex to eliminate the newlines and whitespace. \nHere is a little java app to show the regex in work against your xml string.\npublic class StripXmlWhitespace {\n\n public static void main (String [] args) {\n String xmlString = \"\\n\" + \n \" \\n\" + \n \" \\n\" + \n \" 30e3ed7f512da50206b8720d52457309c87f4edfee85d08f937aef3f955fb7af\\n\" + \n \" \\n\" + \n \" \\n\" + \n \" \\n\" + \n \" \\n\" + \n \" \\n\" + \n \" \\n\" + \n \" \\n\" + \n \" \\n\" + \n \" \\n\" + \n \" \\n\" + \n \" kQEB9r4dd5hhdaPxc4sjPMG3SGM=\\n\" + \n \" \\n\" + \n \" \\n\" + \n \" MSgEXK2+GpwnRBr3vLNncqc9FOY0oDhjlhfyihOjrUPFZAL8eBms6jXdhoWGlrypaF6hE70ZltDQbQTArrk/mfCmoVvna7yEJN9gDh6gAHbh9Zj4BEBdWhd85DKbAdtSy8zYTKIeIjhFBzOItUAhSN7lFrEFVrTLV5wO38hswD7LlaY4ZBSNMWbpHPx+Io6ukdP8b4n95dqoB9iiqKxg3nK0RslhLRcPoe4B2AsdoiZ42iY/tZ4disOzyOCyCdE8nRxipJbP9HZS3psCSCar3CPSigXiNk6fY7+bDEFbJrfoqhHBk1hasx2m0TbxZVeOIPSUPRYpekHCm0sm4RvZhA==\\n\" + \n \" \\n\" + \n \" \\n\" + \n \" CN=AAA Bank Test,OU=AAA Bank IT Dept,O=AAA Bank,L=Delhi,ST=Delhi,C=91\\n\" + \n \" MIIDkTCCAnmgAwIBAgIEZNl4CjANBgkqhkiG9w0BAQsFADB5MQswCQYDVQQGEwI5MTETMBEGA1UECBMKTWFoYXJhc3RyYTEPMA0GA1UEBxMGTXVtYmFpMREwDwYDVQQKEwhSYmwgQmFuazEZMBcGA1UECxMQUkJMIEJhbmsgSVQgRGVwdDEWMBQGA1UEAxMNUmJsIEJhbmsgVGVzdDAeFw0xNzAzMDIxNDA4MTBaFw0xODAyMjUxNDA4MTBaMHkxCzAJBgNVBAYTAjkxMRMwEQYDVQQIEwpNYWhhcmFzdHJhMQ8wDQYDVQQHEwZNdW1iYWkxETAPBgNVBAoTCFJibCBCYW5rMRkwFwYDVQQLExBSQkwgQmFuayBJVCBEZXB0MRYwFAYDVQQDEw1SYmwgQmFuayBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjsF71lv96Y+2DbuSgk1U/Bp3P+jPpKp9GpwiVuIAf4SsBc1bqR3x4JSnY4COdUlq2IkHYSGnufGkPS6tH4edoFpZrSBAiTo1D0WQQ4KoRWBzn9xptMGsJBoV7dcSovjjD1HhUJGNnfoxjBh3AmIe8ZySWhuouEA8cRtFcHoWunpSB1FOJreIZ1P/ZnJ7C4gu+E1ccXjkFPqCGI9RcdUSE72K+ovtI/yWIUPwXdj3O/k30iX2owxUVFKnCmIDFnKDJ/b96RDzlIB9FiH5IVQm4mcU6HiQKqknDI3bPKlwvfFfB+YI69vjRQf3dvsca2nZQsYT3iSgkxBwoiugsD59QIDAQABoyEwHzAdBgNVHQ4EFgQUwFYILDVGVtIJgYveFqZ9YRrRq4AwDQYJKoZIhvcNAQELBQADggEBAKygyzVE1sOaBxuj4IjGDmo2y5UOhPOzklRocZbsqycEApcBn5m/dVauvewqw7An1vrkvjTYbTUCjUKghNW/MdtiWbKKRDy3fA8DyEACcYuK0PpaaXMTJFjIjKxXko6Rmmp6CKFcmERgetiwrFreMfFjvCv9H1fk7FSR87d/17l/LsmAndFIvpZTF3Ruz4lZsoL2qWtBF+wnVjFW+yqf6nXDqE/Swxhiq7dZ+Dl0ilgEsh3Q1WOO/S/TBDkeURIHfIkc886p5M4u5iQdkO1fndptUhBNbaM1idMOW/5QUWFeIEChdSo3mrVVTWyvhQEkYls0GYJUSVSdaITcyE3xkJA=\\n\" + \n \" \\n\" + \n \" \\n\" + \n \" \\n\" + \n \" \";\n String output = xmlString.replaceAll(\">\\\\s+<\", \"><\");\n System.out.println(xmlString);\n System.out.println(output);\n\n }\n\n}\n\nAll you need in your controller is the regex.\nxml = xmlString.replaceAll(\">\\\\s+<\", \"><\");\n\nEssentially unformat the xml before you send it bind it to the view. I hope that helps.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/48564808", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: REGEX to extract multiple name/value tokens (vbscript) Given a template that looks like this:\n{*}Street Address:\n\n\n ^^ might be a space here, might not ^^ always a space here\n\n\nI need to read the name=value pairs out of the comment, plus the whole string so it can be replaced. Names could be any alpha-numeric with no spaces, values could contain anything except double quotes, will be short as possible, and will always be surrounded by double-quotes.\nSo, possible formats:\n\n\n\n\nI've tried a dozen different variations, but the most successful I've been so far is to get the first name=\"value\" pair and nothing else, or I get the whole page worth of stuff. So the desired matches are\n[1] \n[2] drinks\n[3] yes, please\n[4] breadsticks\n[5] garlic, butter (lots); cheese\n\nThe closest I've come so far is \n\n\nbut it only returns the last pair, not all of them.\n\nA: Implementation of the 2 step processes @sln mentioned in VBScript:\nOption Explicit\n\nDim rCmt : Set rCmt = New RegExp\nrCmt.Global = True\nrCmt.Pattern = \"\"\nDim rKVP : Set rKVP = New RegExp\nrKVP.Global = True\nrKVP.Pattern = \"(\\w+)=\"\"([^\"\"]*)\"\"\"\nDim sInp : sInp = Join(Array( _\n \"{*}Street Address:\" _\n , \"\" _\n , \"\" _\n , \"\" _\n , \"\" _\n), vbCrLf)\n\nWScript.Echo sInp\nWScript.Echo \"-----------------\"\nWScript.Echo rCmt.Replace(sInp, GetRef(\"fnRepl\"))\nWScript.Quit 0\n\nFunction fnRepl(sMatch, nPos, sSrc)\n Dim d : Set d = CreateObject(\"Scripting.Dictionary\")\n Dim ms : Set ms = rKVP.Execute(sMatch)\n Dim m\n For Each m In ms\n d(m.SubMatches(0)) = m.SubMatches(1)\n Next\n fnRepl = \"a comment containing \" & Join(d.Keys)\nEnd Function\n\noutput:\ncscript 45200777-2.vbs\n{*}Street Address:\n\n\n\n\n-----------------\n{*}Street Address:\n\na comment containing template for prev\n\na comment containing pipapo rof prev\n\nAs Mr. Gates Doc for the .Replace method sucks, see 1, 2, 3.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/45200777", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: find out what instructions write to this memory address olly dbg cheat engine Is there an option in ollydbg to find out what pieces of code write to a memory address ? Just like Cheat Engine shows all the assembly instructions that write to a specific address.\n\"breakpoint --> memory\" does not work.\n\nA: Yes,\nWith olly open and debugging a certain program, go to View tab>Memory or Alt+M\nthen, find the memory address (first you have to choose the memory part of the program like .data or .bss) and then click on the address (or addresses selecting multiple with Shift) with the right mouse button and hover to Breakpoint then you'll be able to choose the to break the program when it writes or reads the address\nA good thing to do is first find the address on cheatEngine then use the breakpoint on ollydbg.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/27363155", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: setNeedsDisplay not resulting in dirtyRect filling entire view I am having a confusing issue. I try to draw a graph, and call setNeedsDisplay each time new data is added to the graph.\nThe graph receives new data via addData:(NSNotification*)theNote, which then tries several ways to call setNeedsDisplay to redraw the view. The data does not get redrawn properly, however, at this time. If I drag the window to another screen, or if I click on the graph and call setNeedsDisplay from mouseDown then the view is redrawn correctly. By monitoring the size of dirtyRect using NSLog, I have tracked the problem to a too small dirtyRect. But I cannot even guess how to correct this. Any ideas out there?\n//\n// graphView.m\n// miniMRTOF\n//\n// Created by \u30b7\u30e5\u30fc\u30ea \u30d4\u30fc\u30bf\u30fc on 8/1/16.\n// Copyright \u00a9 2016 \u30b7\u30e5\u30fc\u30ea \u30d4\u30fc\u30bf\u30fc. All rights reserved.\n//\n\n#import \"graphView.h\"\n\n@implementation graphView\n\n- (id)initWithFrame:(NSRect)frame{\n self = [super initWithFrame:frame];\n if (self) {\n\n NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];\n [nc addObserver:self selector:@selector(addData:) name:AddDataNotification object:nil];\n\n theData = [[NSMutableArray alloc] init];\n\n NSLog(@\"graphView initialized\");\n\n }\n return self;\n}\n\n-(void)addData:(NSNotification*)theNote{\n NSLog(@\"graphView has gotten the note\");\n\n NSMutableArray *theThermalArray = [[NSMutableArray alloc] init];\n\n theThermalArray = [[theNote userInfo] objectForKey:@\"theThermals\"];\n float ave = 0;\n int n = 0;\n for (int i=0; i<16; i++){\n float f_i = [[theThermalArray objectAtIndex:i] floatValue];\n ave += f_i;\n if(f_i != 0) n++;\n }\n ave /= n;\n\n [theData addObject:[NSNumber numberWithFloat:ave]];\n NSLog(@\"graphView has added %0.3f and now has %lu components\", ave, (unsigned long)[theData count]);\n [self setNeedsDisplay:YES];\n [[self.window contentView] setNeedsDisplay:YES];\n [self performSelectorOnMainThread:@selector(redraw) withObject:nil waitUntilDone:YES];\n}\n\n-(void)redraw{\n [self setNeedsDisplay:YES];\n [[self.window contentView] setNeedsDisplay:YES];\n\n}\n\n- (void)drawRect:(NSRect)dirtyRect {\n [super drawRect:dirtyRect];\n // Drawing code here.\n\n NSLog(@\"dirtyRect: x:%0.2f, y:%0.2f, w:%0.2f, h:%0.2f\", dirtyRect.origin.x, dirtyRect.origin.y, dirtyRect.size.width, dirtyRect.size.height);\n\n float xScale = ([self bounds].size.width)/((float)[theData count]+1e-3);//(maxX - minX);\n float yScale = [self bounds].size.height/(maxT - minT);\n\n [[NSColor whiteColor] set];\n NSRect fillArea = [self bounds];\n [NSBezierPath fillRect:fillArea];\n\n if(dirtyRect.size.height < 100){\n NSLog(@\"small dirtyRect\");\n [[NSColor grayColor] set];\n [NSBezierPath fillRect:dirtyRect];\n }\n dirtyRect = [self bounds];\n\n int dataCount = (int)[theData count];\n\n NSBezierPath *pathForFrame = [[NSBezierPath alloc] init];\n\n NSPoint P0 = {1,1};\n NSPoint P1 = {1, [self bounds].size.height};\n NSPoint P2 = {[self bounds].size.width, 1};\n\n [pathForFrame moveToPoint:P0];\n [pathForFrame lineToPoint:P1];\n [pathForFrame moveToPoint:P0];\n [pathForFrame lineToPoint:P2];\n\n [[NSColor redColor] set];\n [pathForFrame stroke];\n\n NSLog(@\"drawing %i points\", dataCount);\n\n NSBezierPath *pathForPlot = [[NSBezierPath alloc] init];\n if(dataCount1){\n\n NSPoint p1;\n p1.y = [[theData objectAtIndex:0] floatValue];\n p1.x = (0-minX)*xScale;\n p1.y = (p1.y-minT)*yScale;\n [pathForPlot moveToPoint:p1];\n NSLog(@\"point: %0.1f, %0.1f\", p1.x, p1.y);\n }\n for(int i=1; i\n

{val + \" \" + Math.random()}

\n \n \n );\n}\n\nReactDOM.render(, document.querySelector('#mount'));\n\n\n\n
\n\n\nOutput of the above code\nTell me why:\n\n*\n\n*inner and outer reference is different\n\n*useState does not change 2 times but changes a third time\n\n*giveNewRef() increasing value by 2\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/68496796", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Changing the shape of a new assigned variable in Tensorflow if you change a tf.Variable using tf.assign with validate_shape=False the shape is not updated.\nBut if I use set_shape to set the new (correct) shape I get a ValueError.\nHere a quick example:\nimport tensorflow as tf \n\na = tf.Variable([3,3,3])\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n # [3 3 3]\n print(sess.run(a))\n\n sess.run(tf.assign(a, [4,4,4,4], validate_shape=False))\n # [4 4 4 4]\n print(sess.run(a))\n\n# (3,)\nprint(a.get_shape())\n\n# ValueError: Dimension 0 in both shapes must be equal, but are 3 and 4. Shapes are [3] and [4].\na.set_shape([4])\n\nHow do I change the shape of the Variable?\nNote: I am aware that the code works if I use a = tf.Variable([3,3,3], validate_shape=False) but in my context I will not be able to initialize the variable myself.\n\nA: Tell the static part of the graph that the shape is unknown from the start as well.\na = tf.Variable([3,3,3], validate_shape=False)\n\nNow, to get the shape, you cannot know statically, so you have to ask the session, which makes perfect sense:\nprint(sess.run(tf.shape(a)))\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/53611227", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: How to remove backup logs on application startup I have a RotatingFileHandler with mode=w, maxBytes=20000000 and backupCount=10 as shown below: \n[loggers]\nkeys=root\n\n[logger_root]\nlevel=INFO\nhandlers=file\n\n\n[formatters]\nkeys=simple\n\n[formatter_simple]\nformat=[%(levelname)s] %(asctime)s : %(name)s - %(message)s\ndatefmt=%H:%M:%s\n\n[handlers]\nkeys=file\n\n[handler_file]\nclass=handlers.RotatingFileHandler\nformatter=simple\nlevel=INFO\nargs=(log_directory,'w', 20000000, 10)\n\nThis means that after a period of time, 11 distinct log files will be present ( test.log, test.log.1, ..., test.log.10 ). My requirement is when the application is started, I want to delete all of the backup log files (test.log.1, ..., test.log.10). The content of test.log (current) log file will be removed anyway because mode is set to w. \n\nA: That task is not under logging scope, you should \"manually\" delete them upon application start. Use os or shutil.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/56890049", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to debug Spring Cloud Kubernetes Configuration Watcher when it is not working as expectted There are two components in my k8s namespace.\n\n*\n\n*The first component is a simple Spring Boot Web Service with actuator/refresh endpoint exposed. I have mannualy make post request to the endpoint and it will trigger a configuration context refresh succesfully.\n\n\n*The second component is Spring Cloud Kubernetes Configuration Watcher which I pull the image per official document guidance and make it run in my k8s env. Per official spring document, it should detect the changes on configmap with label spring.cloud.kubernetes.config=\"true\" and make post request to the actuator/refresh endpoint of the application whose spring.application.name is equal to the configmap name.\nThe second component is not working as expectted, and I don't know how to trouble shoot the root cause.\nMy Springboot application is called spring-boot-demo, the configmap is also named as spring-boot-demo. But I never find any mentions of \"spring-boot-demo\" in Spring Cloud Kubernetes Configuration Watcher's log and nor can I assure if it has sent post request to related endpoint.\nI can only see the logs showed up repeatedly below:\n2021-11-22 02:58:53.332 INFO 1 --- [192.168.0.1/...] .w.HttpBasedConfigMapWatchChangeDetector : Added new Kubernetes watch: config-maps-watch-event\n2021-11-22 02:58:53.332 INFO 1 --- [192.168.0.1/...] .w.HttpBasedConfigMapWatchChangeDetector : Kubernetes event-based configMap change detector activated\n2021-11-22 03:34:06.555 WARN 1 --- [192.168.0.1/...] .f.c.r.EventBasedConfigMapChangeDetector : ConfigMaps watch closed\n\nio.fabric8.kubernetes.client.WatcherException: too old resource version: 5491278743 (5554041906)\n at io.fabric8.kubernetes.client.dsl.internal.AbstractWatchManager.onStatus(AbstractWatchManager.java:263) [kubernetes-client-5.5.0.jar:na]\n at io.fabric8.kubernetes.client.dsl.internal.AbstractWatchManager.onMessage(AbstractWatchManager.java:247) [kubernetes-client-5.5.0.jar:na]\n at io.fabric8.kubernetes.client.dsl.internal.WatcherWebSocketListener.onMessage(WatcherWebSocketListener.java:93) [kubernetes-client-5.5.0.jar:na]\n at okhttp3.internal.ws.RealWebSocket.onReadMessage(RealWebSocket.java:322) [okhttp-3.14.9.jar:na]\n at okhttp3.internal.ws.WebSocketReader.readMessageFrame(WebSocketReader.java:219) [okhttp-3.14.9.jar:na]\n at okhttp3.internal.ws.WebSocketReader.processNextFrame(WebSocketReader.java:105) [okhttp-3.14.9.jar:na]\n at okhttp3.internal.ws.RealWebSocket.loopReader(RealWebSocket.java:273) [okhttp-3.14.9.jar:na]\n at okhttp3.internal.ws.RealWebSocket$1.onResponse(RealWebSocket.java:209) [okhttp-3.14.9.jar:na]\n at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174) [okhttp-3.14.9.jar:na]\n at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) [okhttp-3.14.9.jar:na]\n at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_312]\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_312]\n at java.lang.Thread.run(Thread.java:748) [na:1.8.0_312]\nCaused by: io.fabric8.kubernetes.client.KubernetesClientException: too old resource version: 5491278743 (5554041906)\n ... 13 common frames omitted\n\n2021-11-22 03:34:06.605 INFO 1 --- [192.168.0.1/...] .f.c.r.EventBasedConfigMapChangeDetector : Added new Kubernetes watch: config-maps-watch-event\n2021-11-22 03:34:06.605 INFO 1 --- [192.168.0.1/...] .f.c.r.EventBasedConfigMapChangeDetector : Kubernetes event-based configMap change detector activated\n2021-11-22 03:34:06.607 INFO 1 --- [192.168.0.1/...] s.c.k.f.c.Fabric8ConfigMapPropertySource : Loading ConfigMap with name 'spring-cloud-kubernetes-configuration-watcher' in namespace 'my-namespace'\n2021-11-22 03:34:06.621 WARN 1 --- [192.168.0.1/...] o.s.c.k.f.config.Fabric8ConfigUtils : config-map with name : 'spring-cloud-kubernetes-configuration-watcher' not present in namespace : 'my-namespace'\n2021-11-22 03:34:06.625 WARN 1 --- [192.168.0.1/...] o.s.c.k.f.config.Fabric8ConfigUtils : config-map with name : 'spring-cloud-kubernetes-configuration-watcher-kubernetes' not present in namespace : 'my-namespace'\n\nThe docker image I use is springcloud/spring-cloud-kubernetes-configuration-watcher:2.1.0-RC1\nAny hint to debug this issue is appreciated.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/70061702", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: CSS mobile devices and hamburger menu I have designed a website that uses a CSS hamburger menu to activate a slidebar with a links to different webpages on the site. \nI also have written an iPhone/andriod apps that need to have an hamburger menu that open a slider work that run swift and android code.\nI want to add to the iphone/android hamburger slidebar links to the website (which has it own hamburger menu)\nHow can I test on the website if it a mobile device or a PC, so I can turn off if \"Website\" hamburger if its a mobile, since I already have and need the hamburger menu on the mobile.\nI have php on the website so I can remove the hamburger menu on the website if its a mobile.\nThis is the main page\n\n\n\n
\n\nLink 1\nLink 2\nLink 3\n
\n\n\n\n\n\n\n
\n
\n\n
\n

My Page

\n
\n\nThanks \n\nA: so there are a few ways of doing this, but a really simple one is something like this:\nvar width = $(window).width(); //jquery\nvar width = window.innerWidth; //javascript\n\nif(width > 1000){do large screen width display)\nelse{handle small screen}\n\nof course 1000 is just an arbitrary number. it gets tricky because when you consider tables, there really are screens of all sizes so its up to you to determine what belongs where\n\nA: \nHow can I test on the website if it a mobile device or a PC, so I can\n turn off if \"Website\" hamburger if its a mobile,\n\nIf I understood you correctly, you could use CSS @media -rules, to setup CSS rules that only apply to smaller devices. Below is a simple code-snippet example of a CSS media-query.\n@media (min-width: 700px), handheld\n{\n .w3-sidebar\n {\n display: none;\n }\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/45897302", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: 'i' symbol in TeX Consider:\n\nI would like to know the LaTeX command for the symbol above. I searched for it online and tried Detexify, but I could not find it.\n\nA: \\documentclass{article}\n\\usepackage{bbm}\n\\begin{document}\n$\\mathbbm{i}$\n\\end{document}\n\n\nOne drawback, of course is that the bbm fonts are bitmapped. There is a scalable alternative with the STIX fonts, but it looks slightly different.\n\\documentclass[border=10]{standalone}\n\\usepackage{amsmath}\n\n\\DeclareFontEncoding{LS1}{}{}\n\\DeclareFontSubstitution{LS1}{stix}{m}{n}\n\n\\newcommand{\\bbi}{\\text{\\usefont{LS1}{stixbb}{m}{n}i}}\n\n\\begin{document}\n\n$\\bbi$\n\\end{document}\n\n\n\nA: There is Unicode character U+1D55A (MATHEMATICAL DOUBLE-STRUCK SMALL I). If you\nuse a TeX-engine that allows you to use arbitrary fonts (like LuaLaTeX) and have a font that supports the glyph, you could use directly, as it were.\n\nA: If you have the option to use unicode math, you can also use \\Bbbi (U+1D55A) or \\mitBbbi (U+02148) for the italic one (Thanks to Ingmar who pointed this out). Below you see the result in some of the commonly used fonts. If the font does not have it a question mark is shown.\n\n", "meta": {"language": "en", "url": "https://tex.stackexchange.com/questions/641490", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "7"}} {"text": "Q: NativeScript Typescript: JSON Array to Typescript Typed Array I need your help, I'm learning NativeScript, here I read the txt file which has JSON data below output. After I fetch them I want to assign it to Array countries. But no luck :(\npublic countries: Array\nconsole.log(response)\nconsole.log(JSON.parse(JSON.stringify(response)))\nOutput:\n[\n {\n \"name\": \"Afghanistan\",\n \"code\": \"AF\"\n },\n {\n \"name\": \"Albania\",\n \"code\": \"AL\"\n }\n]\nPlease help.\nRegards,\n\nA: This is an Array:\n[ { \"name\": \"Afghanistan\", \"code\": \"AF\" }, { \"name\": \"Albania\", \"code\": \"AL\" } ] \nYou need to convert it to a Array, Example:\nresult.forEach((e) => { countries.push(new Country(e.name, e.code))\nThat, or you can change the return of the function that reads the txt to Array\n\nA: finally got it via below code...\n let elements: Array = JSON.parse(JSON.stringify(response))\n .map((item:Country) => \n {\n console.log(item.name + ' < - >' + item.code);\n })\n\nThanks All :)\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/43926540", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Condition for differentiable functional - Why is it defined in this exact way? I'm kind of struggling to understand, why the condition\n\n$$J\\left[y+h\\right]-J\\left[y\\right] = \\Psi \\left[h\\right]+\\varepsilon\n \\left(h\\right){\\lVert}h{\\rVert} $$\nwhere $\\Psi$ is a linear functional, and $\\varepsilon(h)$ is a\nfunctional such that $\\varepsilon(h) \\rightarrow 0 $ for\n${\\lVert}h{\\rVert} \\rightarrow 0$\n\nis the condition to check if we want to know if our given functional $J\\left[\\cdot \\right]$ is differentiable or not.\nShould we divide both sides by $\\varepsilon(h)$, and take the limit ${\\lVert}h{\\rVert} \\rightarrow 0$, and see what happens?\nAlso, I know, that if $\\varepsilon(h) \\rightarrow 0 $ for ${\\lVert}h{\\rVert} \\rightarrow 0$, then $\\varepsilon(h)$ is a continuous functional - but why? Shouldn't continuity be checked by taking the difference ${\\lVert}\\varepsilon(f_n) - \\varepsilon (f){\\rVert}$ and checking if it's $\\rightarrow 0$ for ${\\lVert}f_n - f{\\rVert} \\rightarrow 0$?\n\nA: apping \u03a8; typically denoted as DJy or dJy or in the calculus of variations, \u03b4Jy, or simply \u03b4J. Calculating \u03a8 means figuring out what is \u03a8(h) for all possible h. One possible way of doing to is that \u03a8(h)=DJy(h) (the Frechet derivative of J at h) and by the chain rule, this is equal to dds\u2223\u2223\u2223s=0J(y+sh)=lims\u21920J(y+sh)\u2212J(y)s. i.e \u03a8(h)=DJy(h)=dds\u2223\u2223\u2223s=0J(y+sh)=lims\u21920J(y+sh)\u2212J(y\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/4273866", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: jquery array confusion I have a web page with a bunch of tables decorated with the datatable jquery plugin. When the page is loaded, they're hidden. Then I have a function that toggles them based on the index:\nfunction expand_job(i) {\n $(\".dataTables_wrapper\")[i].show();\n}\n\nBut it didn't work. Browser complains that show() is not a function. As a work around, I'm doing something like this:\nfunction expand_job(i) {\n $(\".dataTables_wrapper\").each( function(idx) {\n if ( i == idx ) {\n $(this).slideToggle(300);\n }\n });\n}\n\nThat works fine but it's..... I just can't let this go. \nSo why did the first piece of code not work? Is it because [i] takes an jquery object into and normal JS object and as a result lost the jquery functionality?\nThanks,\n\nA: Use .eq():\n$(\".dataTables_wrapper\").eq(i).show();\n\njQuery arrays contain the underlying DOM elements at each index, so when you access them the DOM functions are available but not the jQuery methods. \n\nA: $(\".dataTables_wrapper\")[i]\n\nreturns a std java script object, not a jQuery object so you could:\n$($(\".dataTables_wrapper\")[i]).show()\n\nor use nth child or similar\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/6787741", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: How can I know whether my port is blocked by firewall or engaged with some other service I want to know whether the below 3388 port is blocked by firewall or it is engaged with some other services.\nCould you please suggest on this.\nMicrosoft Windows XP [Version 5.1.2600]\n(C) Copyright 1985-2001 Microsoft Corp.\n\nD:\\Documents and Settings\\32323>telnet xfjdd.og.com 3388\nConnecting To xfjdd.og.com...Could not open connection to the\nhost, on port 3388: Connect failed\n\nD:\\Documents and Settings\\32323>\n\n\nA: By no means a hard and fast rule but, typically, if it sits on the 'Connecting to...' message for a short while, it is blocked by the firewall; while if it instantly goes past that and says 'Connect failed', the server has actively decided not to respond (either because the port is not open, or the service rejects your initial connection).\nAn old Windows command-line app called PortQry (http://support.microsoft.com/kb/310099) used to do the job quite nicely, with a FILTERED response for blocked by firewall and a NOT LISTENING response for server rejection.\nOtherwise, you should familiarise yourself with Nmap (http://nmap.org/); it uses FILTERED when blocked by a firewall and CLOSED when the server rejects.\n", "meta": {"language": "en", "url": "https://serverfault.com/questions/417779", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}} {"text": "Q: redux differentiation with context api My understanding is that React's Context API was essentially introduced for quick and dirty global state management, particularly before Redux Toolkit was introduced to simplify the overhead of implementing Redux.\nMy understanding is that one of the main downsides of Context API is that it any update to any property on it will re-render all component fields which are bound to Context API (full re-render).\nI recently explained that downside to someone and he asked why that wouldn't be the case with Redux. He said Redux uses the Context API under the covers which appears to be the case based on some googling:\nhttps://react-redux.js.org/using-react-redux/accessing-store#:~:text=Internally%2C%20React%20Redux%20uses%20React's,object%20instance%20generated%20by%20React.\nA few questions:\n1 - Can you confirm that Context API does a full component re-render when any state value is changed on it?\n2 - Can you confirm that Redux uses Context API under the covers? And can you confirm if Redux Toolkit still uses Context API under the covers?\n3 - I was under the impression that Context API was introduced to be a simpler alternative to tools like Redux. But if Redux uses Context API then did Context API come first but maybe it wasn't exposed directly to the developer?\n4 - If Redux does use Context API under the covers then can you provide any insight into how Redux avoids a full component re-render? I would assume that there's somevtype of mapping layer but I'd be interested to get some more insight into the specific implementation details\n\nA: \nMy understanding is that React's Context API was essentially introduced for quick and dirty global state management\n\nThat's a common misunderstanding. Context is not a state management system, any more than props is a state management system. Context (like props) is a way to get data from one component to another. The difference is that props always passes the data to direct children, while context makes the data available to whichever random components in a subtree are interested.\n\nMy understanding is that one of the main downsides of Context API is that it any update to any property on it will re-render all component fields which are bound to Context API (full re-render).\n\nThis is true. Similarly, if you change props, the component that receives those props must rerender\n\n1 - Can you confirm that Context API does a full component re-render when any state value is changed on it?\n\nOf the specific components that are listening to that context, yes.\n\n2 - Can you confirm that Redux uses Context API under the covers? And can you confirm if Redux Toolkit still uses Context API under the covers?\n\nReact-redux does use context, yes. Pure redux and redux toolkit don't, since they're general purpose libraries not directly related to react, but I think you meant react-redux.\nThat that you must render at the top of a react-redux app is there to provide a context to the components underneath it. Components that call hooks like useSelector or useDispatch then use the context to find the store that they should interact with.\n\n3 - I was under the impression that Context API was introduced to be a simpler alternative to tools like Redux. But if Redux uses Context API then did Context API come first but maybe it wasn't exposed directly to the developer?\n\nContext has existed for a long time, but it used to be an unofficial feature. They've also made it easier to use over time.\n\n4 - If Redux does use Context API under the covers then can you provide any insight into how Redux avoids a full component re-render?\n\nThe context is only providing a minimal amount of things to the child components, most importantly the store object. The reference to the store object does not typically change, so since the context value does not change, the child components do not need to render. To see exactly what it's providing, see this code: https://github.com/reduxjs/react-redux/blob/master/src/components/Provider.tsx#L33\nThe contents of the store does change, but that's not what the context is providing. To get the contents of the store, the individual components subscribe to the store, using redux's store.subscribe, plus a special hook called useSyncExternalStore. Basically, redux fires an event when the store's state is updated, and then the individual components set their own local state if it's a change they care about. This local state change is what causes the rerender.\n\nIf you're writing code that uses context, you're rarely going to be doing things fancy enough to require useSyncExternalStore or a custom subscription system. So the main things you'll want to keep in mind are:\n\n*\n\n*Keep the context focused on a single task. For example, if you have a theme object to control your app's colors, and also a user object which describes who is currently logged in, put these in different contexts. That way a component that just cares about the theme doesn't need to rerender when the user changes, and vice versa.\n\n\n*If your context value is an object, memoize it so it's not changing on every render (see this documentation)\n\nA: I'm a Redux maintainer. @NicholasTower gave a great answer, but to give some more details:\nContext and Redux are very different tools that solve different problems, with some overlap.\nContext is not a \"state management\" tool. It's a Dependency Injection mechanism, whose only purpose is to make a single value accessible to a nested tree of React components. It's up to you to decide what that value is, and how it's created. Typically, that's done using data from React component state, ie, useState and useReducer. So, you're actually doing all the \"state management\" yourself - Context just gives you a way to pass it down the tree.\nRedux is a library and a pattern for separating your state update logic from the rest of your app, and making it easy to trace when/where/why/how your state has changed. It also gives your whole app the ability to access any piece of state in any component.\nIn addition, there are some distinct differences between how Context and (React-)Redux pass along updates. Context has some major perf limitations - in particular, any component that consumes a context will be forced to re-render, even if it only cares about part of the context value.\nContext is a great tool by itself, and I use it frequently in my own apps. But, Context doesn't \"replace Redux\". Sure, you can use both of them to pass data down, but they're not the same thing. It's like asking \"Can I replace a hammer with a screwdriver?\". No, they're different tools, and you use them to solve different problems.\nBecause this is such a common question, I wrote an extensive post detailing the differences:\nWhy React Context is Not a \"State Management\" Tool (and Why It Doesn't Replace Redux)\nTo answer your questions specifically:\n\n*\n\n*Yes, updating a Context value forces all components consuming that context to re-render... but there's actually a good chance that they would be re-rendering anyway because React renders recursively by default, and setting state in a parent component causes all components inside of that parent to re-render unless you specifically try to avoid it. See my post A (Mostly) Complete Guide to React Rendering Behavior, which explains how all this works.\n\n*Yes, React-Redux does use Context internally... but only to pass down the Redux store instance, and not the current state value. This leads to very different update characteristics. Redux Toolkit, on the other hand, is just about the Redux logic and not related to any UI framework specifically.\n\n*Context was not introduced to be an alternative to Redux. There was a \"legacy Context\" API that existed in React well before Redux itself was created, and React-Redux used that up through v5. However, that legacy context API was broken in some key ways. The current React Context API was introduced in React 16.3 to fix the problems in legacy Context, not specifically to replace Redux.\n\n*React-Redux uses store subscriptions and selectors in each component instance, which is a completely different mechanism than how Context operates.\n\nI'd definitely suggest reading the posts I linked above, as well as these other related posts:\n\n*\n\n*Redux - Not Dead Yet!\n\n*When (and when not) to Reach for Redux\n\n*React, Redux, and Context Behavior.\n\n\nA: Original blog post by Mark Erikson:\nI'll just copy paste some info, but here's the original source and I recommend going directly here: https://blog.isquaredsoftware.com/2020/01/blogged-answers-react-redux-and-context-behavior/\nMore links here:\n\n*\n\n*https://github.com/markerikson/react-redux-links\n\n*https://blog.isquaredsoftware.com/2018/11/react-redux-history-implementation/\n\n*https://medium.com/async/how-useselector-can-trigger-an-update-only-when-we-want-it-to-a8d92306f559\nAn explanation of how React Context behaves, and how React-Redux uses Context internally\nThere's a couple assumptions that I've seen pop up repeatedly:\n\n*\n\n*React-Redux is \"just a wrapper around React context\"\n\n*You can avoid re-renders caused by React context if you destructure the context value\n\nBoth of these assumptions are incorrect, and I want to clarify how they actually work so that you can avoid mis-using them in the future.\nFor context behavior, say we have this initial setup:\nfunction ProviderComponent() {\n const [contextValue, setContextValue] = useState({a: 1, b: 2});\n\n return (\n \n \n \n )\n}\n\nfunction ChildComponent() {\n const {a} = useContext(MyContext);\n return
{a}
\n}\n\nIf the ProviderComponent were to then call setContextValue({a: 1, b: 3}), the ChildComponent would re-render, even though it only cares about the a field based on destructuring. It also doesn't matter how many levels of hooks are wrapping that useContext(MyContext) call. A new reference was passed into the provider, so all consumers will re-render. In fact, if I were to explicitly re-render with , ChildComponent would still re-render because a new object reference has been passed into the provider! (Note that this is why you should never pass object literals directly into context providers, but rather either keep the data in state or memoize the creation of the context value.)\nFor React-Redux: yes, it uses context internally, but only to pass the Redux store instance down to child components - it doesn't pass the store state using context!. If you look at the actual implementation, it's roughly this but with more complexity:\nfunction useSelector(selector) {\n const [, forceRender] = useReducer( counter => counter + 1, 0);\n const {store} = useContext(ReactReduxContext);\n \n const selectedValueRef = useRef(selector(store.getState()));\n\n useLayoutEffect(() => {\n const unsubscribe = store.subscribe(() => {\n const storeState = store.getState();\n const latestSelectedValue = selector(storeState);\n\n if(latestSelectedValue !== selectedValueRef.current) {\n selectedValueRef.current = latestSelectedValue;\n forceRender();\n }\n })\n \n return unsubscribe;\n }, [store])\n\n return selectedValueRef.current;\n}\n\nSo, React-Redux only uses context to pass the store itself down, and then uses store.subscribe() to be notified when the store state has changed. This results in very different performance behavior than using context to pass data.\nThere was an extensive discussion of context behavior in React issue #14110: Provide more ways to bail out of hooks. In that thread, Sebastian Markbage specifically said:\n\nMy personal summary is that new context is ready to be used for low frequency unlikely updates (like locale/theme). It's also good to use it in the same way as old context was used. I.e. for static values and then propagate updates through subscriptions. It's not ready to be used as a replacement for all Flux-like state propagation.\n\nIn fact, we did try to pass the store state in context in React-Redux v6, and it turned out to be insufficiently performant for our needs, which is why we had to rewrite the internal implementation to use direct subscriptions again in React-Redux v7.\nFor complete detail on how React-Redux actually works, read my post The History and Implementation of React-Redux, which covers the changes to the internal implementation over time, and how we actually use context.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/75498437", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: ThreadPoolTaskExecutor giving ConnectionPoolTimeOutException Getting this error even though the total count of active thread is less than the corepoolsize.\nThreadPool which I have created :\nThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();\n executor.setCorePoolSize(1500);\n executor.setMaxPoolSize(2000);\n executor.setQueueCapacity(500);\n executor.setThreadNamePrefix(\"MakeShoppingRequest\");\n executor.setKeepAliveSeconds(10);\n executor.setAllowCoreThreadTimeOut(true);\n executor.initialize();\n\nException:\n**org.springframework.ws.client.WebServiceIOException: I/O error: Timeout waiting for connection from pool; nested exception is org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool**\n at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:561)\n at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390)\n at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:383)\n at jdk.internal.reflect.GeneratedMethodAccessor66.invoke(Unknown Source)\n at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.base/java.lang.reflect.Method.invoke(Method.java:566)\n at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)\n at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)\n at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)\n at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115)\n at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)\n at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)\n at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)\n at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)\n at java.base/java.lang.Thread.run(Thread.java:834)\nCaused by: org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool\n at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.leaseConnection(PoolingHttpClientConnectionManager.java:316)\n at org.apache.http.impl.conn.PoolingHttpClientConnectionManager$1.get(PoolingHttpClientConnectionManager.java:282)\n at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:190)\n at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)\n at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)\n at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)\n at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)\n at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)\n at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)\n at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)\n at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)\n at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:66)\n at org.springframework.ws.transport.http.ClientHttpRequestConnection.onSendAfterWrite(ClientHttpRequestConnection.java:83)\n at org.springframework.ws.transport.AbstractWebServiceConnection.send(AbstractWebServiceConnection.java:48)\n at org.springframework.ws.client.core.WebServiceTemplate.sendRequest(WebServiceTemplate.java:658)\n at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:606)\n at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)\n ... 15 more\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/66383729", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: What does the standard claim that detecting a closed universe would rule out the multiverse mean? The new article \"Lorentzian Vacuum Transitions: Open or Closed Universes?\" On page 41 reads:\n\"We believe that the possibility that the geometry of the bubble after nucleation corresponds to a closed FLRW universe, contrary to CDL, should be seriously considered. Indeed this is the natural implication of brane nucleation in string theory as we have argued in this paper. This may have important physical implications if our universe is described in terms of a bubble after vacuum transitions as discussed at the end of the previous section Besides the deep implications of having a finite against an infinite universe, with finite number of stars and galaxies, it may eventually be tested if there is a definite way of determining the curvature of the universe. For the string theory landscape, it will at least eliminate the standard claim that detecting a closed universe would rule out the multiverse. These are important cosmological questions that deserve further scrutiny \".\nWhat does the standard claim that detecting a closed universe would rule out the multiverse mean? If cosmologists find that the universe is closed and finite, would that rule out the existence of the multiverse and other universes?\nArticle link: https://arxiv.org/abs/2011.13936\n\nA: I've not read the full paper you listed there (and it definitely doesn't look like a quick read), but the following passage by Ellis seems most relevant:\n\nThe multiverse idea is testable, because it can\nbe disproved if we determine there are closed\nspatial sections in the universe (for example, if\nthe curvature is positive).\n\n\nThe claim [above] is that only negatively curved FRW\nmodels can exist in a multiverse based on chaotic inflation, either because Coleman\u2013de Luccia tunnelling only gives negative curvature\nor because a closed spatial section necessarily\nimplies a single universe. But the first argument\nis disputed (there are already papers suggesting\nthat tunnelling to positively curved universes is\npossible) and the second argument would not\napply if we lived in a high-density lump imbedded in a low-density universe (i.e. the extrapolation of positive curvature to very large scales\nmay not be valid)\n\ntaken from the article Universe or Multiverse, (bullet point 3), the whole of which may be worthwhile reading. As said in the quote, he's referring to a multiverse in the context of chaotic inflation, but within the article he makes reference to the string landscape, though I don't think I'll do it justice by picking out any more quotes.\nFrom what I gather, the quote from your paper is saying that, the claim: a closed universe is inconsistent with a multiverse scenario, is no longer correct. Ellis also seems to be saying the same thing, except making the point that this implies the multiverse is not testable. Different arguments based on the same core idea. The reason why the claim does not apparently hold anymore is listed in my long quote from Ellis above (and references can be found therein that are more technical).\nRelated article: https://academic.oup.com/astrogeo/article-pdf/49/2/2.33/683010/49-2-2.33.pdf\n", "meta": {"language": "en", "url": "https://physics.stackexchange.com/questions/602615", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Is it necessary to hash REST API tokens? So I have a REST API and some socket APIs which use a common token validation module. Here are the things that the token module does:\nfunction tokenManager() {\n this.generate = (db, userId, cacheManager) => {\n /*Generates a token for a user and stores it in a db, also puts it in a cache as token: userId key- \n value pair.*/\n }\n\n this.verify = async (db, token, cacheManager) => {\n /*Checks the cache if a user is present for the given token and returns the user id. If the token was \n not found in cache, it verifies it from database and puts it in cache.*/\n\n //Each time for a successful verification, the token validity is increased by one day.\n }\n}\n\nThis approach works well, however the tokens are stored in database as plain text. If someone gains access to the database they could get the tokens and make API calls, although rate limiting is present, there is some data compromised. I was planning to hash the API tokens and store them, but a hash compare has to be done on literally every request putting extra computation load on server. (especially bad for node). Is there a better way to implement this? Or is it even necessary to hash API tokens?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/64403682", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: iOS Firebase ML Kit Simple Audio Recognition \"Failed to create a TFLite interpreter for the given model\" I have been trying to implement the Simple Audio Recognition Tensorflow sample in iOS using the Firebase's ML kit. I have successfully trained the model and converted it into a TFlite file. The model takes the Audio(wav) file path as input([String]) and gives the predictions as output(float32). My iOS code is fairly simple\nfunc initMLModel(){\n\n /*Initializing local TFLite model*/\n guard let modelPath = Bundle.main.path(forResource: \"converted_model\", ofType: \"tflite\") else {\n return\n }\n\n let myLocalModel = LocalModelSource.init(modelName: \"My\", path: modelPath)\n let registrationSuccessful = ModelManager.modelManager().register(myLocalModel)\n\n let options = ModelOptions(cloudModelName: nil, localModelName: \"My\")\n\n let interpreter = ModelInterpreter.modelInterpreter(options: options)\n\n let ioOptions = ModelInputOutputOptions()\n do {\n try ioOptions.setInputFormat(index: 0, type: .unknown, dimensions: []) /*input is string path. Since string is not defined, setting it as unknown.*/\n try ioOptions.setOutputFormat(index: 0, type: .float32, dimensions: [1,38]) /* output is 1 of 38 labelled classes*/\n } catch let error as NSError {\n print(\"Failed to set IO \\(error.debugDescription)\")\n }\n\n let inputs = ModelInputs()\n var audioData = Data()\n\n let audiopath = Bundle.main.path(forResource: \"audio\", ofType: \"wav\")\n do {\n audioData = try Data.init(contentsOf: URL.init(fileURLWithPath: audiopath!))\n //try inputs.addInput(audioData) /*If the input type is direct audio data*/\n try inputs.addInput([audiopath])\n } catch let error as NSError {\n print(\"Cannot get audio file data \\(error.debugDescription)\")\n return\n }\n\n interpreter.run(inputs: inputs, options: ioOptions) { (outputs, error) in\n if error != nil {\n print(\"Error running the model \\(error.debugDescription)\")\n return\n }\n do {\n let output = try outputs!.output(index: 0) as? [[NSNumber]]\n let probabilities = output?[0]\n\n guard let labelsPath = Bundle.main.path(forResource: \"conv_labels\", ofType: \"txt\") else { return }\n let fileContents = try? String.init(contentsOf: URL.init(fileURLWithPath: labelsPath))\n guard let labels = fileContents?.components(separatedBy: \"\\n\") else {return}\n\n for i in 0 ..< labels.count {\n if let probability = probabilities?[i] {\n print(\"\\(labels[i]) : \\(probability)\")\n }\n }\n\n }catch let error as NSError {\n print(\"Error in parsing the Output \\(error.debugDescription)\")\n return\n }\n }\n }\n\nBut when i run this i get the following error output Failed to create a TFLite interpreter for the given model. The Complete Log of the sample app is as below\n 2019-01-07 18:22:31.447917+0530 sample_core_ML[67500:3515789] - [I-ACS036002] Analytics screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable screen reporting, set the flag FirebaseScreenReportingEnabled to NO (boolean) in the Info.plist\n 2019-01-07 18:22:33.354449+0530 sample_core_ML[67500:3515686] libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform.\n 2019-01-07 18:22:34.789665+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/Analytics][I-ACS023007] Analytics v.50400000 started\n 2019-01-07 18:22:34.790814+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see )\n 2019-01-07 18:22:35.542993+0530 sample_core_ML[67500:3515823] [BoringSSL] nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x7f9db0701d70] get output frames failed, state 8196\n 2019-01-07 18:22:35.543205+0530 sample_core_ML[67500:3515823] [BoringSSL] nw_protocol_boringssl_get_output_frames(1301) [C1.1:2][0x7f9db0701d70] get output frames failed, state 8196\n 2019-01-07 18:22:35.543923+0530 sample_core_ML[67500:3515823] TIC Read Status [1:0x0]: 1:57\n 2019-01-07 18:22:35.544070+0530 sample_core_ML[67500:3515823] TIC Read Status [1:0x0]: 1:57\n 2019-01-07 18:22:39.981492+0530 sample_core_ML[67500:3515823] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Didn't find custom op for name 'DecodeWav' with version 1\n 2019-01-07 18:22:39.981686+0530 sample_core_ML[67500:3515823] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Registration failed.\n Failed to set IO Error Domain=com.firebase.ml Code=3 \"input format 0 has invalid nil or empty dimensions.\" UserInfo={NSLocalizedDescription=input format 0 has invalid nil or empty dimensions.}\n 2019-01-07 18:22:40.604961+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Didn't find custom op for name 'DecodeWav' with version 1\n 2019-01-07 18:22:40.605199+0530 sample_core_ML[67500:3515812] 5.15.0 - [Firebase/MLKit][I-MLK002000] ModelInterpreterErrorReporter: Registration failed.\n Error running the model Optional(Error Domain=com.firebase.ml Code=2 \"Failed to create a TFLite interpreter for the given model (/Users/minimaci73/Library/Developer/CoreSimulator/Devices/7FE413C1-3820-496A-B0CE-033BE2F3212A/data/Containers/Bundle/Application/868CB2FE-77D8-4B1F-8853-C2E17ECA63F2/sample_core_ML.app/converted_model.tflite).\" UserInfo={NSLocalizedDescription=Failed to create a TFLite interpreter for the given model (/Users/minimaci73/Library/Developer/CoreSimulator/Devices/7FE413C1-3820-496A-B0CE-033BE2F3212A/data/Containers/Bundle/Application/868CB2FE-77D8-4B1F-8853-C2E17ECA63F2/sample_core_ML.app/converted_model.tflite).})\n\nWhen looked at this line Didn't find custom op for name 'DecodeWav' I looked up on the custom supported ops and found that Tensorflow already supports this in the audio_ops.cc by default.\nDetails\nMy Tensorflow Version : 1.12.0\nEnvironment : Conda\nOS Version : Mac OSX Mojave 10.14.2\nDeployment target : ios 12.0\nInstallation type : Pod Installation (pod 'Firebase/MLModelInterpreter')\nBut i ran my training model first in v1.9.0. Then updated the Tensorflow to latest v1.12.0 to run the TFLite Convertor. Both are master branch.\nMy TFLite Convertor code Python\nimport tensorflow as tf\n\ngraph_def_file = \"my_frozen_graph.pb\"\ninput_arrays = [\"wav_data\"]\noutput_arrays = [\"labels_softmax\"]\ninput_shape = {\"wav_data\" : [1,99,40,1]}\n\nconverter = tf.contrib.lite.TFLiteConverter.from_frozen_graph(\n graph_def_file, input_arrays, output_arrays, input_shape)\nconverter.allow_custom_ops = True\ntflite_model = converter.convert()\nopen(\"converted_model.tflite\", \"wb\").write(tflite_model)\n\n\nA: I posted this same question in the firebase quickstart iOS repository, And i got the following response DecodeWav op is never supported by TensorFlowLite. So at present Tensorflow Lite does not support audio processing even-though Tensorflow itself supports audio processing.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/54093248", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: HTML link with GET parameters: load page html and javascript before executing ajax request When I paste the HTML link below in my address bar or press the browser \"previous page\" button my ajax GET request is executed before the html content is fully loaded resulting in my ajax returned content being displayed above my nav bar and therefore breaking my site. \nIf the same request gets executed from within the site then everything is fine.\nHow can I make sure the page HTML and javascript loads before the ajax request is fired?\nEDIT: SOLVED (answer in post below)\nHTML LINK\nhttps://domainName/?action=listy&p=test\nJS pushstate\nvar container = document.querySelector('.lnk');\nvar url = \"\";\n\ncontainer.addEventListener('click', function(e) {\n if (e.target != e.currentTarget) {\n e.preventDefault();\n\n if (e.target.getAttribute('name')) {\n var data = e.target.getAttribute('name')\n url = \"?action=list&p=\" + data;\n history.pushState(data, null, url);\n }\n\n }\n e.stopPropagation();\n}, false);\n\n\nwindow.addEventListener('popstate', function(e) {\n\n window.location.replace(url);\n\n});\n\nJQuery AJAX\n$(document).ready(function() {\n // .....\n success: function(dataBack) {\n $('.content-area').html(dataBack);\n },\n});\n\nPHP\nif(isset($_GET['action']) && !empty($_GET['action'])) {\n$action = $_GET['action'];\n$var = $_GET['p'];\nswitch($action) {\n\n case 'list' : list($var);break;\n\n\n}\n}\n\n\nA: This works for me (Note this uses the jquery library):\n$(document).ready(function () {\n Your code here...\n});\n\nThis will wait for the page to load then run the function. I personally use this for animations but then the animations also take more time for me so I have to also include the setTimeout function like this:\nsetTimeout(function () {\n Your code here...\n}, 1000);\n\nIt waits a specific amount of milliseconds before executing the function.\n\nA: Turns out the issue was coming from my index.php structure; \nI moved the php code in separate files and included it at the end of index.php instead of the top. \nNow Im having other issues but the main question is resolved.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/47904530", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Get random ID from DB on button click Hi guys (I'm a beginner so take it easy) I have this code which searches my database and brings up the title / artists and that works fine. I am required to make a button which when clicked it brings up a random ID from my database. I have looked around but can't find anything useful.Trying to come up with a lamda expression or something...\nThanks\nCONTROLLER\npublic ActionResult Play(string searchTitle, string searchArtist, string shuffle)\n{\n var media = from s in db.UploadTables select s;\n\n if (!string.IsNullOrEmpty(searchTitle))\n {\n media = media.Where(m => m.MediaTitle.Contains(searchTitle));\n }\n\n if (!string.IsNullOrEmpty(searchArtist))\n {\n media = media.Where(m => m.MediaArtist.Contains(searchArtist));\n }\n\n return View(media);\n}\n\nVIEW\n@using (Html.BeginForm())\n{\n

\n Song Name: @Html.TextBox(\"searchTitle\") \n \n Artist: @Html.TextBox(\"searchArtist\") \n \n @Html.TextBox(\"shuffle\") \n \n

\n
\n}\n\n\nA: Random rand = new Random();\nint total = db.UploadTables.Count();\nvar randomId = db.UploadTables.Skip(rand.Next(total)).First().Id;\n\nRandom.Next(Int32 maxValue) will get a number between 0 and maxValue-1.\nIQueryable.Skip(this IQueryable, int count) will skip count entries.\nYou then take the First() of the remaining entries and tadaa you can access its Id field.\nObviously, this is only one way to do it, and as told by others, there are many ways to do that.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/51824399", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Is it possible to develop apps for iOS with iPod? I develop games for Android, but now I want to try the iOS platform. Actually, I have Mac Mini, but I haven't enought money to buy iPhone, so I think about buying iPod Touch instead. Is it possible to develop games (Unity engine) using iPod? What about games performance? Sorry if I ask something stupid, I never developed for iOS before, thanks!\n\nA: We use an iTouch for development (cheaper than buying iPad2's). So yes, you can definitely develop for iOS using an iTouch/iPod.\nYou will also need to join the Apple developer program before you can deploy to the iTouch - Apple has a $99 annual fee for an individual. Even if you purchase Unity you will need buy into the Apple dev program too.\n\nA: same code will work in iphone,ipad ,ipod .so no problem.so that the name of IDE is xcode.but performance and image accuracy will be varied.\nhttp://unity3d.com/company/news/iphone-press.html\n\nA: Apple provides a SDK including a simulator. Never trust the simulator completely, but you can use it easily for day by day job, and test it on a real iphone, ipod touch or similar only from time to time.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/6746559", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Django tagging migration to GAE I have a Django app that use a django-tagging. I need to port this application to GAE. So, the main problem is to migrate tagging part. It has a complicated model, that should be rewritten to work with Google store. I think tagging is very popular django app and someone has the same problem before. Has someone a rewritten model?\n\nA: Check Nick's post about tagging blog posts. It covers all main tagging issues.\n\nA: There is a modified django-tagging, probably it might work.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/1643838", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: How to add delay between jquery steps transition (jquery steps plugin) I am using http://www.jquery-steps.com/Examples#advanced-form plugin.\nHow can I add delay between the two steps?\nI have tried adding the timeout function in onStepChanging and onStepChanged but it's not working.\nHere's what my code looks like:\nvar form = $(\"#example-advanced-form\").show();\n\nform.steps({\n headerTag: \"h3\",\n bodyTag: \"fieldset\",\n transitionEffect: \"slideLeft\",\n onStepChanging: function (event, currentIndex, newIndex)\n {\n // Allways allow previous action even if the current form is not valid!\n if (currentIndex > newIndex)\n {\n return true;\n }\n // Forbid next action on \"Warning\" step if the user is to young\n if (newIndex === 3 && Number($(\"#age-2\").val()) < 18)\n {\n return false;\n }\n // Needed in some cases if the user went back (clean up)\n if (currentIndex < newIndex)\n {\n // To remove error styles\n form.find(\".body:eq(\" + newIndex + \") label.error\").remove();\n form.find(\".body:eq(\" + newIndex + \") .error\").removeClass(\"error\");\n }\n form.validate().settings.ignore = \":disabled,:hidden\";\n return form.valid();\n },\n onStepChanged: function (event, currentIndex, priorIndex)\n {\n // Used to skip the \"Warning\" step if the user is old enough.\n if (currentIndex === 2 && Number($(\"#age-2\").val()) >= 18)\n {\n form.steps(\"next\");\n }\n // Used to skip the \"Warning\" step if the user is old enough and wants to the previous step.\n if (currentIndex === 2 && priorIndex === 3)\n {\n form.steps(\"previous\");\n }\n },\n onFinishing: function (event, currentIndex)\n {\n form.validate().settings.ignore = \":disabled\";\n return form.valid();\n },\n onFinished: function (event, currentIndex)\n {\n alert(\"Submitted!\");\n }\n}).validate({\n errorPlacement: function errorPlacement(error, element) { element.before(error); },\n rules: {\n confirm: {\n equalTo: \"#password-2\"\n }\n }\n});\n\n\nA: how about this\nsetTimeout(function(){ /*your function*/ }, 3000);\n\nhttps://www.w3schools.com/JSREF/met_win_setTimeout.asp\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/45648661", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Using Reflection to determine which Fields are backing fields of a Property I'm using reflection to map out objects. These objects are in managed code but I have no visibility into their source code, underlying structure, etc. other than through reflection. The overarching goal of all this is a rudimentary memory map of an object (similar in functionality to SOS.dll DumpObject and !ObjSize commands). As such, I'm trying to determine which members are being \"double counted\" as both a field and a property. \nFor example:\npublic class CalendarEntry\n{\n // private property \n private DateTime date { get; set;}\n\n // public field \n public string day = \"DAY\";\n}\n\nWhen mapped shows:\n\n\n*\n\n*Fields\n\n*\n\n*day\n\n*k__BackingField\n\n\n*Properties\n\n*\n\n*date\n\n\n\nWhere as a class like this:\npublic class CalendarEntry\n{\n // private field \n private DateTime date;\n\n // public field \n public string day = \"DAY\";\n\n // Public property exposes date field safely. \n public DateTime Date\n {\n get\n {\n return date;\n }\n set\n {\n date = value;\n }\n }\n}\n\nWhen mapped shows:\n\n\n*\n\n*Fields\n\n*\n\n*day\n\n*date\n\n\n*Properties\n\n*\n\n*Date\n\n\n\nAt first glance there's nothing to tell you that the Date property's \"backing field\" is the field named date. I'm trying to avoid counting date twice in this scenario since that will give me a bad memory size approximation. \nWhat's more confusing/complicated is I've come across scenarios where properties don't always have a corresponding field that will be listed through the Type.GetFields() method so I can't just ignore all properties completely.\nAny ideas on how to determine if a field in the collection returned from Type.GetFields() is essentially the backing field of some corresponding property returned from Type.GetProperties()?\nEdit- I've had trouble determining what conditions a property will not have a corresponding field in listed in the collection returned from Type.GetFields(). Is anyone familiar with such conditions?\nEdit 2- I found a good example of when a property's backing field would not be included in the collection returned from Type.GetFields(). When looking under the hood of a String you have the following:\n\n\n*\n\n*Object contains Property named FirstChar\n\n*Object contains Property named Chars\n\n*Object contains Property named Length\n\n*Object contains Field named m_stringLength\n\n*Object contains Field named m_firstChar\n\n*Object contains Field named Empty\n\n*Object contains Field named TrimHead\n\n*Object contains Field named TrimTail\n\n*Object contains Field named TrimBoth\n\n*Object contains Field named charPtrAlignConst\n\n*Object contains Field named alignConst\n\n\nThe m_firstChar and m_stringLength are the backing fields of the Properties FirstChar and Length but the actual contents of the string are held in the Chars property. This is an indexed property that can be indexed to return all the chars in the String but I can't find a corresponding field that holds the characters of a string. Any thoughts on why that is? Or how to get the backing field of the indexed property?\n\nA: The name of a property's backing field is a compiler implementation detail and can always change in the future, even if you figure out the pattern.\nI think you've already hit on the answer to your question: ignore all properties.\nRemember that a property is just one or two functions in disguise. A property will only have a compiler generated backing field when specifically requested by the source code. For example, in C#:\npublic string Foo { get; set; }\n\nBut the creator of a class need not use compiler generated properties like this. For example, a property might get a constant value, multiple properties might get/set different portions of a bit field, and so on. In these cases, you wouldn't expect to see a single backing field for each property. It's fine to ignore these properties. Your code won't miss any actual data.\n\nA: You can ignore all properties completely. If a property doesn't have a backing field, then it simply doesn't consume any memory.\nAlso, unless you're willing to (try to) parse CIL, you won't be able to get such mapping. Consider this code:\nprivate DateTime today;\n\npublic DateTime CurrentDay\n{\n get { return today; }\n}\n\nHow do you expect to figure out that there is some relation between the today field and the CurrentDay property?\nEDIT: Regarding your more recent questions:\nIf you have property that contains code like return 2.6;, then the value is not held anywhere, that constant is embedded directly in the code.\nRegarding string: string is handled by CLR in a special way. If you try to decompile its indexer, you'll notice that it's implemented by the CLR. For these few special types (string, array, int, \u2026), you can't find their size by looking at their fields. For all other types, you can.\n\nA: To answer your other question:Under what circumstances do properties not have backing fields? \npublic DateTime CurrentDay\n{\n get { return DateTime.Now; }\n}\n\nor property may use any other number of backing fields/classes\npublic string FullName \n{\n get {return firstName + \" \" + lastName;}\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/14322660", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "13"}} {"text": "Q: \"What' and 'which' difference Which one of the following sentence is grammatical?\n1- What footballer has scored the most number of goals?\n2- Which footballer has scored the most number of goals?\n\nA: Although both are commonly used I would go with\nWhat footballer has scored the most goals? (number of is not required).\nWhy? basically which is used when you are choosing between a small number of alternatives.\nWhich of your friends....\nwhat student from your school...\nwhich\ndeterminer, pronoun\nUK /w\u026at\u0283/ US /w\u026at\u0283/\nwhich determiner, pronoun (QUESTION)\nA1\n(used in questions and structures in which there is a fixed or limited set of answers or possibilities) what one or ones:\nwhat\ndeterminer, pronoun, exclamation\nUK /w\u0252t/ US /w\u0251\u02d0t/\nwhat determiner, pronoun, exclamation (QUESTION)\nA1\nused to ask for information about people or things:\nWhat time is it?\nWhat books did you buy?\nWhat did you wear?\nWhat size shoes do you take?\nWhat happened after I left?\nall ref CED WHAT\n", "meta": {"language": "en", "url": "https://ell.stackexchange.com/questions/277191", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}} {"text": "Q: Como traer datos con php y mysqli pero que sean de los \u00faltimos 7 d\u00edas tengo la siguiente consulta con mysqli que me trae registros de una base de datos:\n\n \n \n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n\n \n
ESTADOFLOTAEQUIPOFECHA SALIDACAMBIOSTRABAJO
\n
\n\nComo puedo hacer para traer solo registros de los \u00faltimos 7 d\u00edas comenzando desde los d\u00edas jueves, ejemplo: la consulta debe traer todos los registros de los \u00faltimos 7 d\u00edas comenzando desde el jueves y cuando termine los 7 d\u00edas vuelve a comenzar desde el d\u00eda jueves pero por supuesto una fecha posterior.\nMe seria de gran utilidad cualquier ayuda que me puedan aportar. muchas gracias.\n\nA: Puedes usar interval en tu consulta MySQL:\nSELECT * FROM `trabajos` WHERE estado_kal='Finalizado'\nAND fecha >= (DATE(NOW()) - INTERVAL 7 DAY)\nORDER BY fecha DESC\n\n", "meta": {"language": "es", "url": "https://es.stackoverflow.com/questions/357561", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Line below link on hover How can I add a short line below link ? The line should be visible only on hover. \nI tried with border-bottom, but that way the line is 100% of the link width and I want the line to be shorter than the link .\nHere is a example image of the effect that I try to make. \n\n\nA: This is something I just thought of, check it out see what you think. So we use :after and create a line under the text. This only works if the parent has a width (for centering).\nHTML:\n
Test
\n\nCSS:\ndiv {\n width: 30px;\n}\ndiv:hover:after {\n content: \"\";\n display: block;\n width: 5px;\n border-bottom: 1px solid;\n margin: 0 auto;\n}\n\nDEMO\n\nUpdated CSS:\ndiv {\n display: inline-block;\n}\n\nNot sure why I didnt think of this but you can just use inline-block to get it to center without the parent having a width.\nDEMO HERE\n\nHere is a link using the same method, just incase you got confused.\nDEMO HERE\n\nSo I have now be told I should even point out the most obvious thing so here is an update just for the people that don't know width can be a percentage.\nwidth: 70%;\n\nChanged the width from 5px to 70% so it will expand with the width of the text.\nDEMO HERE\n\nA: Edit:\nRuddy's solution has the same result and is more elegant so based on that, I used it recently with addition of transition, making it a bit more eye catching and I thought it would be useful to share here:\n a {\n display: inline-block;\n text-decoration:none\n }\n a:after {\n content: \"\";\n display: block;\n width: 0;\n border-bottom: 1px solid;\n margin: 0 auto;\n transition:all 0.3s linear 0s;\n }\n\n a:hover:after {\n width: 90%;\n }\n\njsfiddle link\n(Original answer below)\nCheck this i just came up with, playing in the fiddle:\n I am a link, hover to see\n\n\n a.bordered { \n text-decoration:none;\n position: relative;\n z-index : 1;\n display:inline-block;\n }\n\na.bordered:hover:before {\ncontent : \"\";\nposition: absolute;\nleft : 50%;\nbottom : 0;\nheight : 1px;\nwidth : 80%;\nborder-bottom:1px solid grey;\nmargin-left:-40%;\n}\n\nDepending on the percentages, you may play with a.bordered:hover:before margin and left position.\n\nA: Simply use this class:\n.link:hover {\n background-image:url(\"YOUR-SMALL-LINE-BOTTOM.png\")\n}\n\nlike this, the line will appear when you hover over the element. And you can specify in the image, how small or big the line has to be.\n\nA: Try creating another Div for border. And adjust the width of that div according to your choice. I hope this will help.\n\nA: what about this?\na {text-decoration:none;position:relative;}\na:hover:before {content:\"_\";position:absolute;bottom:-5px;left:50%;width:10px;margin:0 0 0 -5px;}\n\ncheck this fiddle for more: http://jsfiddle.net/h7Xb5/\n\nA: You can try using ::after pseudo element:\n\n\na {\r\n position: relative;\r\n text-decoration: none;\r\n}\r\n\r\na:hover::after {\r\n content: \"\";\r\n position: absolute;\r\n left: 25%;\r\n right: 25%;\r\n bottom: 0;\r\n border: 1px solid black;\r\n}\nDemo Link\n\n\n\nA: use underline or if u want the line to be much shorter try scalar vector graphics(svg) with this you can have custom lines.\n\n \n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/23631822", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "10"}} {"text": "Q: EF Insert Array into db With View I have something to ask , i 'm going to create a simple application that store value of student Below is my class which i have tried . \nClass Data{\n public int Id {get;set;}\n public string Name {get;set;}\n public int[] ValuesStudent{get;set;} \n\n}\nAnd below is example of the data \nid = 1 \nName = Jhon \nValues = 9,8,7,5,9,7,4,6,4\n\n\nid = 2\nName = Uncle \nValues = 4,7,8,4\n\nid = 3 \nName = Jhon \nValues = 9,8,7,5,9,7\n\nas you can see above example of the data i can insert multiple value as i need, Student has taken 3 examination so i must insert 3 values for him . \nBut what i'm confuse is how can i make insert new Data . enter image description here\nOke if you any link which refer about problem , and explain about it , you can directly comment it .\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/39550765", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Is there a property I can check to see if code is rendered using hydrate vs render? I have a React app (with SSR) and need to handle things differently for server vs browser renders.\n\nA: I ended up using the following, but my gut feeling is there is a better way.\nif (typeof window !== \"undefined\") {\n // This code is rendered in browser vs server\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/64279861", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to abort processing a request in NodeJS http server I have your standard callback-hell http server like (simplified):\nhttp.createServer((req, res) => {\n doSomething(() => {\n doMoreSomethings(() => {\n if (!isIt())\n // explode A\n\n if (!isItReally())\n // explode B\n\n req.on('data', (c) => {\n if (bad(c))\n // explode C\n });\n\n req.on('end', () => {\n // explode D\n });\n });\n });\n};\n\nThe only way I know of to end the request is res.end(), which is asynchronous, so stuff after you call that will run (as far as I can tell). Is there a way to do a pseudo-process.exit mid-flight and abort processing the request, so I don't waste time on other stuff? For example how can I stop at the above // explode lines and not process anything else? throw doesn't leap over scope boundaries. Basically, I think, I want to return or break out of the createServer callback from within a nested callback. Is the only way to do this to be able to have code with a single path and just not have more than one statement at each step? Like, horizontal coding, instead of vertical KLOCs.\nI'm a Node noob obviously.\nEdit: Maybe another way to ask the question is: Is it possible to abort at the // explode C line, not read any more data, not process the end event, and not process any more lines in the doMoreSomethings callback (if there were any)? I'm guessing the latter isn't possible, because as far as I know, doMoreSomethings runs to completion, including attaching the data and end event handlers, and only then will the next event in the queue (probably a data event) get processed, at which point doMoreSomethings is done. But I am probably missing something. Does this code just zip through, call isIt and isItReally, assign the event handlers, hop out of all the callbacks, the createServer callback finishes, and then all the extra stuff (data/end/etc.) runs from the event queue?\n\nA: Typically you will use a return statement. When you call return any code below it will not get executed. Although, if your functions isIt() or isItReally() are asynchronous functions then you will be running into trouble as those are used in a synchronous fashion.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/40808578", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Looking for a script/tool to dump a list of installed features and programs on Windows Server 2008 R2 The same compiled .Net / C++ / Com program does different things on two seemingly same computers. Both have DOZENS of things installed on them. I would like to figure out what the difference between the two is by looking at an ASCII diff. Before that I need to \"serialize\" the list of installed things in a plain readable format - sorted alphabetically + one item per line.\nA Python script would be ideal, but I also have Perl, PowerShell installed.\nThank you.\n\nA: You can get the list of installed programs from the registry. It's under HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\nIf this is a once-off exercise you may not even need to write any code - just use Regedit to export the key to a .REG file. If you do want to automate it Python provides the _winreg module for registry access.\n\nA: There are two tools from Microsoft that may be what you need: RegDump and RegDiff. You can download them from various places, including as part of the Microsoft Vista Logo Testing Toolkit.\nAlso, there is Microsoft Support article How to Use WinDiff to Compare Registry Files.\nFor a Pythonic way, here is an ActiveState recipe for getting formatted output of all the subkeys for a particular key (HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall for example). \n\nA: Personally I always liked sysinternals' stuff (powerfull, light, actual tools - no need to install)\nThere is command line tool psinfo that can get you what you want (and then some) in various formats, distinguishing hotfixes and installed software, on local or remote computer (providing system policies allow it on remote).\nYou can also run it live from here, so though not strictly pythonic you could plug it in quite nicely.\n\nA: Taken from List installed software from the command line:\n\nIf you want to list the software known to Windows Management\n Instrumentation (WMI) from the command line, use WMI command line\n (WMIC) interface.\nTo list all products installed locally, run the following\n command:\nwmic product\n\nCaveat: It seems that this command only list software installed through Windows Installer. See Win32_Product class\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/2448612", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Using Python CGI for a big HTML file I have a big html file named exercise.html, I need generate to one som stuff by Python CGI.\nI want to ask you what is the best way to print this HTML.\nI know that it is possible by print method with using format methods %s, %i etc.:\nprint '''\nMy first Python CGI app\n \n

Hello, 'world'!

\n.\n.\n
%s
\n.\n.\n\n''' % generated_text\n\nBut this HTML is really big,so is this only one solution?\n\nA: You should consider using a templating language like Jinja2. \nHere is a simple example straight from the link above:\n>>> from jinja2 import Template\n>>> template = Template('Hello {{ name }}!')\n>>> template.render(name='John Doe')\n\nGenerally, though you save templates in a file, and then load / process them:\nfrom jinja2 import Environment, PackageLoader\n# The env object below finds templates that are lcated in the `templates`\n# directory of your `yourapplication` package.\nenv = Environment(loader=PackageLoader('yourapplication', 'templates'))\ntemplate = env.get_template('mytemplate.html')\nprint template.render(the='variables', go='here')\n\nAs demonstrated above, templates let you put variables into the template. Placing text inside {{ }} makes it a template variable. When you render the template, pass in the variable value with a keyword argument. For instance, the template below has a name variable that we pass via template.render\n\nThis is my {{name}}.\n\ntemplate.render(name='Jaime')\n\n\nA: Also consider Python Bottle (SimpleTemplate Engine). It is worth noting that bottle.py supports mako, jinja2 and cheetah templates.\nThe % indicates python code and the {{var}} are the substitution variables\nHTML:\n
    \n % for item in basket:\n
  • {{item}}
  • \n % end\n
\n\nPython:\nwith open('index.html', 'r') as htmlFile:\n return bottle.template(htmlFile.read(), basket=['item1', 'item2'])\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/23654230", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: A nicer recurrence for the Eulerian polynomials. I was perusing the subject of Eulerian polynomials. I'm assuming the definition that the Eulerian polynomial is defined by $C_n(t)=\\sum_{\\pi\\in S_n}t^{1+d(\\pi)}$, where $d(\\pi)$ is the number of descents.\nThe Eulerian polynomials satisfy a standard recurrence $C_n(t)=t(1-t)C'_{n-1}(t)+ntC_{n-1}(t)$. Apparently they also satisfy the more aesthetically pleasing relation\n$$\r\nC_n(t)=tC'_{n-1}(t)+t^nC'_{n-1}(t^{-1}).\r\n$$\nThe generating function in $t^{-1}$ is troublesome to me. How can one derive this other recurrence relation? Thank you,\n\nA: Write $C_{n-1}(t) = \\sum_{k=1}^{n-1} a_k t^k$, and look eactly how each term contributes in $C_n(t)$ :\nYour first recurrence relation says :\n$C_n(t) = t(1-t)C'_{n-1}(t)+ntC_{n-1}t = (t-t^2)(\\sum_{k=1}^{n-1} k a_k t^{k-1}) + nt(\\sum_{k=1}^{n-1} a_k t^k) \\\\\r\n = \\sum_{k=1}^{n-1} (k-kt+nt)a_k t^k = \\sum_{k=1}^{n-1} (k + (n-k)t)a_k t^k $\nEssentially, each term $t^k$ is turned into $k t^k + (n-k) t^{k+1}$ \nThe second recurrence relation attempts to show this symmetric-looking separation :\n$tC'_{n-1}(t) = \\sum_{k=1}^{n-1} k a_k t^k$ : we recover the first half, which leaves us with the other half.\nSince it is the same thing but in the other direction, we have to switch the coefficients of the polynomial around, differentiate, adjust the power of $t$, then switch them around again.\nIn fact, since the Euler polynomials are symmetric, $a_k = a_{n-k}$, we can skip the first step. The last switching around step explains why you see that $C'_{n-1}(t^{-1})$ :\n$\\sum_{k=1}^{n-1} (n-k) a_k t^{k+1} = \\sum_{k=1}^{n-1} (n-k) a_{n-k} t^{k+1} \r\n= \\sum_{k=1}^{n-1} k a_k t^{n-k+1} \\\\\r\n = t^n \\sum_{k=1}^{n-1} k a_k (t^{-1})^{k-1} = t^n C'_{n-1}(t^{-1})$.\nEven if you use $t^{-1}$, $t^n C'_{n-1}(t^{-1})$ is still a polynomial in $t$. It is a simple trick done to reverse the coefficients of a polynomial.\nFor example, stating that the polynomials are symmetric ($a_k = a_{n-k}$),\nis the same as stating that $C_n(t) = t^{n+1} C_n(t^{-1})$\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/106520", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "7"}} {"text": "Q: Callback parameters gets shifted I have a video c++ callback function where the parameters get suddently shifted after a few hours. In debug, it will assert on this:\nvoid CCameraInstance::VideoCallback(void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)\n{\n assert(nWidth < 4000);\n CCameraInstance *pThis = (CCameraInstance*)pContext;\n pThis->PaintFrame(pBuffer, nWidth, nHeight, nFrameErrorNo);\n}\n\nWhen the debugger breaks on the assert, nWidth has a big invalid value. However, nHeight is 320 (the width value) and nFrameErrorNo is 240 (the nHeight value).\nHow can the parameters get shift that way?\n\nA: The shift could be caused by the hidden this pointer. http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/\nFrom the code you have pasted here\nvoid CCameraInstance::VideoCallback(void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)\n\nI can see the callback function is a member of class CCameraInstance\nI'm not sure whether you are defining the function as a static function or a normal one. But in theory it should be a static function to avoid the this pointer. Using a C++ class member function as a C callback function\nHowever, I had a problem with C++/CLI even if i have define the member function as static. The this pointer/Handle still exist.\nI think you can try to define your function as \nvoid CCameraInstance::VideoCallback(CCameraInstance* test,void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)\n\nand have try.\nIf you are using C++/CLI it would be \nvoid CCameraInstance::VideoCallback(CCameraInstance^ test,void *pContext, unsigned char *pBuffer, long nWidth, long nHeight, long nFrameErrorNo)\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/19498545", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Negation with multiple quantifiers I have a logical statement that looks like the following for the sentence \"If every cat feels wet, then every dog is happy\"\n$$\n[\\forall x \\ \\ C(x) \\implies W(x)] \\implies [\\forall y \\ \\ D(y) \\implies H(y)]\n$$\nI want to put the NEGATED version of this statement in CNF form, so first I remove all the implications:\n$$\n\\lnot([\\forall x \\ \\ \\lnot C(x) \\lor W(x)] \\implies [\\forall y \\ \\ \\lnot D(y) \\lor H(y)]) \\\\\n\\lnot([\\lnot\\forall x \\ \\ \\lnot C(x) \\lor W(x)] \\lor [\\forall y \\ \\ \\lnot D(y) \\lor H(y)]) \\\\\n\\lnot([\\exists x \\ \\ C(x) \\land \\lnot W(x)] \\lor [\\forall y \\ \\ \\lnot D(y) \\lor H(y)]) \\ \\ \\ \\text{used Demorgan's Law here}\\\\\n$$\nAssuming the above steps are current, I am confused on how to distribute the outermost negation inside when there are quantifiers and logical statements.\nI understand the following conversions:\n$$\n\\lnot \\forall x \\ P(x) = \\exists x \\ \\lnot P(x) \\\\\n\\lnot \\exists x \\ P(x) = \\forall x \\ \\lnot P(x) \\\\\n\\lnot (a \\lor b \\lor...c) = \\lnot (\\lnot a \\land \\lnot b \\land...\\lnot c) \\\\\n\\lnot (a \\land b \\land...c) = \\lnot (\\lnot a \\land \\lnot b \\lor...\\lnot c)\n$$\nbut it's not clear to me how I can distribute the outermost negation because now it involves quantifiers. Any hints?\nEdit 1\nI think I may have gotten it:\n$$\n(\\lnot[\\exists x \\ \\ C(x) \\land \\lnot W(x)] \\land \\lnot[\\forall y \\ \\ \\lnot D(y) \\lor H(y)]) \\\\\n([\\forall x \\ \\ \\lnot C(x) \\lor W(x)] \\land [\\exists y \\ \\ D(y) \\land \\lnot H(y)]) \\\\\n$$\n\nA: One extra substitution rule to remember is Implication Negation Equivalence: $$\\neg(\\phi\\to\\psi) ~\\equiv~ (\\phi\\wedge\\neg\\psi)$$\nThis can be derived using:\n$$\\begin{align}\\neg(\\phi\\to\\psi)&\\quad&\\\\\\neg(\\neg\\phi\\vee\\psi)&&&\\text{Implication Equivalence}\\\\\\neg\\neg\\phi\\wedge\\neg\\psi&&&\\text{de Morgan's Rule}\\\\\\phi\\wedge\\neg\\psi&&&\\text{Double Negation Equivalence}\\end{align}$$\nAlso vice versa.\nThus your statement's negation begins:\n$$\\begin{align}&\\neg\\Big(\\big(\\forall x~(Cx\\to Wx)\\big)\\to\\big(\\forall y~(Dy\\to Hy)\\big)\\Big)\n\\\\&\\quad\\big(\\forall x~(Cx\\to Wx)\\big)\\wedge\\neg\\big(\\forall y~(Dy\\to Hy)\\big)&&\\text{Implication Negation Equivalence}\n\\\\&\\quad\\vdots\\end{align}$$\nAnd it should be clear how to continue.\n\nAlso recall that the distribution rules for quantifiers in non-empty domains includes: $$(\\forall x~P(x))\\wedge (\\exists y~Q(y))~~\\equiv~~ \\forall x~\\exists y~(P(x)\\wedge Q(y))$$\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/3593555", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Composite/Combined Indexing vs Single Index vs multiple Combined Indexed on a large table I have a very large table (that is still growing) (around 90GB with ~350mil rows). It is a table that include sales of items, if you were wondering.\nIn this table, there's (for example), column A,B,C,D,E,F,G.\nCurrently, I am using a combined index, consisting of (A,B,C,D,E,F).\nUsually, the query will consist of A,B,C,D,E. F is included occasionally (hence the indexing).\neg,\nSELECT * FROM table WHERE A = ? AND B = ? AND C = ? AND D = ? AND E = ?;\nSometimes, with the addon of AND F = ?;\nBut on certain occasion, the query will consist of A,B,C,D,G (whereby G is not indexed (not combined nor single indexed).\nThis causes timeout on certain occasion as the data is quite big.\nSo my question is, in order to solve this issue in terms of indexing,\nshould I\nOption 1: add G into the combined index, making it become (A,B,C,D,E,F,G).\n\n*\n\n*Does this even work when I query A,B,C,D,G (missing E & F)?\n\nOption 2: add G as a single index.\n\n*\n\n*Based on what i know, this does not work, as my query has A,B,C,D,G. The first combined index will be used instead (correct me if I'm wrong).\n\nOption 3: Go with option 1, combine all the columns, but I change my query instead, to always query A,B,C,D,E,F,G even when F is not needed.\neg,\nSELECT * FROM table WHERE A = ? AND B = ? AND C = ? AND D = ? AND E = ? AND F IS NOT NULL AND G = ?;\nThanks\n\nA: Option 1 - Yes, this will work. The server will perform index seek by (A,B,C,D,E) and furter index scan by (G).\nOption 2 - Makes no sense in most cases, server uses only one index for one source table copy. But when the selectivity of single index by (G) is higher than one for (A,B,C,D,E) combination then the server will use this single-column index.\nOption 3 - The processing is equal to one in Option 2.\n\nA: Are the PRIMARY KEY's column(s) included in A..E ? If so, none of the indexes are needed.\nWhat datatypes are involved?\nAre they all really tests on =? If not then 'all bets are off'. More specifically, useful indexes necessarily start with the columns tested with = (in any order). In particular, F IS NOT NULL is not = (but IS NULL would count as =).\nI would expect INDEX(A,B,C,D,E, anything else or nothing else) to work for all of the queries you listed. (Hence, I suspect there are some details missing from your over-simplified description.)\nHow \"selective\" are F and G? For example, if most of the values of G are distinct, then INDEX(G) would possibly be useful by itself.\nPlease provide SHOW CREATE TABLE and EXPLAIN SELECT ...\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/73581169", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to convert below javascript code to work in IE11 I want to convert my code from es6 to es4-3 so that it supports IE11. I am trying to toggle the class=\"open\" for the three button which helps me to open a small div.\nJS:\nlet customSelect = document.getElementsByClassName('input-select')\n\nArray.from(customSelect).forEach((element, index) => {\n element.addEventListener('click', function () {\n Array.from(customSelect).forEach((element, index2) => {\n if (index2 !== index) {\n element.classList.remove('open')\n }\n })\n this.classList.add('open')\n })\n\n for (const option of document.querySelectorAll('.select-option')) {\n option.addEventListener('click', function () {\n if (!this.classList.contains('selected')) {\n this.parentNode\n .querySelector('.select-option.selected')\n .classList.remove('selected')\n this.classList.add('selected')\n this.closest('.input-select').querySelector(\n '.input-select__trigger span'\n ).textContent = this.textContent\n }\n })\n }\n\n // click away listener for Select\n document.addEventListener('click', function (e) {\n var isClickInside = element.contains(e.target);\n if(!isClickInside) {\n element.classList.remove('open');\n } \n return\n })\n}) \n\nHTML:\n
\n \n
\n

Hi

\n

Bye

\n
\n
\n
\n \n
\n

Hi

\n

Bye

\n
\n
\n \n
\n

Hi

\n

Bye

\n
\n
\n\nThis is pure es6 code i need to convert it into lower version of js\n\nA: This is the Babel's (targeted only to IE 11) answer:\n\"use strict\";\n\nfunction _createForOfIteratorHelper(o, allowArrayLike) {\n var it =\n (typeof Symbol !== \"undefined\" && o[Symbol.iterator]) || o[\"@@iterator\"];\n if (!it) {\n if (\n Array.isArray(o) ||\n (it = _unsupportedIterableToArray(o)) ||\n (allowArrayLike && o && typeof o.length === \"number\")\n ) {\n if (it) o = it;\n var i = 0;\n var F = function F() {};\n return {\n s: F,\n n: function n() {\n if (i >= o.length) return { done: true };\n return { done: false, value: o[i++] };\n },\n e: function e(_e) {\n throw _e;\n },\n f: F\n };\n }\n throw new TypeError(\n \"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"\n );\n }\n var normalCompletion = true,\n didErr = false,\n err;\n return {\n s: function s() {\n it = it.call(o);\n },\n n: function n() {\n var step = it.next();\n normalCompletion = step.done;\n return step;\n },\n e: function e(_e2) {\n didErr = true;\n err = _e2;\n },\n f: function f() {\n try {\n if (!normalCompletion && it.return != null) it.return();\n } finally {\n if (didErr) throw err;\n }\n }\n };\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))\n return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n return arr2;\n}\n\nvar customSelect = document.getElementsByClassName(\"input-select\");\nArray.from(customSelect).forEach(function (element, index) {\n element.addEventListener(\"click\", function () {\n Array.from(customSelect).forEach(function (element, index2) {\n if (index2 !== index) {\n element.classList.remove(\"open\");\n }\n });\n this.classList.add(\"open\");\n });\n\n var _iterator = _createForOfIteratorHelper(\n document.querySelectorAll(\".select-option\")\n ),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done; ) {\n var option = _step.value;\n option.addEventListener(\"click\", function () {\n if (!this.classList.contains(\"selected\")) {\n this.parentNode\n .querySelector(\".select-option.selected\")\n .classList.remove(\"selected\");\n this.classList.add(\"selected\");\n this.closest(\".input-select\").querySelector(\n \".input-select__trigger span\"\n ).textContent = this.textContent;\n }\n });\n } // click away listener for Select\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n\n document.addEventListener(\"click\", function (e) {\n var isClickInside = element.contains(e.target);\n\n if (!isClickInside) {\n element.classList.remove(\"open\");\n }\n\n return;\n });\n});\n\n\nA: You can use Babel to transpile the code first. You can also refer to this tutorial about how to use Babel to transpile code.\nThe code I use Babel to transpile is like below:\n'use strict';\n\nvar customSelect = document.getElementsByClassName('input-select');\n\nArray.from(customSelect).forEach(function (element, index) {\n element.addEventListener('click', function () {\n Array.from(customSelect).forEach(function (element, index2) {\n if (index2 !== index) {\n element.classList.remove('open');\n }\n });\n this.classList.add('open');\n });\n\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = document.querySelectorAll('.select-option')[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var option = _step.value;\n\n option.addEventListener('click', function () {\n if (!this.classList.contains('selected')) {\n this.parentNode.querySelector('.select-option.selected').classList.remove('selected');\n this.classList.add('selected');\n this.closest('.input-select').querySelector('.input-select__trigger span').textContent = this.textContent;\n }\n });\n }\n\n // click away listener for Select\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n document.addEventListener('click', function (e) {\n var isClickInside = element.contains(e.target);\n if (!isClickInside) {\n element.classList.remove('open');\n }\n return;\n });\n});\n\nThen add this line of code before the script to add a polyfill:\n\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/71392000", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: FileNotFoundException : Could not open ServletContext resource [/WEB-INF/spring/root-context.xml] I am facing below exception while building a SpringMVC application through Maven.\nMaven builds the application and tries to deploy on already running tomcat which fails.\nIf I build and run the same code through eclipse+inbuild Tomcat, it runs fine.\nException coming while building from Maven:\njava.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/spring/root-context.xml]\nat org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)\nat org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)\nat org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)\nat org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)\nat org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)\nat org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)\nat org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)\nat org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)\nat org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)\nat org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)\nat org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)\nat org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)\nat org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)\nat org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5003)\nat org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5517)\nat org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)\nat org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)\nat org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)\nat org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)\nat org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1095)\nat org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1930)\nat java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)\nat java.util.concurrent.FutureTask.run(FutureTask.java:262)\nat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)\nat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)\nat java.lang.Thread.run(Thread.java:745)\nCaused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/spring/root-context.xml]\nat \n\nweb.xml\n\n\n\n\n contextConfigLocation\n /WEB-INF/spring/root-context.xml\n\n\n\n\n org.springframework.web.context.ContextLoaderListener\n\n\n\n\n appServlet\n org.springframework.web.servlet.DispatcherServlet\n \n contextConfigLocation\n /WEB-INF/spring/appServlet/servlet-context.xml \n\n\n \n 1\n\n\n\n appServlet\n /\n\n\n\nHere is my project Structure\n\nIs there any way to solve this ?\nThanks\n\nA: @ian-roberts and @bohuslav-burghardt already answered your question: you have created a structure that doesn't conform to the structure that Maven project must have.\nTo fix it you should put all contents of WebContent directory to src/main/webapp\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/32652133", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: In python, is it easy to call a function multiple times using threads? Say I have a simple function, it connects to a database (or a queue), gets a url that hasn't been visited, and then fetches the HTML at the given URL.\nNow this process is serial, i.e. it will only fetch the html from a given url one at a time, how can I make this faster by doing this in a group of threads?\n\nA: Yes. Many of the Python threading examples are just about this idea, since it's a good use for the threads.\nJust to pick the top four Goggle hits on \"python threads url\": 1, 2, 3, 4.\nBasically, things that are I/O limited are good candidates for threading speed-ups in Python; things the are processing limited usually need a different tool (such as multiprocessing).\n\nA: You can do this using any of:\n\n\n*\n\n*the thread module (if your task is a function)\n\n*the threading module (if you want to write your task as a subclass of threading.Thread)\n\n*the multiprocessing module (which uses a similar interface to threading)\n\n\nAll of these are available in the Python standard library (2.6 and later), and you can get the multiprocessing module for earlier versions as well (it just wasn't packaged with Python yet).\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/4962022", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: \u00bfC\u00f3mo Puedo insertar dentro de un JButton un icono y texto en un salto de Linea usando NetBeans? Quiero agregar un icono tipo .png dentro de un JButton y con un salto de linea agregar texto, esto con la finalidad de que la GUI del proyecto se vea mejor y el usuario pueda identificar con imagen y texto la acci\u00f3n que se quiere realizar. Cabe mencionar que estoy utilizando la IDE NetBeans\nHe intentado lo siguiente:\nbtnAdd_Departamentos.setText(\"\");\n\nPero me marca error en la imagen.\n", "meta": {"language": "es", "url": "https://es.stackoverflow.com/questions/331649", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: password set during checkout issue I have an issue with customer registered through checkout. \nAfter the checkout process, the customer lands in \u201cMy Account\u201d but once logged off, he can\u2019t acces \"My Account\" anymore, the message \"Invalid login or password\" is displayed.\nSetting a new password through \u201cForgotten Password\u201d button seems to solve the problem for the customer. (But it would be great if the password could work directly without passing through this step.)\nI think (but am not sure at all) that the password set through billing.phtml is not stored correctly.\nThe customers registered through \"Register\" button are saved correctly and don't encounter any issue.\nI have in template/persistent/Customer/form/register.phtml:\n
  • \n
    \n \n
    \n quoteEscape($this->__('Password')) ?>\" class=\"input-text required-entry validate-password\" />\n
    \n
    \n
    \n \n
    \n quoteEscape($this->__('Confirm Password')) ?>\" id=\"confirmation\" class=\"input-text required-entry validate-cpassword\" />\n
    \n
    \n
  • \n\nIn template/Customer/form/resetforgottenpassword.phtml:\n
  • \n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n \n
    \n
    \n
  • \n\nAnd in template/persistent/checkout/onepage/billing.phtml, which I think is the culprit:\n
  • \n
    \n \n
    \n quoteEscape($this->__('Password')) ?>\" class=\"input-text required-entry validate-password\" />\n
    \n
    \n
    \n \n
    \n quoteEscape($this->__('Confirm Password')) ?>\" id=\"billing:confirm_password\" class=\"input-text required-entry validate-cpassword\" />\n
    \n
    \n
  • \n\nI tried several modifications to billing.phtml, such as:\n\nquoteEscape($this->__('Password')) ?>\" class=\"input-text required-entry validate-password\" />\nquoteEscape($this->__('Confirm Password')) ?>\" id=\"confirmation\" class=\"input-text required-entry validate-cpassword\" />\n\nBut I\u2019m still leading to the same result.\nI\u2019m on a CE 1.9.3.1 patched with SUPEE 9652.\nHow to make Customer registered during checkout being saved correctly?\n\nA: I have 4 errors concerning lib/Varien/Crypt/Mcrypt.php\nWarning: mcrypt_generic_init(): Key size is 0 in /lib/Varien/Crypt/Mcrypt.php on line 94\nWarning: mcrypt_generic_init(): Key length incorrect in /lib/Varien/Crypt/Mcrypt.php on line 94\nWarning: mcrypt_generic_deinit(): 495 is not a valid MCrypt resource in /lib/Varien/Crypt/Mcrypt.php on line 135\nWarning: mcrypt_module_close(): 495 is not a valid MCrypt resource in /lib/Varien/Crypt/Mcrypt.php on line 136\n\nI thought it was relative to a module is missing in PHP Mcrypt on my server (https://magento.stackexchange.com/a/35888). But it's not the case as by installing a fresh CE 1.9.3.1 in a folder in the root of the same Magento installation is doing its job properly with the same server configuration and Mcrypt.php. Moreover, the password set during registration with form (?and using the same encryption?), is set properly.\nI'll open a new post with more precisions.\n@urfusion, thank you for advice, I was looking at the wrong end of system.log (thought it was writing on the top...)\nEdit\nI got it, the solution's here:\nhttps://stackoverflow.com/a/42474835/7553582\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/42439888", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to change part of window content upon combo box selection changed event? In my wpf window I want to change part of it (make different controls visible) when combo box selection is changed. Exactly like TabControl works, just with combobox. I know I could just make some controls visible while hiding the others in the c# code behind but I want to find out if there are other -better solutions.\n\nA: You can use two Grid or GroupBox (or other container type) controls and put appropriate set of controls in each of them. This way you can just visibility of panels to hide the whole set of controls instead of hiding each control directly.\nIt may sometimes be appropriate to create a user control for each set of controls. However, this can depend on a specific case.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/10541331", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to block mouse click events from another form I have a winforms single form application that uses a \"Thickbox\" I've created whenever the loads a new view into the application form.\nThe \"Thickbox\" shows another form in front of the application's form that is semi-transparent and has a user control that is the box itself.\nThis thickbox can be shown a modal dialog and in that case I have no problems at all, but it can also be shown as a non modal, for instance, when the user switches views in the main form, it shows thickbox with a loading animated icon.\nThe problem is that when the thickbox is shown as non modal, it doesn't block the user from clicking on the buttons of main form of the application.\nWhen thickbox is shown nothing happens, but as soon as it's closed, the click is being processed by the click event handler of the relevant button in the main form.\nI can't use ShowDialog since I can't block the UI thread, and I need to get the indication from the main form when to close the thickbox,\nI can't set the Enabled property of the owner form as described in this answer (though I've tried various versions of this solution, nothing helps)\nI've tried using the win API function BlockInput as descried in this answer, but that didn't block the input,\nI think my best chance is using the Application.FilterMessage method, but I couldn't get that to block the mouse clicks as well. \nIt would be great if I could encapsulate the mouse click blocking inside the thickbox form itself, so that it would be usable easily with other applications as well, but \na solution on to the calling form would also be very much appreciated.\n\nA: I'm glad to announce that the problem is finally solved.\nAfter spending a few days attempting to recreate this bug in a new application, re-constructing the main form in the application, comment out parts of the code in the main application, and generally just shooting all over to try and find a lead, It finally hit me.\nThe application behaved as if the clicks on the thickbox was queued somehow and only activated when the thickbox was closed. This morning, after fixing some other bugs, The penny finally dropped - all I was missing was a single line of code right before closing the thickbox's form: \nApplication.DoEvents();\n\nThe annoying thing is that it's not something that's new to me, I've used it many times before including in the main application and in the thickbox code itself... I guess I just had to let if go for a while to enable my mind to understand what was so painfully obvious in hindsight...\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/35684964", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Create twin object a.k.a. inheritance clone The working twin(source) function below generates a new object with the same own properties as source and with the same parents (prototype chain). (e.g. twin(isFinite) would be [object Object] and instanceof Function) Does any native function provide the same effect?\n/**\n * @param {Object|Function} source\n * @param {(Object|Function|null)=} parent defaults to source's parents\n * @return {Object}\n */\nfunction twin(source, parent) {\n var twin, owned, i = arguments.length;\n source = i ? source : this; // use self if called w/o args\n parent = 2 == i ? parent : Object.getPrototypeOf(source);\n twin = Object.create(parent);\n owned = Object.getOwnPropertyNames(source);\n for (i = owned.length; i--;) {\n twin[owned[i]] = source[owned[i]];\n }\n return twin;\n}\n\nUpdate: A .twin method is available in blood.\n\nA: You can try something like this:\nobj= eval(uneval(objSource));\n\nIt only works in FF but the idea is to serialize an object and the eval the serialized string instantiating (prototyping) a new object with the same properties as the first one.\nYou can use also the function JSON.stringify as the \"uneval\" function.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/16594717", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: Mathematical models in geology and industry I'm a student of applied math. Do you think that if I attend courses on mathematical models in geology will I have the possibility to apply what I've learned in industry? I think it's a very interesting field but I've never heard of mathematicians working on \"computational geology\" outside academia. \n\nA: There is a great deal of mathematical modeling in industrial geology. Particularly among the large mining and oil producing companies. Of particular interest are models of seismic and electromagnetic methods of exploration.\n\nA: \"A geophysicist friend once told me that geophysicists are geologists that know math.\"\nSee:\nhttps://earthscience.stackexchange.com/questions/265/what-is-the-difference-between-a-geologist-and-a-geophysicist\nTo start, try the book \"An Introduction to Geophysical Exploration\" by Kearey, Brooks and Hill.\nhttp://elibrary.bsu.az/azad/new/2192.pdf\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/2328435", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Updating parent component only after multiple child components have completed running I have a Parent react component with multiple child components that are created through a .map() function. I am passing in a function addCallback() as child props so I have a reference and can trigger all child's handleRun() function via the Parent.\nI'm trying to update state of my Parent component to running = true when all children are running and to running = false and render said status on the parent when all children have completed running. However the state doesn't seem to update in the particular sequence I specify.\nHere is how I'm doing it:\nlet promise1 = this.setState({isRunning: true},\n () => {\n this.state.childRef.map(x => x())\n });\n\nPromise.all([promise1])\n .then(() => this.setState({isRunning: false}))\n\nHere's the entire code in codesandbox: link \nWould appreciate your help as I'm still pretty new to React (and Javascript in general). Thanks!\n\nA: Cause runSomething is not a Promise. You must change. \nrunSomething() {\n return new Promise((resolve, reject) => {\n this.setState({ status: \"running\" });\n // simulate running something that takes 8s\n setTimeout(() => {\n this.setState({ status: \"idle\" });\n resolve(true);\n }, 3000);\n });\n}\n\nA working sandbox here https://codesandbox.io/s/fragrant-cloud-5o2um\n\nA: Using async in a function declaration automatically returns a Promise wrapped around whatever you are returning from your function. In your case, it's undefined. This is why your current code is not throwing any errors at the moment.\nYou will need a mechanism to wait for the setTimeout. Changing the runSomething function like this will work\n async runSomething() {\n this.setState({ status: \"running\" });\n\n // simulate running something that takes 8s\n return new Promise(resolve => {\n setTimeout(() => {\n this.setState({ status: \"idle\" }, resolve);\n }, 3000);\n });\n }\n\nDo notice the line this.setState({ status: \"idle\" }, resolve);. It makes sure that your promise resolves not only after the setTimeout but also after the child's state is changed to \"idle\". Which is the correct indication that your child component has moved to \"idle\" state.\nCodesandbox: https://codesandbox.io/s/epic-boyd-12hkj\n\nA: Here is the sandbox implementation of what you are trying to achieve. Sanbox\nHere i have created a state in parent component that will be updated when child is running. \nthis.state = {\n callbacks: [],\n components: [\n {\n index: 0, // we don't need this field its just for your info you can just create [true,false] array and index will represent component index.\n status: false\n },\n {\n index: 1,\n status: false\n }\n ]\n};\n\nWhen all the status in component array is true we update the idle status of parent to running. \n getAllRunningStatus() {\n let { components } = this.state;\n let checkAllRunning = components.map(element => element.status);\n if (checkAllRunning.indexOf(false) === -1) { // you can also use !includes(false) \n return true;\n }\n return false;\n }\n\ninside your render function \n

    Parent {this.getAllRunningStatus() ? \"running\" : \"idle\"}

    \n\nNote:- I have just written a rough code. You can optimise it as per your requirements. Thanks\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/56784785", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: How to access a variable that was available when an async method was called? The animal names are fetched from an API that could return 404 if the animal is not found. But in order to properly log the error, we need to have access to the animal's country. Is it possible? I've read something from a guy called Stephen Cleary that made me think it is possible with lambdas, but I couldn't find anything.\nvar gettingNames = new List>();\n\nforeach (var animal in animals)\n{\n gettingNames.Add(this.zooApi.GetNameAsync(animal));\n}\n\ntry\n{\n await Task.WhenAll(gettingNames);\n}\ncatch (Exception e)\n{\n var exception = gettingNames.Where(task => task.IsFaulted)\n .SelectMany(x => x.Exception.InnerExceptions).First();\n\n this.logger.LogError(\"The animal name from {Country} was not found\",\n animal.Country); // This is the goal\n}\n\n\nA: One way to solve this problem is to project each Animal to a Task that contains more information than either a naked name or a naked error. For example you could project it to a Task> that contains three pieces of information: the animal, the animal's scientific name from the zooApi, and the error that may have happened while invoking the zooApi.GetScientificNameAsync method.\nThe easiest way to do this projection is the LINQ Select operator:\nList> tasks = animals.Select(async animal =>\n{\n try\n {\n return (animal, await this.zooApi.GetScientificNameAsync(animal),\n (Exception)null);\n }\n catch (Exception ex)\n {\n return (animal, null, ex);\n }\n}).ToList();\n\n(Animal, string, Exception)[] results = await Task.WhenAll(tasks);\n\nforeach (var (animal, scientificName, error) in results)\n{\n if (error != null)\n this.logger.LogError(error,\n $\"The {animal.Name} from {animal.Country} was not found\");\n}\n\n\nA: You have almost nailed it. :)\nRather than having a List> you need a Dictionary, string> structure:\nstatic async Task Main()\n{\n var taskInputMapping = new Dictionary, string>();\n var inputs = new[] { \"input\", \"fault\", \"error\", \"test\"};\n foreach (var input in inputs)\n {\n taskInputMapping.Add(DelayEcho(input), input);\n }\n\n try\n {\n await Task.WhenAll(taskInputMapping.Keys);\n }\n catch\n {\n foreach (var pair in taskInputMapping.Where(t => t.Key.IsFaulted))\n {\n Console.WriteLine($\"{pair.Value}: {pair.Key.Exception?.GetType().Name}\");\n }\n }\n}\n\nstatic readonly ImmutableArray wrongInputs = \n ImmutableArray.Create(\"error\", \"fault\");\nstatic async Task DelayEcho(string input)\n{\n if (wrongInputs.Contains(input)) throw new ArgumentException();\n await Task.Delay(10);\n return input;\n}\n\n\n*\n\n*taskInputMapping.Add(DelayEcho(input), input): Stores the input next to the Task itself\n\n*taskInputMapping.Where(t => t.Key.IsFaulted): Iterates through the faulted tasks\n\n*$\"{pair.Value}: {pair.Key.Exception?.GetType().Name}\": Retrieves the input + the related error\n\n\nA: I combined the answers and came up with this:\nvar tasks = animals.Select(async animal =>\n{\n try\n {\n return await this.zooApi.GetNameAsync(animal);\n }\n catch (Exception ex)\n {\n this.logger.LogError(error,\n $\"The {animal.Name} from {animal.Country} was not found\");\n\n return null;\n }\n});\n\nvar results = await Task.WhenAll(tasks);\n\nforeach (var name in results.Where(x => x != null))...\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/69383186", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: HTML divide and conquer i am looking for the best pratice when it comes to HTML.\nNow my normal programming instincts tells me to always divide and conquer but i am not sure how or even if it is recommended when it comes to HTML.\nSo say for example i have the following index file:\n \n \n \n Dinner plans\n \n \n
    \n
    \n
      \n
    • \n
      \n\n \n\n \n\n
      \n\n
    • \n\n
    \n
    \n
    \n \n
    \n
    \n\n\n\n\nnow i would devide some of this code for example the menu into another HTML file for instance menu.html and then place the content of the file within the index file.\nMy question is simple is this recommended and if so how is it achieved?\n\nA: I think what you are asking is if you can separate parts of an HTML page into smaller pages, so you can separate concerns.\nIn PHP this can be accomplished by referencing other files by a require() or include(). But I still don't believe this really answers your question. ASP.NET MVC allows you to render partial views within a webpage through `RenderPartial() but you didn't mention anything about using this.\nYou can find more at http://www.asp.net/mvc/videos/mvc-2/how-do-i/how-do-i-work-with-data-in-aspnet-mvc-partial-views \n\nA: If you want to divide a single webpage into multiple hmtl files you can do it by inserting frames. This is an old way of programming and you don't really see it these days but its efficient at doing what you are asking. \n\nA: Yes, this is highly recommended. You are trying to apply the DRY principle (see: http://en.wikipedia.org/wiki/Don't_repeat_yourself). It's an excellent idea to apply this to your HTML. You can achieve this using require, require_once, include, and include_once in PHP. If you want to get a bit fancier, take a look at templating systems like Smarty (see: http://www.smarty.net/)\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/17914717", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Select ScrollView element (Button) by code I would like to set my scrollView element seleted, using code.\nHere is what I have so far (commented code is not working):\npublic class Dictionary extends Activity implements Runnable, OnClickListener {\n //Candidates\n candidatesScrollView = (HorizontalScrollView) findViewById(R.id.activity_dictionary_horizontalScrollView1);\n\n candidatesButtons = new ArrayList\n

    \n
    \n\nentonces quiero que se vean los registros que tengo almacenados en la base de datos y de paso poderlos guardar con el form\nagrego captura de como se ve en la pantalla\n\n\nA: Realmente tu c\u00f3digo no es err\u00f3neo. Pero implementas malas pr\u00e1cticas al mezclar el estilo orientado a objetos: $query = $mysqli -> query (\"SELECT * FROM generales\"); y el estilo procedural: while ($valores = mysqli_fetch_array($query)) {. Esto es desaconsejado1, porque produce un c\u00f3digo confuso y revela poco rigor en el estilo de programaci\u00f3n. Dado que el estilo orientado a objetos es m\u00e1s sencillo y m\u00e1s claro, vamos a optar por \u00e9l en la respuesta.\nEl motivo por el que tu c\u00f3digo no estar\u00eda funcionando es porque faltan controles. En una consulta deber\u00edas verificar siempre lo siguiente:\n\n*\n\n*Que hay conexi\u00f3n\n\n*Que no hay error en la consulta (en una consulta del tipo SELECT podr\u00eda haber errores de sintaxis, en consultas de otro tipo puede haber errores de violaci\u00f3n de restricciones como PK duplicada u otras)\n\n*Que hay registros (en una consulta del tipo SELECT como la de este c\u00f3digo)\n\nEl problema es que se suele programar pensando que todo saldr\u00e1 bien (a lo que yo llamo programaci\u00f3n optimista y que es un error de concepto que produce programas d\u00e9biles). Hay que programar pensando que cualquier cosa puede salir mal (programaci\u00f3n pesimista) y la tarea del programador es responder cuando algo salga mal. Ese estilo de programaci\u00f3n produce un c\u00f3digo robusto a prueba de todo lo que salga mal.\nPropongo esto:\n
    \n

    Seleccione un pais del siguiente men\u00fa:

    \n

    Paises:\n \n \n

    \n
    \n\nAhora tendr\u00e1s en el option los valores obtenidos o un mensaje con lo que haya ocurrido. Como ya dije en comentarios del c\u00f3digo, podr\u00edas implementar tu propia pol\u00edtica de errores, en la cual decidir\u00edas no llenar el select en caso de error y mostrar en alg\u00fan contenedor (un div u otro) un mensaje de error o lo que quieras.\n\nNotas\n\n*\n\n*En mi respuesta a la pregunta Diferencia entre new mysqli y mysqli_connect he tratado de explicar ese problema bas\u00e1ndome en la documentaci\u00f3n. Realmente la mezcla de estilos no produce c\u00f3digo err\u00f3neo, simplemente es una mala pr\u00e1ctica por lo que se explica en la respuesta.\n\n\nA: Veo que andas un poco confuso. Como te he escrito en el comentario, no es buena pr\u00e1ctica mezclar los estilos a la hora de trabajar con nuestra Base de Datos.\nAun as\u00ed, faltan detalles en tu c\u00f3digo para poder ver donde esta tu fallo preciso, siempre es bueno ejecutar nuestra consulta en el phpMyAdmin y ver su trae resultados y as\u00ed verificar que est\u00e1 formado correctamente. \nSELECT * FROM generales\nTambi\u00e9n te aconsejo que compruebas tu conexi\u00f3n lanzando alg\u00fan mensaje. \nif ($mysqli->connect_errno) { #mensaje de error }\n\n\nSupongamos que tu conexi\u00f3n est\u00e1 formado al estilo objeto :\n$mysqli = new mysqli(\"localhost\", \"mi_usuario\", \"mi_contrase\u00f1a\", \"nombre_bd\");\n\nEjemplo pr\u00e1ctico\nconnect_errno) {\n printf(\"Conexi\u00f3n fallida: %s\\n\", $mysqli->connect_error);\n exit();\n}\n\n$consulta = \"SELECT * FROM generales\";\n\nif ($resultado = $mysqli->query($consulta)) {\n\n /* obtener un array asociativo */\n while ($valores = $resultado->fetch_assoc()) {\n echo \"\";\n }\n\n /* liberar el conjunto de resultados */\n $resultado->free();\n}\n\nAun asi te aconsejo usar sentencias preparadas.\nEjemplo sentencia preparada\n/* La conexi\u00f3n */\n$mysqli = new mysqli(\"localhost\", \"mi_usuario\", \"mi_contrase\u00f1a\", \"nombre_bd\");\n\n/* Consulta */\n$consulta = \"SELECT id,departamento FROM generales\";\n\n/* crear una sentencia preparada */\n$sentencia = $mysqli->prepare($consulta);\n\n/* ejecutar la consulta */\nif (!$sentencia->execute()) {\n echo \"Fall\u00f3 la ejecuci\u00f3n: (\" . $sentencia->errno . \") \" . $sentencia->error;\n}\n\n/* almacenar el resultado */\n$sentencia->store_result();\n\n/* Comprobar que existen registros */\nif ($sentencia->num_rows > 0) {\n /* vincular las variables de resultados */\n $sentencia->bind_result($id,$departamento);\n\n /* obtener el valor */\n while ($sentencia->fetch() ) {\n echo \"\";\n }\n } else { # Mensaje, no existen resultados en BD }\n\n /* cerrar la sentencia */\n $sentencia->close();\n\nTe dejo un enlace de como evitar la inyeccion SQL en PHP.\n", "meta": {"language": "es", "url": "https://es.stackoverflow.com/questions/385843", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: What adverb can I use to describe a slap that intends to get someone's attention? \n\"Listen to me,\" Samuel says, swatting the side of Cal's face '_____'.\n\nIt's not a playful or deliberately hurtful slap. It's somewhere in the middle - irritated. Considering the character's personalities, it's rather a gentle gesture for them but shocking enough to say 'get ahold of yourself!'\nIf not an adverb, how would you word this?\n\nA: I agree with @YosefBaskin. A strong verb is better than an adverb or adjective. Swat, tap, slap, etc.\nYou can also phase it more suscinctly, e.g.\n\u201cListen to me!\u201d Samuel swatted Cal's cheek. \u201c...\nYou're writing in the present tense (says vs said) which seems to be in vogue at the moment but is tricky to do because it can lead to writing that sounds like a laundry list of actions.\nAnother thing to consider is who your point of view character is. If it's Samuel or Cal, you have an opportunity to give internals as a way to convey what the intent of the slap was or how it was received.\n\nA: Since the purpose of the slap is to to say Get ahold of yourself! or Snap out of it!, you could use an adverb that helps conveys this purpose and let the intensity be intuited from the purpose:\n\n\"Listen to me,\" Samuel says, swatting the side of Cal's face\nabruptly.\"\n\nabruptly (adv.)\n\nIn an abrupt manner: in a sudden and unexpected way\nHe left abruptly.\nThe car swerved abruptly onto the exit ramp. m-w\n\nabrupt (adj.)\n\nCharacterized by or involving action or change without preparation or\nwarning: sudden and unexpected m-w\n\n\nA: The adverb \"enticingly\" might correspond to what you are lookinng for.\nFrom SOED\n\nentice v.t. Persuade or attract by the offer of pleasure or advantage\nenticingly adv. in an enticing manner\n\n", "meta": {"language": "en", "url": "https://english.stackexchange.com/questions/550417", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Writing unit tests that work with the DOM I have some functionality that works with the DOM, specifically dealing with resizing elements. I looked over the Unit Testing documentation here and couldn't find anything on doing this. Is it possible? Is there any existing documentation that shows how to do it?\n\nA: Try DumpRenderTree - headless chrome which outputs a textual version of layout.\neg:\nContent-Type: text/plain\nlayer at (0,0) size 808x820\n RenderView at (0,0) size 800x600\nlayer at (0,0) size 800x820\n RenderBlock {HTML} at (0,0) size 800x820\n RenderBody {BODY} at (8,8) size 784x804\n RenderHTMLCanvas {CANVAS} at (0,0) size 800x800 [bgcolor=#808080]\n RenderText {#text} at (0,0) size 0x0\n#EOF\n#EOF\n\nKevin Moore's blog post \"Headless Browser Testing with Dart\" explains the details (and the above snippet is taken from that)\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/14987852", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Is $\\sigma$-finiteness necessary for the existence and uniqueness of product measure? Let $(X,\\mathfrak{B}_X,\\mu_X)$ and $(Y,\\mathfrak{B}_Y,\\mu_Y)$ be $\\sigma$-finite measure spaces. Then there exists a unique measure $\\mu_X\\times\\mu_Y$ on $\\mathfrak{B}_X\\times\\mathfrak{B}_Y$ that obeys $\\mu_X\\times\\mu_Y(E\\times F)=\\mu_X(E)\\times\\mu_Y(F)$ whenever $E\\in \\mathfrak{B}_X$ and $F\\in \\mathfrak{B}_Y$.\nThat is the existence and uniqueness of product measure.\nI want to ask if I remove condition\"$\\sigma$-finite\", is the conclusion still correct? If not, please give a counterexample.\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/595601", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: C# Object reference not set to an instance of an object. Instantiating Class within a List? public class OrderItem\n{\n public string ProductName { get; private set; }\n public decimal LatestPrice { get; private set; }\n public int Quantity { get; private set; }\n public decimal TotalOrder { get {return LatestPrice * Quantity;}}\n\n public OrderItem(string name, decimal price, int quantity)\n {\n\n }\n\n public OrderItem(string name, decimal price) : this(name, price, 1)\n {\n\n }\n}\n\nAbove is the class, just for some background.\npublic void AddProduct(string name, decimal price, int quantity)\n{\n lstOrderitem.Add(new OrderItem(name, price, quantity)); \n}\n\nOn the code inside the AddProduct method is where I am getting the error stated in the title. \nI'm just trying to instantiate the class and add it to a collection to be displayed in a listbox on my form program. \nThe \"AddProduct\" will be called on a button click event \n\nError = NullReferenceException - Object reference not set to an instance of an object.\n\nI was wondering if anybody knew why this was happening since I thought that since I am making a NEW instance of the class while adding it to the list that it would have something to reference too. Thank you if anybody knows what the problem is.\nEdit\n public List lstOrderitem{ get; private set; }\n public int NumberOfProducts { get; private set; }\n public decimal BasketTotal { get; private set; }\n\n public ShoppingBasket()\n {\n //List lstOrderitem = new List();\n }\n\n public void AddProduct(string name, decimal price, int quantity)\n {\n lstOrderitem.Add(new OrderItem(name, price, quantity));\n\n\n }\n\n\nA: It looks like you didn't initialize your reference lstOrderitem. Debug your code if your references value is null, you need to initialize lstOrderitem before using it.\n\nA: You should initialize lstOrderitem property in the constructor, like this:\nEDIT\npublic MyClass() {\n lstOrderitem = new List();\n}\n\nP.S. Microsoft suggests starting the names of your properties in capital letters, to avoid confusion with member variables, which should be named starting with a lowercase letter.\n\nA: It looks like you didn't initialize your reference lstOrderitem. Debug your code if your reference value is null, you need to initialize lstOrderitem before using it.\npublic MyClass() {\n lstOrderitem = new List();\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/8701846", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "11"}} {"text": "Q: Can we say anything about $\\nu_p(x^n-y^n)$ if $p\\nmid x-y$? I know about the LTE lemma which says the following: If $p$ is a prime and $x,y,n$ are natural numbers with $p\\nmid xy$ and $p\\mid x-y$, then\n$$ \\nu_p(x^n-y^n)=\\nu_p(x-y)+\\nu_p(n),$$\nwhere $\\nu_p(n)$ is the multiplicity of $p$ in the prime factorisation of $n$.\nI was wondering if we can make any statements about $\\nu_p(x^n-y^n)$ if the conditions of the lemma do not hold; it is quite easy to reduce the case $p\\mid xy$ to the case $p\\nmid xy$, but I cannot immediately see how to make any statements about $\\nu_p(x^n-y^n)$ in the case where $p\\nmid xy$ and $p\\nmid x-y$.\nCan anyone offer any useful conclusions concerning $\\nu_p(x^n-y^n)$ in this particular case or is it impossible to make any general statements here?\n\nA: (LTE in the form you stated it requires that $p$ be odd.)\nAs Greg Martin says in the comments, if $p \\nmid xy$ then $p \\mid x^n - y^n$ iff $\\left( \\frac{x}{y} \\right)^n \\equiv 1 \\bmod p$. The set of $n$ for which this occurs consists of multiples of the order of $\\frac{x}{y} \\bmod p$, which can be any divisor of $p - 1$. If we write $d$ for the order, then information about $\\nu_p(x^n - y^n)$ for $d \\mid n$ can be obtained by applying LTE to $x' = x^d, y' = y^d$. The conclusion is that if $d \\mid n$ (and $p$ is odd) then\n$$\\nu_p(x^n - y^n) = \\nu_p(x^d - y^d) + \\nu_p \\left( \\frac{n}{d} \\right)$$\nand if $d \\nmid n$ then $\\nu_p(x^n - y^n) = 0$.\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/3926731", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Is there a way to make app engine turn off when no traffic I am currently using App Engine in Google Cloud with Docker to handle Mux Video requests. The problem is I am being charged over $40 when the app is in development and there is virtually no traffic on the app. Is there a way to turn off the App Engine when no requests are being sent so the hours of operation are less or this not possible with app Engine? I am quite new to App Engine.\nruntime: custom\nenv: flex\n\nmanual_scaling:\n instances: 1\nresources:\n cpu: 1\n memory_gb: 0.5\n disk_size_gb: 10\n\n\nA: No, you can't scale to 0 the Flex instances. It's the main problem of the flex instances.\nYou have to replace the current service by a APp Engine standard service version that can scale to 0 and stop paying.\n\nIf your application doesn't run background processes, and the request handling doesn't take more than 60 minutes, I strongly recommend you to have a look to Cloud Run\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/70173388", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: \"save link as\" bulk download I have a list of links in an html file and I want to perform a \"save link as\" for all of them so it downloads all the files into one folder.\nIs this possible? I need to do this from within firefox or chrome as I am required to be logged in to the website,\nThanks,\nA\n\nA: Whilst it's possible to do this with curl (including the login), I would recommend using a browser extension. Flashgot for Firefox is excellent, you can tell it to download all files of a certain extension, or do things like pattern matching.\nhttp://flashgot.net/\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/8112283", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Why do we need to define a function to call another function? In the implementation of ResNet architecture in Pytorch I encountered the code below which is from line 264 til 283:\ndef _forward_impl(self, x: Tensor) -> Tensor:\n # See note [TorchScript super()]\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n x = self.fc(x)\n\n return x\n\ndef forward(self, x: Tensor) -> Tensor:\n return self._forward_impl(x)\n\nWhat is the purpose of _forward_impl? Why didn't the coder bring what is happening inside _forward_impl into forward itself and getting ride of _forward_impl? I see _forward_impl looks like a private method, since it has underscore at the start of its name, however, I cannot yet see what the purpose of _forward_impl is.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/72111540", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: How to read logging configuration from appsettings.json in .net Core 2.2 In .net Core 2.1 it was done like this\nvar loggingConfig = configuration.GetSection(\"Logging\");\nloggerFactory.AddConsole(loggingConfig);\n\nI have moved it to ConfigureServices and now I get \n\nError CS1503 Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action Microsoft.Extensions.Logging.Console.ConsoleLoggerOptions' \n\n\nA: Base on this you may have to change the way you are configuring your application:\nvar webHost = new WebHostBuilder()\n .UseKestrel()\n .UseContentRoot(Directory.GetCurrentDirectory())\n .ConfigureAppConfiguration((hostingContext, config) =>\n {\n var env = hostingContext.HostingEnvironment;\n config.AddJsonFile(\"appsettings.json\", optional: true, reloadOnChange: true)\n .AddJsonFile($\"appsettings.{env.EnvironmentName}.json\", \n optional: true, reloadOnChange: true);\n config.AddEnvironmentVariables();\n })\n .ConfigureLogging((hostingContext, logging) =>\n {\n logging.AddConfiguration(hostingContext.Configuration.GetSection(\"Logging\"));\n logging.AddConsole();\n logging.AddDebug();\n logging.AddEventSourceLogger();\n })\n .UseStartup()\n .Build();\n\n webHost.Run();\n\n1 Microsoft ASP.NET Core 2.2 Logging documentation\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/54321456", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "8"}} {"text": "Q: Facebook Likeview is not working I have implemented Like as suggested on Facebook developer site \nI just added Likeview and set Object id for post code is as below\nlikeView = (LikeView)findViewById(R.id.like_view);\n likeView.setObjectId(\"https://www.facebook.com/karan.raj.5070276/posts/396696657159566\");\n\nMy layout file has LikeView widget\n\n\nOn clicking it just opens Dialog for sometime and it disappears without any action\nand In log-cat I finds error message like\n\"Like dialog is only available to developers and tester\"\nWhat should I do In my Facebook app. Should I add Roles for developer and tester \nPlease help any help will be appreciated \n\nA: Login your facebook with same user which you have created facebook app with. This error appeared because you logged in facebook with other user.\nNote: By default Facebook app app is in development mode and can only be used by app admins, developers and testers.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/27821911", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: Offsets to create n-sided shape around starting point in Javascript I would like to find an function where, given a starting point (x, y) P, a radius r, and an integer n, I can generate offsets from P to create n well-placed points to create a shape (within a circle of radius r) around P.\nFor example:\nFor P = {x: 0, y: 0}, r = 25.\nWhere \"offsets\" is the return value of the desired function...\nLet n = 0:\n offsets = [];\nLet n = 1:\n // Note 25 here is simply P.x + r, where P.x = 0 for simplicity's sake.\n // So x: 25 is actually x: P.x + 25\n // And y: 0 is actually y: P.y + 0\n // I've kept the simplified notation here and below for readability.\n offsets = [{x: 25, y: 0}];\nLet n = 2: // Line\n offsets = [{x: 25, y: 0}, {x: -25, y: 0}];\nLet n = 3: // Triangle\n offsets = [{x: 25, y: 0}, {x: -25, y: 0}, {x: 0, y: 25}];\nLet n = 4: // Square\n offsets = [\n {x: 25, y: 0},\n {x: -25, y: 0},\n {x: 0, y: 25},\n {x: 0, y: -25}\n ];\nLet n = 5: // Pentagon\n offsets = [\n {x: 25, y: 0},\n {x: -25, y: 0},\n {x: 0, y: 25},\n {x: -12.5, y: -25},\n {x: 12.5, y: -25}\n ];\n\n.... and so on.\n\nA: Just sample a circle:\nallocate offset array\nvar angle = 2 * Math.PI / n;\nfor(var i = 0; i < n; ++i)\n offsets[i] = {x: r * Math.cos(i * angle), y: r * Math.sin(i * angle)};\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/33378118", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Why is setuid not running as the owner? I am currently trying to learn what the special bits in file permissions do but am currently stuck trying to understand what the setuid bit does. From all the online resources it says:\n\nCommonly noted as SUID, the special permission for the user access level has a single function: A file with SUID always executes as the user who owns the file, regardless of the user passing the command\n\nHowever in a simple experiment this just doesn't appear to be true (unless I have misunderstood and am doing something wrong?) i.e.\nmkdir /tmp/foo\nmkdir /tmp/foo/bar\nchmod 0700 /tmp/foo/bar # Restrict directory so only current user can access\necho content > /tmp/foo/bar/baz.txt # Create content in the restricted directory\necho \"ls /tmp/foo/bar\" > /tmp/foo/myscript.sh # Script to access content of restricted directoy\nchmod 4777 /tmp/foo/myscript.sh # Set setuid bit so the script runs as current user\n/tmp/foo/myscript.sh # Show it works when run as current user\n\n#> baz.txt\n\nsu bob # Switch to a new user\n/tmp/foo/myscript.sh # Run script again\n\n#> ls: cannot open directory '/tmp/foo/bar': Permission denied\n\nMy expectation was that as the setuid bit was set the script should have been executed as the original user and as such should have had permissions to ls into the restricted directory. But instead I got a permissions denied error indicating that the script was not run as the original user.\nAny help into understanding what I'm doing wrong would be greatly appreciated. (example was run on zsh / ubuntu 20.04 / wsl2)\n\nA: The suid bit works only on binary executable programs, not on shell scripts. You can find more info here: https://unix.stackexchange.com/questions/364/allow-setuid-on-shell-scripts\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/69958788", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Managing users in the TFS work items \"Assigned To\" field So I know there have been a couple of posts around about this topic, but I don't think they've quite got to the bottom of it!\nSo my problem is that when I create a new work item in TFS, the users which I can assign it to include NT Authority\\Local Service (which is also the TFS service account). I'm not asking why, as I know that this field, by default is populated by the Valid Users group, and upon inspecting the groups, I can see that the group permissions hierarchy looks like this:\n -> Valid Users\n -> Project Collection Admistrators\n -> Project Collection Service Accounts\n -> NT Authority\\Local Service\n\nAnd you can't change anything in the project collection service accounts, so surely by default, everyone has this user in the assign to field? So does this mean everyone accepts it, or do they modify their process templates to filter it out (see the blog here)?\nJust seems a bit odd to me that by default is isn't filtered out already! Clearly I don't want to be removing this from any permissions either (even if I could) as I'm worried it'll cause problems later.\nSo is filtering in the process template the only way (which looks like a bit of effort to maintain), or is there a simpler way?\n\nA: Under TFS2008, you do need to do it this way. Under 2010, there might be an \"exclude\", but I'm not able to check that at the moment.\nTo keep from having a whole lot of maintenance, instead of listing each user individually, what we did was just pared down the list from \"Valid Users\" to the \"Moderators\" and \"Contributors\". We know that we can control those groups without affecting service permissions:\n \n \n \n \n \n \n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/3422653", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "5"}} {"text": "Q: Anybody who have used Django and JQuery Autocomplete? Is there anybody out there who have used Django and JQuery Autocomplete? Am stuck on this and i will highly appreciate to see how someone else has done this! especially without using the AutocompleteWidget!\nGath\n\nA: There are some easy to follow examples in this GitHub mirror of django-autocomplete.\n\nA: some time ago I put together a small tutorial on this, you might find that useful... it's here\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/738529", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "7"}} {"text": "Q: What do you call a \"de-amplifier\" device(is there such a thing)? So if an amplifier is an electronic circuit(/device) that boosts the voltage and/or power of an AC electrical signal, what do you call such a device that decrease the voltage without increasing the current or better yet reduces the power of an electrical signal? \nWhat I'm thinking of is essentially an amplifier with a voltage or power gain less than unity(in terms of magnitude).\nSuch a device might be used at a power substation to reduce both the voltage and current from a HV power source. Or when measuring a very high voltage current or signal(with high wattage) by means of a computer where the signal carries enough power to fry the low-power components. As step-down transformer reduces the voltage but increases the current, so I'm not talking about those.\n\nA: Such a device could be called an attenuator (defined as \"an electronic device that reduces the power of a signal without appreciably distorting its waveform.\")[1].\nFor specialized RF situations, there are specific designs based usually around passives of carefully-selected values for a given frequency or frequency range.\nFor low-frequency applications, or where extreme precision isn't necessary, it's often common (at least for hobbyists, not sure about professional applications) to use simple voltage dividers with the divided voltage connected an an analog input, for example on a microcontroller.\n", "meta": {"language": "en", "url": "https://electronics.stackexchange.com/questions/205330", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Running a docker container which uses GPU from kubernetes fails to find the GPU I want to run a docker container which uses GPU (it runs a cnn to detect objects on a video), and then run that container on Kubernetes.\nI can run the container from docker alone without problems, but when I try to run the container from Kubernetes it fails to find the GPU.\nI run it using this command:\nkubectl exec -it namepod /bin/bash\n\nThis is the problem that I get:\nkubectl exec -it tym-python-5bb7fcf76b-4c9z6 /bin/bash\nkubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.\nroot@tym-python-5bb7fcf76b-4c9z6:/opt# cd servicio/\nroot@tym-python-5bb7fcf76b-4c9z6:/opt/servicio# python3 TM_Servicev2.py \n Try to load cfg: /opt/darknet/cfg/yolov4.cfg, weights: /opt/yolov4.weights, clear = 0 \nCUDA status Error: file: ./src/dark_cuda.c : () : line: 620 : build time: Jul 30 2021 - 14:05:34 \n\n CUDA Error: no CUDA-capable device is detected\npython3: check_error: Unknown error -1979678822\nroot@tym-python-5bb7fcf76b-4c9z6:/opt/servicio#\n\nEDIT.\nI followed all the steps on the Nvidia docker 2 guide and downloaded the Nvidia plugin for Kubernetes.\nhowever when I deploy Kubernetes it stays as \"pending\" and never actually starts. I don't get an error anymore, but it never starts.\nThe pod appears like this:\ngpu-pod 0/1 Pending 0 3m19s\n\nEDIT 2.\nI ended up reinstalling everything and now my pod appears completed but not running. like this.\ndefault gpu-operator-test 0/1 Completed 0 62m\n\nAnswering Wiktor.\nwhen I run this command:\nkubectl describe pod gpu-operator-test \n\nI get:\nName: gpu-operator-test\nNamespace: default\nPriority: 0\nNode: pdi-mc/192.168.0.15\nStart Time: Mon, 09 Aug 2021 12:09:51 -0500\nLabels: \nAnnotations: cni.projectcalico.org/containerID: 968e49d27fb3d86ed7e70769953279271b675177e188d52d45d7c4926bcdfbb2\n cni.projectcalico.org/podIP: \n cni.projectcalico.org/podIPs: \nStatus: Succeeded\nIP: 192.168.10.81\nIPs:\n IP: 192.168.10.81\nContainers:\n cuda-vector-add:\n Container ID: docker://d49545fad730b2ec3ea81a45a85a2fef323edc82e29339cd3603f122abde9cef\n Image: nvidia/samples:vectoradd-cuda10.2\n Image ID: docker-pullable://nvidia/samples@sha256:4593078cdb8e786d35566faa2b84da1123acea42f0d4099e84e2af0448724af1\n Port: \n Host Port: \n State: Terminated\n Reason: Completed\n Exit Code: 0\n Started: Mon, 09 Aug 2021 12:10:29 -0500\n Finished: Mon, 09 Aug 2021 12:10:30 -0500\n Ready: False\n Restart Count: 0\n Limits:\n nvidia.com/gpu: 1\n Requests:\n nvidia.com/gpu: 1\n Environment: \n Mounts:\n /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-9ktgq (ro)\nConditions:\n Type Status\n Initialized True \n Ready False \n ContainersReady False \n PodScheduled True \nVolumes:\n kube-api-access-9ktgq:\n Type: Projected (a volume that contains injected data from multiple sources)\n TokenExpirationSeconds: 3607\n ConfigMapName: kube-root-ca.crt\n ConfigMapOptional: \n DownwardAPI: true\nQoS Class: BestEffort\nNode-Selectors: \nTolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s\n node.kubernetes.io/unreachable:NoExecute op=Exists for 300s\nEvents: \n\nI'm using this configuration file to create the pod\napiVersion: v1\nkind: Pod\nmetadata:\n name: gpu-operator-test\nspec:\n restartPolicy: OnFailure\n containers:\n - name: cuda-vector-add\n image: \"nvidia/samples:vectoradd-cuda10.2\"\n resources:\n limits:\n nvidia.com/gpu: 1\n\n\nA: Addressing two topics here:\n\n*\n\n*The error you saw at the beginning:\n\n\nkubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.\n\nMeans that you tried to use a deprecated version of the kubectl exec command. The proper syntax is:\n$ kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...]\n\nSee here for more details.\n\n\n*According the the official docs the gpu-operator-test pod should run to completion:\n\nYou can see that the pod's status is Succeeded and also:\n\n State: Terminated\n Reason: Completed\n Exit Code: 0\n\nExit Code: 0 means that the specified container command completed successfully.\nMore details can be found in the official docs.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/68653976", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: cant get android sqlite select statement to work I'm trying to select the items that have expired in my database but nothing is ever returned. I've tried the following:\nselect * from productTable where columnExpiration < date( currentDate)\n\nAll dates in the format yyyy-mm-dd\nWhen that didn't work I tried:\nSelect* from productTable where columnExpiration < currentDate\n\nAny suggestions? This is really starting to drive me crazy. Thanks\n\nA: Try here, which has already been asked, and has a solution:\nuse Datetime() to format your dates before comparison.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/7898612", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to find the number of each elements in the row and store the mean of each row in another array using C#? I am using the below code to read data from a text file row by row. I would like to assign each row into an array. I must be able to find the number or rows/arrays and the number of elements on each one of them.\nI would also like to do some manipulations on some or all rows and return their values.\nI get the number of rows, but is there a way to to loop something like:\n *for ( i=1 to number of rows)\n do\n mean[i]<-row[i]\n done\n return mean*\n\n\nvar data = System.IO.File.ReadAllText(\"Data.txt\");\n\nvar arrays = new List();\n\nvar lines = data.Split(new[] {'\\r', '\\n'}, StringSplitOptions.RemoveEmptyEntries);\n\nforeach (var line in lines)\n{\n var lineArray = new List();\n\n foreach (var s in line.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries))\n {\n lineArray.Add(Convert.ToSingle(s));\n }\n arrays.Add(lineArray.ToArray());\n\n}\n\nvar numberOfRows = lines.Count();\nvar numberOfValues = arrays.Sum(s => s.Length);\n\n\nA: var arrays = new List();\n//....your filling the arrays\nvar averages = arrays.Select(floats => floats.Average()).ToArray(); //float[]\nvar counts = arrays.Select(floats => floats.Count()).ToArray(); //int[]\n\n\nA: Not sure I understood the question. Do you mean something like\nforeach (string line in File.ReadAllLines(\"fileName.txt\")\n{\n...\n}\n\n\nA: Is it ok for you to use Linq? You might need to add using System.Linq; at the top. \nfloat floatTester = 0;\nList result = File.ReadLines(@\"Data.txt\")\n .Where(l => !string.IsNullOrWhiteSpace(l))\n .Select(l => new {Line = l, Fields = l.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) })\n .Select(x => x.Fields\n .Where(f => Single.TryParse(f, out floatTester))\n .Select(f => floatTester).ToArray())\n .ToList();\n\n// now get your totals\nint numberOfLinesWithData = result.Count;\nint numberOfAllFloats = result.Sum(fa => fa.Length);\n\nExplanation:\n\n\n*\n\n*File.ReadLines reads the lines of a file (not all at once but straming)\n\n*Where returns only elements for which the given predicate is true(f.e. the line must contain more than empty text)\n\n*new { creates an anonymous type with the given properties(f.e. the fields separated by comma)\n\n*Then i try to parse each field to float\n\n*All that can be parsed will be added to an float[] with ToArray()\n\n*All together will be added to a List with ToList()\n\nA: Found an efficient way to do this. Thanks for your input everybody!\nprivate void ReadFile()\n {\n var lines = File.ReadLines(\"Data.csv\");\n var numbers = new List>();\n var separators = new[] { ',', ' ' };\n /*System.Threading.Tasks.*/\n Parallel.ForEach(lines, line =>\n {\n var list = new List();\n foreach (var s in line.Split(separators, StringSplitOptions.RemoveEmptyEntries))\n {\n double i;\n\n if (double.TryParse(s, out i))\n {\n list.Add(i);\n }\n }\n\n lock (numbers)\n {\n numbers.Add(list);\n }\n });\n\n var rowTotal = new double[numbers.Count];\n var rowMean = new double[numbers.Count];\n var totalInRow = new int[numbers.Count()];\n\n for (var row = 0; row < numbers.Count; row++)\n {\n var values = numbers[row].ToArray();\n\n rowTotal[row] = values.Sum();\n rowMean[row] = rowTotal[row] / values.Length;\n totalInRow[row] += values.Length;\n }\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/11541076", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Audio not working in html5 I was adding audio to an HTML5 website. The audio works fine with FireFox and IE but does not show up and play in FireFox. Any ideas why and solution? Thanks in advance.\n\n\n\n\nUntitled Document\n\n\n\n\n\n\n\n\nA: Firefox doesn't support MP3. It won't show the fallback message because it supports the audio tag.\nhttps://developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements#MPEG_H.264_(AAC_or_MP3)\n\nA: You can't play MP3 files with such a code in Firefox.\nSee https://developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/10667932", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "8"}} {"text": "Q: TextInfo ToTitleCase missing in Xamarin Forms I am trying to convert a string to title case in my cross platform Xamarin app using the following code.\nstring rawString = \"this is a test string\";\nSystem.Globalization.TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;\nstring formattedString = textInfo.ToTitleCase(rawString);\n//Expected output is \"This Is A Test String\"\n\nI cannot run this code as the compiler insists that there is no definition for ToTitleCase in TextInfo. However the documentation says otherwise.\nI am using Visual Studio 2017 with the latest NuGet packages for everything (including all .Net packages and Xamarin.Forms)\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/50333596", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: php \u0440\u0435\u0433\u0443\u043b\u044f\u0440\u043d\u043e\u0435 \u0432\u044b\u0440\u0430\u0436\u0435\u043d\u0438\u0435 \u041a\u0430\u043a \u043d\u0430\u0439\u0442\u0438 \u0438 \u0437\u0430\u043c\u0435\u043d\u0438\u0442\u044c \u0432 \u0441\u0442\u0440\u043e\u043a\u0435 \u0432\u0441\u0435 \u043f\u043e\u0434\u0441\u0442\u0440\u043e\u043a\u0438 \u043f\u043e\u0441\u043b\u0435 ( = ) \u043a\u043e\u043d\u0435\u0446 \u043f\u043e\u0434\u0441\u0442\u0440\u043e\u043a\u0438 \u043f\u0435\u0440\u0435\u0434 \u043f\u0435\u0440\u0435\u043d\u043e\u0441\u043e\u043c \u0441\u0442\u0440\u043e\u043a\u0438 ( \\r \u0438\u043b\u0438 \\n )\n\u0425\u043e\u0447\u0443 \u043c\u0435\u043d\u044f\u0442\u044c \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0435 \u0432 \u0444\u0430\u0439\u043b\u0435(\u043f\u0440\u0438\u043c\u0435\u0440):\nlang=en,ru\n\npassword=6fbde3e2135f10ee603ff6f59bc97d4b0a4d4e9a\n\nsession=\n\npass_complexity=500000\n\npass_complexity_js=15000\n\n\nA: // \u0434\u043b\u044f \u0447\u0442\u0435\u043d\u0438\u044f \u0434\u0430\u043d\u043d\u044b\u0445\n$file = file('yourfile.txt');\n$arrConf = array();\n\nforeach($file as $_file) {\n if(trim($_file)!=\"\") {\n $tmp = explode('=',$_file);\n $arrConf[trim($tmp[0])] = trim($tmp[1]);\n }\n}\n\n// \u043c\u043e\u0436\u0435\u043c \u043f\u043e\u043c\u0435\u043d\u044f\u0442\u044c \u0441\u0434\u0435\u0441\u044c \n$arrConf['lang'] = 'fr,ru';\n\n// \u0438 \u0437\u0430\u043f\u0438\u0441\u0430\u0442\u044c \u043e\u0431\u0440\u0430\u0442\u043d\u043e\n$resultCompile = '';\nforeach($arrConf as $_key => $_val) {\n $resultCompile = \"$_key=$_val\\n\"; \n}\n\nfile_put_contents('yourfile.txt',$resultCompile);\n\n\u0421 \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043d\u0438\u0435\u043c \u0440\u0435\u0433\u0443\u043b\u044f\u0440\u043e\u043a \u0435\u0441\u0442\u044c \u0434\u0432\u0430 \u043c\u043e\u043c\u0435\u043d\u0442\u0430:\n\n\n*\n\n*\u041d\u0430\u0433\u0440\u0443\u0437\u043a\u0430 \u043d\u0430 \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u0440\n\n*\u0412\u0435\u043b\u0438\u043a\u0430 \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u044c \u043e\u0448\u0438\u0431\u043a\u0438 \u043f\u0430\u0442\u0435\u0440\u043d\u0430, \u0432 \u043a\u043e\u043d\u0446\u0435 \u043a\u043e\u043d\u0446\u043e\u0432 \u043a\u043e\u043d\u0435\u0446 \u0441\u0442\u0440\u043e\u043a\u0438 \\n\\r \u0438 \u0442.\u0434.\n\n\n\u041f\u043b\u044e\u0441\u044b \u0442\u0430\u043a\u043e\u0433\u043e \u043f\u043e\u0434\u0445\u043e\u0434\u0430 \u0443 \u043d\u0430\u0441 \u0435\u0441\u0442\u044c \u043a\u043e\u043d\u043a\u0440\u0435\u0442\u043d\u0430\u044f \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u0430\u044f, \u043f\u043e \u043a\u043e\u0442\u043e\u0440\u043e\u0439 \u043c\u044b \u043c\u043e\u0436\u0435\u043c \u043e\u0431\u0440\u0430\u0442\u0438\u0442\u044c\u0441\u044f \u0438 \u043f\u0435\u0440\u0435\u0437\u0430\u043f\u0438\u0441\u0430\u0442\u044c \u0435\u0451. \n\u043f.\u0441. \u0423\u043a\u0430\u0436\u0438\u0442\u0435 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043d\u0438\u0435 \u0444\u0430\u0439\u043b\u0430? \u0432 php \u0435\u0441\u0442\u044c \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043d\u0438\u0435 \u0434\u043b\u044f \u0440\u0430\u0431\u043e\u0442\u044b \u0441 ini http://php.net/manual/ru/function.parse-ini-file.php\n\u0435\u0441\u043b\u0438 \u043e\u043d\u043e \u043f\u0440\u043e\u043a\u0430\u0442\u0438\u0442 \u0434\u043b\u044f \u043f\u0430\u0440\u0441\u0438\u043d\u0433\u0430 \u0432\u044b\u0448\u0435 \u0442\u043e \u043c\u043e\u0436\u043d\u043e \u043f\u0440\u0438\u0432\u0435\u0441\u0442\u0438 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0432 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0439 \u0432\u0438\u0434\n// \u0434\u043b\u044f \u0447\u0442\u0435\u043d\u0438\u044f \u0434\u0430\u043d\u043d\u044b\u0445\n$arrConf = parse_ini_file('yourfile.ini');\n\n// \u043c\u043e\u0436\u0435\u043c \u043f\u043e\u043c\u0435\u043d\u044f\u0442\u044c \u0441\u0434\u0435\u0441\u044c \n$arrConf['lang'] = 'fr,ru';\n\n// \u0438 \u0437\u0430\u043f\u0438\u0441\u0430\u0442\u044c \u043e\u0431\u0440\u0430\u0442\u043d\u043e\n$resultCompile = '';\nforeach($arrConf as $_key => $_val) {\n $resultCompile = \"$_key=$_val\\n\"; \n}\n\nfile_put_contents('yourfile.ini',$resultCompile);\n\n", "meta": {"language": "ru", "url": "https://ru.stackoverflow.com/questions/496704", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Group By and Sum Quantity by Direction Column Good Day guys is there a way for me to group by an item and sum its quantity using the direction column?\nI want to add new column positive_quantity (direction are 1, 4, 5)\nand negative_quantity (direction are 2, 3, 6)\nhere's my code:\nSELECT \n il.warehouse_id,\n w.code as warehouse_code,\n w.name as warehouse_name,\n il.item_id, \n i.code as item_code,\n i.name as item_name,\n il.lot, \n il.date_expiry, \n il.direction,\n il.location_id,\n //SUM(il.qty), as posive_quantity (base on direction 1, 4, 5)\n //SUM(il.qty), as negative_quantity (base on direction 2, 3, 6)\nFROM warehouses w\nINNER JOIN inventory_logs il\nON w.id = il.warehouse_id\nINNER JOIN items as i\nON il.item_id = i.id\nWHERE il.location_id IN (1,3) AND il.date_posted BETWEEN '2019-01-01' AND '2019-01-31'\nGROUP BY \nil.warehouse_id,\nil.item_id, \nil.lot, \nil.date_expiry, \nil.location_id,\ndirection\n\n\nhere is my desired output:\n\nThank you in advance. I have also tried using temporary table but it gives me error. like using the same temporary error.\n\nA: You can use conditional sum:\nSELECT \n il.warehouse_id,\n w.code as warehouse_code,\n w.name as warehouse_name,\n il.item_id, \n i.code as item_code,\n i.name as item_name,\n il.lot, \n il.date_expiry, \n il.location_id,\n sum( if( il.direction in (1,4,5), il.qty, 0 ) ) as positive_quantity,\n sum( if( il.direction in (2, 3, 6), il.qty, 0 ) ) as negative_quantity\nFROM warehouses w\nINNER JOIN inventory_logs il\nON w.id = il.warehouse_id\nINNER JOIN items as i\nON il.item_id = i.id\nWHERE il.location_id IN (1,3) AND il.date_posted BETWEEN '2019-01-01' AND '2019-01-31'\nGROUP BY \nil.warehouse_id,\nil.item_id, \nil.lot, \nil.date_expiry, \nil.location_id,\n\nBtw, your images dot match with the query. It is always best to post the question as text instead of an image, preferably as an SQLFiddle.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/58077607", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}} {"text": "Q: How can I use create a program that uses GDI+ 1.0 on XP and 1.1 on Vista/Win7 I know that if I use the features of GDI+ 1.1, the .EXE file won't run on Windows XP.\nI want to make a program that runs on Windows XP and Windows 7 both, and use the GDI+ 1.1 feature on Win7.\nIs there anyway to do this?\n\nA: A simple way to do it is to put your GDI+ 1.1 code in #ifdefs and compile it to two different DLLs -- one with the code and one without. Then at runtime load the DLL that will work. Maybe you could even attempt to load the 1.1 DLL and if that fails fall back to the 1.0 DLL.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/7398145", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: How to use \"-replace\" in Set-ADUser? I want to use PowerShell via my C# to modify Active Directory attributes. Here is my PowerShell command which I can use to replace an Active Directory attribute:\nSet-ADUser -Identity \"kchnam\" -Replace @{extensionAttribute2=\"Neuer Wert\"}\n\nHow can I add the @{extensionAttribute2=\"Neuer Wert\"} to my C# command?\nMy solution is not working:\nCommand setUser = new Command(\"Set-ADUser\");\nsetUser.Parameters.Add(\"Identity\", aduser);\nstring testadd = \"@{extensionAttribute2=\" + quote + \"Neuer Wert\" + quote + \"}\";\nsetUser.Parameters.Add(\"Replace\", testadd);\n\n\nA: In PowerShell that:\n@{extensionAttribute2=\"Neuer Wert\"}\n\nmeans a Hashtable literal, not just string. So, in C# you also have to create a Hashtable object:\nnew Hashtable{{\"extensionAttribute2\",\"Neuer Wert\"}}\n\nAlthough, that is not fully equivalent to PowerShell, since PowerShell create Hashtable with case insensitive key comparer. But, very likely, that you can use any collection implementing IDictionary, not just a Hashtable.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/31921187", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "4"}} {"text": "Q: Visual Studio Code, container: terminal hangs very long before prompt appears I'm using Visual Studio Code to develop within a Docker container (notably, mcr.microsoft.com/vscode/devcontainers/javascript-node:0-12).\nThis is the content of my settings.json file:\n{\n \"terminal.integrated.defaultProfile.linux\": \"zsh\",\n \"terminal.integrated.profiles.linux\": {\n \n \"bash\": {\n \"path\": \"/usr/bin/flatpak-spawn\",\n \"args\": [\n \"--host\",\n \"--env=TERM=xterm-256color\",\n \"bash\"\n ]\n }\n }\n}\n\nWhen I issue any command in the terminal, it executes correctly, but it takes very long for the prompt to appear again.\nWhat is causing this behaviour? How can the problem be solved?\n\nA: It turned out that the delay was due to a combination of:\n\n*\n\n*poor container's file system behaviour because bind-mount'ed to the local machine's one (Linux container on Windows machine)\n\n*project consisting of a large number of (small, actually) source files (~10,000)\n\n*git information displayed on the prompt\n\nTo solve the issue, I ended up disabling git's processing every time (as described at https://giters.com/ohmyzsh/ohmyzsh/issues/9848 ), by adding a postCreateCommand in devcontainer.json file.\nThis is the content of my devcontainer.json:\n\"postCreateCommand\": \"git config --global oh-my-zsh.hide-info 1 && git config --global oh-my-zsh.hide-status 1 && git config --global oh-my-zsh.hide-dirty 1\"\n\n\nA: With recent vscode devcontainers, I found that I needed to do something like this instead, as bash appears to be the default shell, instead of zsh.\n\"postCreateCommand\": \"git config --global codespaces-theme.hide-info 1 && git config --global codespaces-theme.hide-status 1 && git config --global codespaces-theme.hide-dirty 1\"\n\nSee: https://github.com/microsoft/vscode-dev-containers/issues/1196\nThere might be additional changes coming as well, based on https://github.com/devcontainers/features/pull/326\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/70861778", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: use vmalloc memory to do DMA? I'm writing a driver which need large memory. Let's say it will be 1GB at least. \nThe kernel version >= 3.10.\nDriver needs run in X86_64 and Arm platform.\nThe hardware may have IOMMU.\n\n\n*\n\n*This large memory will mmap to userspace.\n\n*Device use those memory to do DMA. Each DMA operation just write max 2KB size of data to those memory.\n\n\nMy Questions.\n\n\n*\n\n*vmalloc can give me large non-physical-continus pages. Can I use vmalloc get large memory to do DMA? I'm thinking use vmalloc_to_page to get page pointer then use page_to_phys to get physical address.\n\n*I found a info about \"vmalloc performance is lower than kmalloc.\" I'm not sure what it means.\nif I do vaddr = vmalloc(2MB) and kaddr = kmalloc(2MB), the function call of vmalloc will be slower than kmalloc because of memory remap. But is memory access in range [vaddr, vaddr+2MB) will slower than [kaddr, kaddr+2MB) ? The large memory will be created during driver init, so does vmalloc memory cause performance issue?\n\n*DMA needs dma_map_single to get dma_addr_t. I'm thinking use dma_map_single to get all the page's dma address at driver init. I will just use those dma address when driver need to do DMA. Can I do this to get some performance improvment?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/61092347", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: problem on $S_n$, quotient and isomorphism \nDoes there exist a finite group $G$ with normal subgroups $N_1$ and $N_2$ such that$N_1 \\cong S_5$, $N_2\\cong S_7$, $G/N_1\\cong S_{42}$ and $G/N_2\\cong S_{41}$?\n\nConsider $N_1 \"Query in KSQL\", I noticed only 1 of them populates the \"Field(s) you'd like to include in your STREAM\". The other 3 show up blank like so:\n\nI noticed the topic that was able to populate the KSQL fields has a surrogate int primary key called id whereas the ones that don't work have a natural string primary key called boxId e.g. \"ABC123\", if that has anything to do with it?\nWhat am I missing to get those fields to populate?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/59534357", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Python spark Dataframe to Elasticsearch I can't figure out how to write a dataframe to elasticsearch using python from spark. I followed the steps from here.\nHere is my code:\n# Read file\ndf = sqlContext.read \\\n .format('com.databricks.spark.csv') \\\n .options(header='true') \\\n .load('/vagrant/data/input/input.csv', schema = customSchema)\n\ndf.registerTempTable(\"data\")\n\n# KPIs\nkpi1 = sqlContext.sql(\"SELECT * FROM data\")\n\nes_conf = {\"es.nodes\" : \"10.10.10.10\",\"es.port\" : \"9200\",\"es.resource\" : \"kpi\"}\nkpi1.rdd.saveAsNewAPIHadoopFile(\n path='-',\n outputFormatClass=\"org.elasticsearch.hadoop.mr.EsOutputFormat\",\n keyClass=\"org.apache.hadoop.io.NullWritable\",\n valueClass=\"org.elasticsearch.hadoop.mr.LinkedMapWritable\",\n conf=es_conf)\n\nAbove code gives \n\nCaused by: net.razorvine.pickle.PickleException: expected zero\n arguments for construction of ClassDict (for\n pyspark.sql.types._create_row)\n\nI also started the script from:\n spark-submit --master spark://aggregator:7077 --jars ../jars/elasticsearch-hadoop-2.4.0/dist/elasticsearch-hadoop-2.4.0.jar /vagrant/scripts/aggregation.py to ensure that elasticsearch-hadoop is loaded\n\nA: For starters saveAsNewAPIHadoopFile expects a RDD of (key, value) pairs and in your case this may happen only accidentally. The same thing applies to the value format you declare.\nI am not familiar with Elastic but just based on the arguments you should probably try something similar to this:\nkpi1.rdd.map(lambda row: (None, row.asDict()).saveAsNewAPIHadoopFile(...)\n\nSince Elastic-Hadoop provide SQL Data Source you should be also able to skip that and save data directly:\ndf.write.format(\"org.elasticsearch.spark.sql\").save(...)\n\n\nA: As zero323 said, the easiest way to load a Dataframe from PySpark to Elasticsearch is with the method\nDataframe.write.format(\"org.elasticsearch.spark.sql\").save(\"index/type\") \n\n\nA: You can use something like this:\ndf.write.mode('overwrite').format(\"org.elasticsearch.spark.sql\").option(\"es.resource\", '%s/%s' % (conf['index'], conf['doc_type'])).option(\"es.nodes\", conf['host']).option(\"es.port\", conf['port']).save()\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/39559121", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "5"}} {"text": "Q: Breaking url into multiple lines results in broken link in rendered PDF In a previous question, and with @Aditya's help I was able to break up URLs into multiple lines in my bibliography source file and still get the link to work.\nNow, I would like to do the same in my source .tex file, so I tried something similar as shown in the answer provided by @Aditya:\n\\setupinteraction\n [state=start]\n\n\\starttext\n\\useURL\n [myUrl]\n [\n \"https://www.g\n oogle.com\"\n ]\n\\goto{link}[url(myUrl)]\n\\stoptext\n\nUnfortunately the link does not work. When I don't split the URL into multiple lines, the link works again.\nIn reality my link is very long and forces uncomfortable line continuation in my vim editor. How can I break up long URLs in my source .tex file and still get the link to work in the resulting pdf?\n\nA: Probably ending lines where things are broken across lines with a character of category code 14(comment), usually %, and not nesting things between quotes, does the trick:\n\\setupinteraction\n [state=start]\n\n\\starttext\n\\useURL\n [myUrl]\n [%\n https://www.g%\n oogle.com%\n ]\n\\goto{link}[url(myUrl)]\n\\stoptext\n\n", "meta": {"language": "en", "url": "https://tex.stackexchange.com/questions/639028", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: sycn a vertical recyclerview with and horizontal recyclerview I am creating a food menu layout, the menu has categories with items.\nat the top is a list of category names like drinks, sushi, etc, which is a recyclerview that scrolls horizontally, at the bottom are the category items for example under drinks there is cocacola Fanta, etc which is a recyclerview that scrolls vertically. I am trying to synch the two recyclerviews together with a behavior in which when you scroll the vertical, it scrolls the horizontal and vice versa.\nI created this class to implement this feature.\nimport android.graphics.Typeface\nimport android.os.Handler\nimport android.os.Looper\nimport android.view.View\nimport android.widget.ImageView\nimport android.widget.TextView\nimport androidx.recyclerview.widget.LinearLayoutManager\nimport androidx.recyclerview.widget.LinearSmoothScroller\nimport androidx.recyclerview.widget.RecyclerView\n\nclass TwoRecyclerViews(\n private val recyclerViewHorizontal: RecyclerView,\n private val recyclerViewVertical: RecyclerView,\n private var indices: List,\n private var isSmoothScroll: Boolean = false,\n) {\n\nprivate var attached = false\n\nprivate var horizontalRecyclerState = RecyclerView.SCROLL_STATE_IDLE\nprivate var verticalRecyclerState = RecyclerView.SCROLL_STATE_IDLE\n\n\nprivate val smoothScrollerVertical: RecyclerView.SmoothScroller =\n object : LinearSmoothScroller(recyclerViewVertical.context) {\n override fun getVerticalSnapPreference(): Int {\n return SNAP_TO_START\n }\n }\n\n\nfun attach() {\n recyclerViewHorizontal.adapter\n ?: throw RuntimeException(\"Cannot attach with no Adapter provided to RecyclerView\")\n\n recyclerViewVertical.adapter\n ?: throw RuntimeException(\"Cannot attach with no Adapter provided to RecyclerView\")\n\n updateFirstPosition()\n notifyIndicesChanged()\n attached = true\n}\n\nprivate fun detach() {\n recyclerViewVertical.clearOnScrollListeners()\n recyclerViewHorizontal.clearOnScrollListeners()\n}\n\nfun reAttach() {\n detach()\n attach()\n}\n\nprivate fun updateFirstPosition() {\n Handler(Looper.getMainLooper()).postDelayed({\n val view = recyclerViewHorizontal.findViewHolderForLayoutPosition(0)?.itemView\n val textView = view?.findViewById(R.id.horizontalCategoryName)\n val imageView = view?.findViewById(R.id.categorySelectionIndicator)\n imageView?.visibility = View.VISIBLE\n textView?.setTypeface(null, Typeface.BOLD)\n textView?.setTextColor(recyclerViewVertical.context.getColor(R.color.primary_1))\n }, 100)\n}\n\nfun isAttached() = attached\n\nprivate fun notifyIndicesChanged() {\n recyclerViewHorizontal.addOnScrollListener(onHorizontalScrollListener)\n recyclerViewVertical.addOnScrollListener(onVerticalScrollListener)\n}\n\nprivate val onHorizontalScrollListener = object : RecyclerView.OnScrollListener() {\n override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {\n horizontalRecyclerState = newState\n }\n\n override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {\n super.onScrolled(recyclerView, dx, dy)\n\n val linearLayoutManager: LinearLayoutManager =\n recyclerView.layoutManager as LinearLayoutManager?\n ?: throw RuntimeException(\"No LinearLayoutManager attached to the RecyclerView.\")\n\n var itemPosition =\n linearLayoutManager.findFirstCompletelyVisibleItemPosition()\n\n if (itemPosition == -1) {\n itemPosition =\n linearLayoutManager.findFirstVisibleItemPosition()\n }\n\n if (horizontalRecyclerState == RecyclerView.SCROLL_STATE_DRAGGING ||\n horizontalRecyclerState == RecyclerView.SCROLL_STATE_SETTLING\n ) {\n for (position in indices.indices) {\n val view = recyclerView.findViewHolderForLayoutPosition(indices[position])?.itemView\n val textView = view?.findViewById(R.id.horizontalCategoryName)\n val imageView = view?.findViewById(R.id.categorySelectionIndicator)\n if (itemPosition == indices[position]) {\n if (isSmoothScroll) {\n smoothScrollerVertical.targetPosition = indices[position]\n recyclerViewVertical.layoutManager?.startSmoothScroll(smoothScrollerVertical)\n } else {\n (recyclerViewVertical.layoutManager as LinearLayoutManager?)?.scrollToPositionWithOffset(\n indices[position], 16.dpToPx()\n )\n }\n imageView?.visibility = View.VISIBLE\n textView?.setTypeface(null, Typeface.BOLD)\n textView?.setTextColor(recyclerView.context.getColor(R.color.primary_1))\n } else {\n imageView?.visibility = View.GONE\n textView?.setTypeface(null, Typeface.NORMAL)\n textView?.setTextColor(recyclerView.context.getColor(R.color.secondary_5))\n }\n }\n }\n }\n}\n\nprivate val onVerticalScrollListener = object : RecyclerView.OnScrollListener() {\n override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {\n verticalRecyclerState = newState\n }\n\n override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {\n super.onScrolled(recyclerView, dx, dy)\n\n val linearLayoutManager: LinearLayoutManager =\n recyclerView.layoutManager as LinearLayoutManager?\n ?: throw RuntimeException(\"No LinearLayoutManager attached to the RecyclerView.\")\n\n var itemPosition =\n linearLayoutManager.findFirstCompletelyVisibleItemPosition()\n\n if (itemPosition == -1) {\n itemPosition =\n linearLayoutManager.findFirstVisibleItemPosition()\n }\n\n if (verticalRecyclerState == RecyclerView.SCROLL_STATE_DRAGGING ||\n verticalRecyclerState == RecyclerView.SCROLL_STATE_SETTLING\n ) {\n for (position in indices.indices) {\n val view = recyclerViewHorizontal.findViewHolderForAdapterPosition(indices[position])?.itemView\n val textView = view?.findViewById(R.id.horizontalCategoryName)\n val imageView = view?.findViewById(R.id.categorySelectionIndicator)\n if (itemPosition == indices[position]) {\n (recyclerViewHorizontal.layoutManager as LinearLayoutManager?)?.scrollToPositionWithOffset(\n indices[position], 16.dpToPx()\n )\n imageView?.visibility = View.VISIBLE\n textView?.setTypeface(null, Typeface.BOLD)\n textView?.setTextColor(recyclerViewVertical.context.getColor(R.color.primary_1))\n } else {\n imageView?.visibility = View.GONE\n textView?.setTypeface(null, Typeface.NORMAL)\n textView?.setTextColor(recyclerViewVertical.context.getColor(R.color.secondary_5))\n }\n }\n }\n }\n}\n\n\n}\n\nthe class works fine for the vertical scroll, but there is an instability with the horizontal scroll. if you also have a better solution than the class i created kindly share.\n\nA: The best way to achieve your UI/UX requirement is to use TabLayout with a vertical recycler view.\nBoth list items in the recycler view and tabs in the tab layout can be set up as a dynamic number of items/tabs\nWhen you scroll up and down and reach the respective category, update the tab layout using the following code. You can identify each category from the\nTabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); // Once for the Activity of Fragment\nTabLayout.Tab tab = tabLayout.getTabAt(someIndex); // Some index should be obtain from the dataset \ntab.select();\n\nIn the same way, when clicking on a tab or scrolling the tab layout, Update the RecyclerVew accordingly./\nrecyclerView.smoothScrollToPosition(itemCount)\n\nHope this will help, Cheers!!\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/74567007", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: ImportError: /lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.30' not found I'm trying to install bern2 locally. bern2 installed successfully. when I started running, I got this error.\nImportError: /lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/../../../libfaiss.so)\nfrom normalizers.neural_normalizer import NeuralNormalizer\n File \"/home/ubuntu/BERN2/BERN2/normalizers/neural_normalizer.py\", line 17, in \n import faiss\n File \"/opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/__init__.py\", line 18, in \n from .loader import *\n File \"/opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/loader.py\", line 65, in \n from .swigfaiss import *\n File \"/opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/swigfaiss.py\", line 10, in \n from . import _swigfaiss\nImportError: /lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/../../../libfaiss.so)\nTraceback (most recent call last):\n File \"/home/ubuntu/BERN2/BERN2/server.py\", line 1, in \n from app import create_app\n File \"/home/ubuntu/BERN2/BERN2/app/__init__.py\", line 12, in \n import bern2\n File \"/home/ubuntu/BERN2/BERN2/bern2/__init__.py\", line 1, in \n from bern2.bern2 import BERN2\n File \"/home/ubuntu/BERN2/BERN2/bern2/bern2.py\", line 22, in \n from normalizer import Normalizer\n File \"/home/ubuntu/BERN2/BERN2/bern2/normalizer.py\", line 11, in \n from normalizers.neural_normalizer import NeuralNormalizer\n File \"/home/ubuntu/BERN2/BERN2/normalizers/neural_normalizer.py\", line 17, in \n import faiss\n File \"/opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/__init__.py\", line 18, in \n from .loader import *\n File \"/opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/loader.py\", line 65, in \n from .swigfaiss import *\n File \"/opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/swigfaiss.py\", line 10, in \n from . import _swigfaiss\nImportError: /lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /opt/conda/envs/bern2/lib/python3.11/site-packages/faiss/../../../libfaiss.so)\n\n\n\nA: The reason could be that the system path is not configured correctly. Try this,\nexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CONDA_PREFIX/lib/\nSource:\nhttps://www.tensorflow.org/install/pip\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/74556574", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: css: make inner container height 100% with top and bottom margin I have strange case:\nI try to make an inner container to fill parent (height with 100% height), but as result I get overflowed content in bottom:\n\nBut it must be so (100% except margin top and bottom):\n\ncode:\n\n\n\n \n \n \n \n\n \n
    \n \n
    \n
    \n
    \n
    \n
    \n
    \n
    Content
    \n
    \n
    \n
    \n
    \n
    \n \n\n\n\nand plunker (CSSit there):\nhttp://plnkr.co/edit/ku7ZXK6uezfZ86cMFhds?p=preview\n(when I set absolute position I get strange width...)\n\nA: You can calculate the height of the .content-wrapper and adjust it.\n.content-wrapper {\n height: calc(100% - 70px);\n}\n\nOutput:\n\n\n\n/* Styles go here */\r\n\r\nhtml,\r\nbody {\r\n height: 100%;\r\n min-height: 100%;\r\n}\r\nbody {\r\n min-width: 1024px;\r\n font-family: 'Open Sans', sans-serif;\r\n margin: 0;\r\n padding: 0;\r\n border: 0;\r\n}\r\n.pull-right {\r\n float: left;\r\n}\r\n.pull-left {\r\n float: left;\r\n}\r\n.main-wrapper {\r\n width: 100%;\r\n height: 100%;\r\n}\r\naside {\r\n width: 48px;\r\n height: 100%;\r\n float: left;\r\n background: #dedede;\r\n position: absolute;\r\n}\r\naside.full-nav {\r\n width: 168px;\r\n}\r\nsection.wrapper {\r\n width: 100%;\r\n height: 100%;\r\n float: left;\r\n padding-left: 168px;\r\n background: #eeeeee;\r\n}\r\nsection.wrapper.full-size {\r\n padding-left: 48px;\r\n}\r\naside ul.full-width {\r\n width: 100%;\r\n list-style-type: none;\r\n}\r\naside nav ul li {\r\n height: 34px;\r\n}\r\naside nav ul li:hover {\r\n opacity: 0.9;\r\n}\r\naside.full-nav nav ul li.company-name {\r\n width: 100%;\r\n height: 80px;\r\n background: #717cba;\r\n position: relative;\r\n}\r\naside.full-nav nav ul li.company-name span {\r\n overflow: hidden;\r\n white-space: nowrap;\r\n text-overflow: ellipsis;\r\n}\r\naside nav ul li a {\r\n height: 34px;\r\n line-height: 1;\r\n max-height: 34px;\r\n font-size: 14px;\r\n font-weight: 400;\r\n color: #ffffff;\r\n margin: 5px 0 0 12px;\r\n text-decoration: none;\r\n display: block;\r\n}\r\naside.full-nav nav ul li a.first {\r\n margin: 20px 0 0 12px;\r\n text-decoration: none;\r\n}\r\naside nav ul li a:hover {\r\n color: #ffffff;\r\n}\r\naside nav ul li.company-name .nav-company-overflow {\r\n display: none;\r\n}\r\naside nav ul li.company-name .nav-company-logo {\r\n display: none;\r\n}\r\naside.full-nav nav ul li.company-name a {\r\n height: 16px;\r\n color: #ffffff;\r\n margin: 10px 0 0 12px;\r\n text-shadow: 0 1px 1px rgba(0, 0, 0, 0.35);\r\n position: absolute;\r\n z-index: 20;\r\n}\r\naside.full-nav nav ul li.company-name .nav-company-overflow {\r\n width: 168px;\r\n height: 80px;\r\n position: absolute;\r\n top: 0;\r\n background: rgba(78, 91, 169, 0.8);\r\n z-index: 15;\r\n display: block;\r\n}\r\naside.full-nav nav ul li.company-name .nav-company-logo {\r\n width: 168px;\r\n height: 80px;\r\n position: absolute;\r\n top: 0;\r\n z-index: 10;\r\n display: block;\r\n}\r\naside nav ul li a em {\r\n line-height: 100%;\r\n display: inline-block;\r\n vertical-align: middle;\r\n margin: 0 18px 0 0;\r\n}\r\naside nav ul li a span {\r\n width: 110px;\r\n display: inline-block;\r\n line-height: 100%;\r\n vertical-align: middle;\r\n max-width: 110px;\r\n}\r\naside nav ul li a.profile em {\r\n width: 18px;\r\n height: 18px;\r\n background: url(../images/png/profile_spritesheet.png);\r\n background-position: -10px -676px;\r\n margin: 6px 8px 0 0;\r\n}\r\naside.full-nav nav ul li a.profile em {\r\n margin: 0 8px 0 0;\r\n}\r\naside nav ul li a.contacts em {\r\n width: 20px;\r\n height: 20px;\r\n background: url(../images/png/profile_spritesheet.png);\r\n background-position: -10px -224px;\r\n}\r\naside nav ul li a.events em {\r\n width: 20px;\r\n height: 22px;\r\n background: url(../images/png/profile_spritesheet.png);\r\n background-position: -10px -268px;\r\n}\r\naside nav ul li a.policy em {\r\n width: 20px;\r\n height: 23px;\r\n background: url(../images/png/profile_spritesheet.png);\r\n background-position: -10px -310px;\r\n}\r\naside nav ul li a.admins em {\r\n width: 18px;\r\n height: 18px;\r\n background: url(../images/png/profile_spritesheet.png);\r\n background-position: -10px -676px;\r\n}\r\naside.full-nav nav ul li a span {\r\n display: inline-block;\r\n}\r\naside nav ul li a span {\r\n display: none;\r\n}\r\naside .hide-sidebar {\r\n width: 100%;\r\n height: 34px;\r\n background: #455095;\r\n position: absolute;\r\n bottom: 0;\r\n}\r\n#hide-sidebar-btn {\r\n width: 30px;\r\n height: 34px;\r\n line-height: 40px;\r\n background: #394485;\r\n float: right;\r\n text-align: center;\r\n}\r\n#hide-sidebar-btn:hover {\r\n cursor: pointer;\r\n}\r\naside .collapse-btn-icon {\r\n width: 8px;\r\n height: 15px;\r\n display: inline-block;\r\n background: url(../images/png/profile_spritesheet.png);\r\n background-position: -10px -353px;\r\n -webkit-transform: rotate(180deg);\r\n transform: rotate(180deg);\r\n}\r\naside.full-nav .collapse-btn-icon {\r\n -webkit-transform: rotate(360deg);\r\n transform: rotate(360deg);\r\n}\r\n.innner-wrapper {\r\n height: 100%;\r\n margin: 0 12px 0 12px;\r\n}\r\n.main-partial {\r\n height: 100%;\r\n}\r\nheader {\r\n height: 40px;\r\n background: #ffffff;\r\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);\r\n}\r\nheader .buttons-header-area {\r\n float: right;\r\n}\r\nheader .company-header-avatar {\r\n width: 28px;\r\n height: 28px;\r\n -webkit-border-radius: 28px;\r\n -webkit-background-clip: padding-box;\r\n -moz-border-radius: 28px;\r\n -moz-background-clip: padding;\r\n border-radius: 28px;\r\n background-clip: padding-box;\r\n margin: 7px 0 0 5px;\r\n float: left;\r\n}\r\nheader .info {\r\n height: 40px;\r\n line-height: 40px;\r\n margin: 0 5px 0 0;\r\n}\r\nheader .info em {\r\n width: 28px;\r\n height: 28px;\r\n display: inline-block;\r\n vertical-align: middle;\r\n background: url(../images/png/profile_spritesheet.png);\r\n background-position: -10px -53px;\r\n}\r\nheader .dropdown-toggle {\r\n width: 170px;\r\n height: 40px;\r\n border: none;\r\n padding: 0;\r\n background: transparent;\r\n font-size: 12px;\r\n color: #444444;\r\n}\r\nheader .btn-group {\r\n height: 40px;\r\n vertical-align: top;\r\n}\r\nheader .btn-group.open {\r\n background: #eeeeee;\r\n}\r\nheader .open > .dropdown-menu {\r\n width: 170px;\r\n font-size: 12px;\r\n border-color: #d9d9d9;\r\n box-shadow: 0 2px 5px rgba(0, 0, 0, 0.11);\r\n margin: 2px 0 0 0;\r\n}\r\nheader .dropdown-toggle:hover {\r\n background: #eeeeee;\r\n}\r\nheader .profile-name {\r\n width: 100px;\r\n height: 40px;\r\n line-height: 40px;\r\n display: inline-block;\r\n overflow: hidden;\r\n white-space: nowrap;\r\n text-overflow: ellipsis;\r\n}\r\nheader .caret {\r\n height: 40px;\r\n border-top: 6px solid #bfbfbf;\r\n border-right: 6px solid transparent;\r\n border-left: 6px solid transparent;\r\n}\r\n.content {\r\n height: 100%;\r\n margin: 12px 0;\r\n overflow: hidden;\r\n}\r\n.content-wrapper {\r\n background: #ffffff none repeat scroll 0 0;\r\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);\r\n height: calc(100% - 70px);\r\n width: 100%;\r\n}\r\n.content-row.company {\r\n height: 300px;\r\n}\r\n.content-row-wrapper {\r\n margin: 0 18px;\r\n}\n\r\n\r\n\r\n\r\n \r\n \r\n\r\n\r\n\r\n
    \r\n \r\n
    \r\n
    \r\n
    \r\n
    \r\n
    \r\n
    \r\n
    Content
    \r\n
    \r\n
    \r\n
    \r\n
    \r\n
    \r\n\r\n\r\n\n\n\n\nA: I think the problem is that you are assigning 100% height to the container and this one is getting the relative window height. The problem is the header at the top of the page does not let this to work. Maybe you have to calculate with javascript or something to apply the correct height to that container.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/31233811", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Hadoop - Creating a single instance of a class for each map() functions inside the Mapper for a particular node I have a Class something like this in java for hadoop MapReduce\npublic Class MyClass {\n public static MyClassMapper extends Mapper {\n static SomeClass someClassObj = new SomeClass();\n\n void map(Object Key, Text value, Context context) {\n String someText = someClassObj.getSomeThing();\n }\n }\n}\n\nI need only a single instance of someClassObj to be available to the map() function per node.\nHow can achieve that?\nPlease feel free to ask if you need further details on this topic.\nThank you! \n\nA: The mapreduce.tasktracker.map.tasks.maximum (defaulted to 2) controls the maximum number of map tasks that are run simultaneously by a TaskTracker. Set this value to 1.\nEach map task is launched is a seperate JVM. Also set the mapreduce.job.jvm.numtasks to -1 to reuse the JVM.\nThe above settings will enable all the map tasks to run in single JVM sequentially. Now, SomeClass has to be made a singleton class.\nThis is not a best practice as the node is not efficiently utilized because of the lower number of map tasks that can run in parallel. Also, with JVM reuse there is no isolation between the tasks, so if there is any memory leak it will be carried on till the jvm crashes.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/7872830", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: using Socket.io with React and Redux to handle a hundred of updates per second I have a list of items which are objects of data from the server (about 1000) that I need to sort, filter, put into Redux and connect to a React table component. I'm using socket.io to listen for updates which sends these individual data objects that then need to be calculated into the table. they can be an update, new one or, removing existing one.\nSo my question is what's the best way to manage so many incoming socket data events? should i just throttle them before i update them into my redux state? i dont want to constantly update my redux state or my table component will re-render too much.\nmy other option is i can request a current up to date list of all the \"active\" data and just ignore the update events. so perhaps every few seconds just update the entire table with all the latest data instead of trying to manage hundreds of updates a second.\n\nA: I would stick to using REST api calls, but faking the update on the start of a redux's action, doing nothing except maybe adding a proper id to your object on success, and reverting back the state on failure only.\nYour reducer would kinda look like this in case of a create item action :\nexport default (state = {}, action) => {\n switch (action.type) {\n case ActionsTypes.CREATE_START:\n // make the temporary changes\n\n case ActionsTypes.CREATE_SUCCESS:\n // update the previous temporary id with a proper id\n\n case ActionsTypes.CREATE_FAILURE:\n // delete the temporary changes\n\n default:\n return state;\n }\n};\n\nAnd your actions like this :\nconst ActionLoading = item => ({\n type: ActionsTypes.CREATE_START,\n item,\n});\n\nconst ActionSuccess = item => ({\n type: ActionsTypes.CREATE_SUCCESS,\n item ,\n createdItem,\n});\n\nconst ActionFailure = item => ({\n type: ActionsTypes.CREATE_FAILURE,\n item,\n});\n\nexport default todo => (dispatch) => {\n dispatch(ActionLoading(item)); // add the item to your state\n\n const updatedTodo = await TodoClient.create(todo)\n\n if (updatedTodo) {\n dispatch(ActionSuccess(item, createdItem)) // update the temp item with a real id\n } else {\n dispatch(ActionFailure(item)) // remove the temporary item \n }\n};\n\nIt is mandatory that you give temporary ids to the data you are managing for performace's sake and to let react key properly the items rendered in maps. I personally use lodash's uniqueId.\nYou'll have also to implement this behavior for updates and removals but it's basically the same: \n\n\n*\n\n*store the changes, update your object without waiting for the api and\nrevert the changes on failure.\n\n*remove your object without waiting for the api and pop it back on failure.\n\n\nThis will give a real time feel as everything will be updated instantly and only reverted on unmanaged errors. If you trust your backend enough, this is the way to go. \nEDIT : Just saw your update, you can stick to this way of mutating the data (or to the normal way of updating the state on success) but to avoid too much complexity and rendering time, make sure you store your data using keyBy. Once your items are stored as an array of object keyed by their id, you will be able to add, remove and modify them with a O(1) complexity. Also, react will understand that it doesn't need to re-render the whole list but only the single updated item.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/50999907", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: VueJS - standard practice for ordering functions in export? New to Vue and wondering if there is there a standard practice for ordering the exports? The name seems to always be at the top and the lifecycle hooks seem to be in the order of the lifescycle but I'm not sure about the rest (data, computed, etc.). \nThoughts?\ne.g. \nexport default {\n name: \"component-name\",\n props: {},\n components: {},\n computed: {},\n data() {},\n watch: {},\n beforeCreate() {},\n created() {},\n beforeMount() {},\n mounted() {},\n beforeUpdate() {},\n updated() {},\n beforeDestroy() {},\n destroyed() {},\n methods: {},\n};\n\n\nA: Based on the rules of the eslint-plugin-vue v6.2.2 (for Vue 2.x), You can read about it here: https://github.com/vuejs/eslint-plugin-vue/blob/v6.2.2/docs/rules/README.md, this is the order:\n{\n \"vue/order-in-components\": [\"error\", {\n \"order\": [\n \"el\",\n \"name\",\n \"parent\",\n \"functional\",\n [\"delimiters\", \"comments\"],\n [\"components\", \"directives\", \"filters\"],\n \"extends\",\n \"mixins\",\n \"inheritAttrs\",\n \"model\",\n [\"props\", \"propsData\"],\n \"fetch\",\n \"asyncData\",\n \"data\",\n \"computed\",\n \"watch\",\n \"LIFECYCLE_HOOKS\",\n \"methods\",\n \"head\",\n [\"template\", \"render\"],\n \"renderError\"\n ]\n }]\n}\n\nHere you can read the Vue style guide and the rules priority information https://v2.vuejs.org/v2/style-guide/\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/62253825", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Python error importing dateutil I try to execute marathon-lb.py and it throws the next error:\nTraceback (most recent call last):\n File \"./marathon_lb.py\", line 46, in \n import dateutil.parser\nImportError: No module named 'dateutil'\n\nI just install python with apt and with pip.\nI have run:\nsudo apt-get install python-pip\npip install python-dateutil\n\nI compile the script with: python -m py_compile script.py\npython application:\nfrom operator import attrgetter\nfrom shutil import move\nfrom tempfile import mkstemp\nfrom wsgiref.simple_server import make_server\nfrom six.moves.urllib import parse\nfrom itertools import cycle\nfrom common import *\nfrom config import *\nfrom lrucache import *\nfrom utils import *\n\nimport argparse\nimport json\nimport logging\nimport os\nimport os.path\nimport stat\nimport re\nimport requests\nimport shlex\nimport subprocess\nimport sys\nimport time\nimport dateutil.parser\n\n\nA: Install python-dateutil\npip install python-dateutil\n\n\nA: Step 1. First thing is upgrade pip for corresponding python version (3 or 2) you have.\npip3 install --upgrade pip\n\nor \npip2 install --upgrade pip\n\nStep2.\nSome times directly running command wont work since\nThere are probably multiple versions of python-dateutil installed. \n\n\n*\n\n*Try to run pip uninstall python-dateutil\nwill give below message if python-dateutil is already un installed.\n\nCannot uninstall requirement python-dateutil, not installed\n\n\n\n*Then, you can run pip install python-dateutil again.\n\n\nNOTE : Directly running step2 wont work for users whose python and pip versions are not compatible.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/37434917", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "7"}} {"text": "Q: Unable to perform successful Paypal webhook validation I am working to validate Paypal webhook data but I'm running into an issue where it's always returning a FAILURE for the validation status. I'm wondering if it's because this is all happening in a sandbox environment and Paypal doesn't allow verification for sandbox webhook events? I followed this API doc to implement the call: https://developer.paypal.com/docs/api/webhooks/v1/#verify-webhook-signature\nRelevant code (from separate elixir modules):\ndef call(conn, _opts) do\n conn\n |> extract_webhook_signature(conn.params)\n |> webhook_signature_valid?()\n |> # handle the result\nend\n\ndefp extract_webhook_signature(conn, params) do\n %{\n auth_algo: get_req_header(conn, \"paypal-auth-algo\") |> Enum.at(0, \"\"),\n cert_url: get_req_header(conn, \"paypal-cert-url\") |> Enum.at(0, \"\"),\n transmission_id: get_req_header(conn, \"paypal-transmission-id\") |> Enum.at(0, \"\"),\n transmission_sig: get_req_header(conn, \"paypal-transmission-sig\") |> Enum.at(0, \"\"),\n transmission_time: get_req_header(conn, \"paypal-transmission-time\") |> Enum.at(0, \"\"),\n webhook_id: get_webhook_id(),\n webhook_event: params\n }\nend\n\ndef webhook_signature_valid?(signature) do\n body = Jason.encode!(signature)\n case Request.post(\"/v1/notifications/verify-webhook-signature\", body) do\n {:ok, %{verification_status: \"SUCCESS\"}} -> true\n _ -> false\n end\nend\n\nI get back a 200 from Paypal, which means that Paypal got my request and was able to properly parse it and run it though its validation, but it's always returning a FAILURE for the validation status, meaning that the authenticity of the request couldn't be verified. I looked at the data I was posting to their endpoint and it all looks correct, but for some reason it isn't validating. I put the JSON that I posted to the API (from extract_webhook_signature) into a Pastebin here cause it's pretty large: https://pastebin.com/SYBT7muv\nIf anyone has experience with this and knows why it could be failing, I'd love to hear. \n\nA: I solved my own problem. Paypal does not canonicalize their webhook validation requests. When you receive the POST from Paypal, do NOT parse the request body before you go to send it back to them in the verification call. If your webhook_event is any different (even if the fields are in a different order), the event will be considered invalid and you will receive back a FAILURE. You must read the raw POST body and post that exact data back to Paypal in your webhook_event.\nExample:\nif you receive {\"a\":1,\"b\":2} and you post back {..., \"webhook_event\":{\"b\":2,\"a\":1}, ...} (notice the difference in order of the json fields from what we recieved and what we posted back) you will recieve a FAILURE. Your post needs to be {..., \"webhook_event\":{\"a\":1,\"b\":2}, ...}\n\nA: For those who are struggling with this, I'd like to give you my solution which includes the accepted answer.\nBefore you start, make sure to store the raw_body in your conn, as described in Verifying the webhook - the client side\n\n @verification_url \"https://api-m.sandbox.paypal.com/v1/notifications/verify-webhook-signature\"\n @auth_token_url \"https://api-m.sandbox.paypal.com/v1/oauth2/token\"\n\n defp get_auth_token do\n headers = [\n Accept: \"application/json\",\n \"Accept-Language\": \"en_US\"\n ]\n\n client_id = Application.get_env(:my_app, :paypal)[:client_id]\n client_secret = Application.get_env(:my_app, :paypal)[:client_secret]\n\n options = [\n hackney: [basic_auth: {client_id, client_secret}]\n ]\n\n body = \"grant_type=client_credentials\"\n\n case HTTPoison.post(@auth_token_url, body, headers, options) do\n {:ok, %HTTPoison.Response{status_code: 200, body: body}} ->\n %{\"access_token\" => access_token} = Jason.decode!(body)\n {:ok, access_token}\n\n error ->\n Logger.error(inspect(error))\n {:error, :no_access_token}\n end\n end\n\n defp verify_event(conn, auth_token, raw_body) do\n headers = [\n \"Content-Type\": \"application/json\",\n Authorization: \"Bearer #{auth_token}\"\n ]\n\n body =\n %{\n transmission_id: get_header(conn, \"paypal-transmission-id\"),\n transmission_time: get_header(conn, \"paypal-transmission-time\"),\n cert_url: get_header(conn, \"paypal-cert-url\"),\n auth_algo: get_header(conn, \"paypal-auth-algo\"),\n transmission_sig: get_header(conn, \"paypal-transmission-sig\"),\n webhook_id: Application.get_env(:papervault, :paypal)[:webhook_id],\n webhook_event: \"raw_body\"\n }\n |> Jason.encode!()\n |> String.replace(\"\\\"raw_body\\\"\", raw_body)\n\n with {:ok, %{status_code: 200, body: encoded_body}} <-\n HTTPoison.post(@verification_url, body, headers),\n {:ok, %{\"verification_status\" => \"SUCCESS\"}} <- Jason.decode(encoded_body) do\n :ok\n else\n error ->\n Logger.error(inspect(error))\n {:error, :not_verified}\n end\n end\n\n defp get_header(conn, key) do\n conn |> get_req_header(key) |> List.first()\n end\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/61399557", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: charts disappear on-click? I am using dynamic feature I am using two different charts on the same page, so when I click on any chart of them the Gauge chart disappear.\nvar gauge1 = new RGraph.Gauge({\n id: 'gauge',\n min:0,\n max: 100,\n value: #{mbCardHistory.creditCardPrecentage},\n options: {\n centery: 120,\n radius: 130,\n anglesStart: RGraph.PI,\n anglesEnd: RGraph.TWOPI,\n needleSize: 85,\n borderWidth: 0,\n shadow: false,\n needleType: 'line',\n colorsRanges: [[0,30,'red'], [30,70,'yellow'],[70,100,'#0f0']],\n borderInner: 'rgba(0,0,0,0)',\n borderOuter: 'rgba(0,0,0,0)',\n borderOutline: 'rgba(0,0,0,0)',\n centerpinColor: 'rgba(0,0,0,0)',\n centerpinRadius: 0,\n textAccessible: true\n }\n }).draw();\n\nbefore\nafter\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/53722359", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: MySQL Query COUNTing incorrectly Well, I realise that in fact it's more likely to be my logic that's counting wrong ;)\nSo here's my query:\nSELECT \n code.id AS codeid, code.title AS codetitle, code.summary AS codesummary, code.author AS codeauthor, code.date,\n code_tags.*, \n tags.*, \n users.firstname AS authorname, \n users.id AS authorid,\n ratingItems.*, FORMAT((ratingItems.totalPoints / ratingItems.totalVotes), 1) AS rating,\n GROUP_CONCAT(tags.tag SEPARATOR ', ') AS taggroup,\n COUNT(comments.codeid) AS commentcount\nFROM \n code\n join code_tags on code_tags.code_id = code.id\n join tags on tags.id = code_tags.tag_id\n join users on users.id = code.author\n left join comments on comments.codeid = code.id\n left join ratingItems on uniqueName = code.id\nGROUP BY code_id\nORDER BY date DESC\nLIMIT 0, 15 \n\nSorry there's quite a bit of 'bloat' in that. The problem I'm having is with commentcount or (COUNT(comments.codeid) AS commentcount) - I want to count the total number of comments a code submission has. Previously, it was working correctly but I restructured my MySQL syntax and now it's stopped working :(\nThere's only 2 code submissions in the database that have comments. The first of these results that is returned correctly identifies it has more than 0 comments, but reports it as having '2' in commentcount, when in fact it has only 1.\nThe second submission ALSO only has one comment, but, it tells me that it has 4!\nCan someone tell me what's wrong my logic here?\nThanks!\nJack\n\nA: Try eliminating the GROUP BY constraint. Then see where your duplicate rows are coming from, and fix your original query. This will fix your COUNTs as well.\n\nA: Try either:\nCOUNT(DISTINCT comments.codeid) AS commentcount\n\nor\n(SELECT COUNT(*) FROM comments WHERE comments.codeid = code.id) AS commentcount\n\n\nA: Try starting with a simple query, and building up from that. If I have understood your structure correctly, the following query will return the correct number of comments for each code submission:\nSELECT code.*, COUNT(code.id) AS comment_count\nFROM code\nJOIN comments ON comments.codeid = code.id\nGROUP BY(code.id);\n\nThere's a few odd looking column names and joins in your example, which may be contributing to the problem \u0085 or it might just be an odd naming scheme :-)\nFor example, you are joining ratingItems to code by comparing code.id with ratingItems.uniqueName. That might be correct, but it doesn't quite look right. Perhaps it should be more like:\nLEFT JOIN ratingItems ON ratingItems.code_id = code.id\n\nStart with a basic working query, then add the other joins.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/3193323", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to trim out multiple time-points in an AVAsset (Swift)? I am working on a video editor app, where based on some processing, I have an array of samples/time-points to remove from the video clip. For example,\ntimePoints = [0 8.2 15.5 20.6...]. //seconds\nI would like to remove these specific frames from the video clip (i.e. AVAsset), which correspond to these time-points. From what I understand so far, you can use AVAssetExportSession to trim a specific time range (e.g. tstart to tend) but not multiple time-points (e.g. timePoints array above).\nHence, is there a way to export with multiple time-points discarded? i.e. the output video will merge together all clips, except the frames corresponding to those time-points to be discarded?\nWould appreciate any help, Thanks!\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/67323555", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Phone not recognized in android debugger I am trying to run the android debugger on my phone, but the console as well as eclipse plugin reports a ??? in place of the device name.\nThe attached phone is a sony ericsson xperia mini, running android 2.3 and the computer is running on ubuntu 10.10 .\nI have enabled the usb debugging option on the phone.\n\nA: You need to enter the Phone USB configuration for your device in the udev file on ubuntu\nYou need to add a udev rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, see USB Vendor IDs, below. To set up device detection on Ubuntu Linux:\nLog in as root and create this file: /etc/udev/rules.d/51-android.rules.\nUse this format to add each vendor to the file:\n SUBSYSTEM==\"usb\", ATTR{idVendor}==\"0bb4\", MODE=\"0666\", GROUP=\"plugdev\" \n\nIn this example, the vendor ID is for HTC. The MODE assignment specifies read/write permissions, and GROUP defines which Unix group owns the device node.\nNote: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules.\nNow execute:\n chmod a+r /etc/udev/rules.d/51-android.rules\n\nVendor ID for Sony Ericcson is\n Sony Ericsson 0FCE\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/8470155", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to keep AllSubscribers email address up to date when unique identifier is a subscriberkey Background: In our use-case, a unique identifier of a customer is a SubscriberKey. We DO NOT HAVE salesforce.com connected to SFMC. SFMC is running independent.\nWe get all contacts in a All_Contacts_DB data extension via API (refreshed daily) and from there we create segmentations and sendable data extensions to send out emails.\nIssue: We recently discovered that when a customer changes their email address and sendable data extension includes the updated email address along with the customer unique idenfier which is the SubscriberKey, the deployment DOES NOT automatically updates the EmailAddress value in all subscribers and send happens on \"old\" (i.e. existing) EmailAddress value in AllSubscribers.\nProposed solution / Steps: For keeping the \"AllSubscribers\" list up to date with most up to date email address value, we are considering following steps in exact order\n\n*\n\n*Create an automation\n\n\n*SQL query\nSelect \n s.SubscriberKey\n, c.CustomerEmail AS EmailAddress \nfrom _Subscribers s\nINNER JOIN All_Contacts_DB c ON c.CustomerID = s.SubscriberKey\nWHERE c.CustomerEmail != s.EmailAddress\n\n\n*\n\n*Save output into a data extension - EmailDiscrepancy_Table\n\n\n\n*Extract \"EmailDiscrepancy_Table\" DE as .TXT on sFTP\n\n\n*File transfer\n\n\n*Import the list in AllSubscribers list as UPDATE\nQuestions:\n\n*\n\n*Is the above solution / process correct OR there is a better / efficiant way of keeping EmailAddress value up to date in SFMC? (OR any way to give priority to sendable data extension emailaddress field over EmailAddress in AllSubscribers?)\n\n\n*What would happen is a subscriber is in middle of an active journey and email address changes?\n\n\n*Does journey remembers / keeps a snapshot of the EmailAddress when a subscriber enters a journey? OR subscriber can be email on emailtouch 1, email touch2 on currentemail@address.com then email changes in the middle by above automation process then email touch3, 4 and so on goes to new EmailAddress value by default? I don't know if journey remembers the subscriber subscriberkey in the snapshot OR everything (includes EmaiulAddress) except the status which is always checked on each send?\n\nA: I would give my opinions here:\n1.\n\n*\n\n*Depending on the number of records in the \"EmailDiscrepancy_Table\" DE, I would try to write a SSJS script to update the most recent email addresses for these subscribers in case it is a small data. So steps from 3 to 5 could be replaced by a script activity. Otherwise, continue to use bulk import as you are doing.\n\n*If you are sending the email from a journey, then you can configure the journey setting, use default email address as the email address field in the DE entry source -> Journey behavior: this will use the email address in the DE to send out the email and update the latest email address in All Subscribers List as well.\n\n\n\n*\n\n\n*\n\n*If you update the email address (e.g., change the email address in All Subscribers List ) while the subscriber is in the middle of the active journey, it won't change the email destination address. In journey, there is the snapshot of the data for \"Journey Data\"\n\n\n\n*\n\n\n*\n\n*Like the 2nd answer above, there is the snapshot of the journey data when the journey is activated. Everything.\n\n", "meta": {"language": "en", "url": "https://salesforce.stackexchange.com/questions/395963", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: MVC2 and mySQL database I'm following the example from the ASP.NET MVC 2 Framework book (Steven Sanderson), except instead of using SQLServer, I'm using mySQL.\npublic class ProductsController : Controller\n{\n private IProductsRepository productsRepository;\n public ProductsController()\n {\n // Temporary hard-coded connection string until we set up dependency injection\n string connString = \"server=xx.xx.xxx.xxx;Database=db_SportsStore;User Id=dbUser;Pwd=xxxxxxxxx;Persist Security Info=True;\";\n productsRepository = new SportsStore.Domain.Concrete.SqlProductsRepository(connString);\n\n }\n public ViewResult List()\n {\n return View(productsRepository.Products.ToList());\n }\n}\n\nWhen I run the project I get the following error:\nA network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)\nI have downloaded the MySQL .Net connector and in the Server Explorer I was able to view the tables on that DB. I also have made sure that the DBs on the server allows for remote connections.\nI am creating and running the code locally via VS2010 and the MySQL DB is on hosted server.\nWhat do I have to do to get this MVC2 example to function for MySQL?\nUpdate:\nI was playing around with the code while waiting for an answer and I updated the ProductsController to the following:\nusing MySql.Data.MySqlClient;\n string connString = \"server=xx.xx.xxx.xxx;Database=db_SportsStore;User Id=dbUser;Pwd=xxxxxx;\";\n var connection = new MySqlConnection(connString);\n\n productsRepository = new SportsStore.Domain.Concrete.SqlProductsRepository(connection);\n\nThen in the repository:\npublic SqlProductsRepository(MySql.Data.MySqlClient.MySqlConnection connection)\n{\n connection.Open();\n productsTable = (new DataContext(connection)).GetTable();\n connection.Close();\n}\n\nNow I get a totally different error:\n{\"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[t0].[ProductID], [t0].[Name], [t0].[Description], [t0].[Price], [t0].[Category]' at line 1\"}\nI should also mention... This example is using LINQ to SQL. I'm not sure if that matters or not. Please advise.\n\nA: A couple of thoughts come to mind. \n\n\n*\n\n*The connection string you are using is the connection string if you are connecting to a SQL Server DB instead of a MySQL .Net Connector connection string. You're going to have to change the connection string example from the book to what MySQL needs. For example, MySQL doesn't have a Trusted Connection option. (http://dev.mysql.com/doc/refman/5.1/en/connector-net-connection-options.html)\n\n*In your SQLProductsRepository you'll need to use the MySQLConnection Object and so forth instead of a SQLConnection object if used. I think the book used Linq To SQL or Linq to Entity Framework. Either way you'll have to modify the code to use the MySQL... objects or modify the model to hit your MySQL if it's Entity Framework. If you already did this then the connection string in it will give a good idea of what you need in #1.\n\n\nhttp://dev.mysql.com/doc/refman/5.1/en/connector-net-tutorials-intro.html\nEDIT - With your update...\nMySQL doesn't have the same syntax as SQL Server sometimes. I am assuming that is what this error is pointing to. \nOn the MySQL Connector connection string, it has an option to use SQL Server Syntax called SQL Server Mode. Set this to true and see if this works....\nSomething like:\nServer=serverIP;Database=dbName;Uid=Username;Pwd=Password;SQL Server Mode=true;\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/5843376", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Are Google Cloud Disks OK to use with SQLite? Google Cloud disks are network disks that behave like local disks. SQLite expects a local disk so that locking and transactions work correctly.\nA. Is it safe to use Google Cloud disks for SQLite?\nB. Do they support the right locking mechanisms? How is this done over the network?\nC. How does disk IOP's and Throughput relate to SQLite performance? If I have a 1GB SQLite file with queries that take 40ms to complete locally, how many IOP's would this use? Which disk performance should I choose between (standard, balanced, SSD)?\nThanks.\nRelated\nhttps://cloud.google.com/compute/docs/disks#pdspecs\n\nPersistent disks are durable network storage devices that your instances can access like physical disks\n\nhttps://www.sqlite.org/draft/useovernet.html\n\nthe SQLite library is not tested in across-a-network scenarios, nor is that reasonably possible. Hence, use of a remote database is done at the user's risk.\n\n\nA: Yeah, the article you referenced, essentially stipulates that since the reads and writes are \"simplified\", at the OS level, they can be unpredictable resulting in \"loss in translation\" issues when going local-network-remote.\nThey also point out, it may very well work totally fine in testing and perhaps in production for a time, but there are known side effects which are hard to detect and mitigate against -- so its a slight gamble.\nAgain the implementation they are describing is not Google Cloud Disk, but rather simply stated as a remote networked arrangement.\nMy point is more that Google Cloud Disk may be more \"virtual\" rather than purely networked attached storage... to my mind that would be where to look, and evaluate it from there.\n\nCheckout this thread for some additional insight into the issues, https://serverfault.com/questions/823532/sqlite-on-google-cloud-persistent-disk\nAdditionally, I was looking around and I found this thread, where one poster suggest using SQLite as a read-only asset, then deploying updates in a far more controlled process.\nhttps://news.ycombinator.com/item?id=26441125\n\nA: the persistend disk acts like a normal disk in your vm. and is only accessable to one vm at a time.\nso it's safe to use, you won't lose any data.\n\nFor the performance part. you just have to test it. for your specific workload. if you have plenty of spare ram, and your database is read heavy, and seldom writes. the whole database will be cached by the os (linux) disk cache. so it will be crazy fast. even on hdd storage.\nbut if you are low on spare ram. than the database won't be in the os cache. and writes are always synced to disk. and that causes lots of I/O operations.\nin that case use the highest performing disk you can / are willing to afford.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/73459746", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: while loop with a multiple tableX union i want to know please how i can put\nunion of table 2014 to 2017 only in loop in this query:\nselect\nxxx,\nxxx,\nxxx,\nfrom (\nselect\ncolonne,\ncolonne,\nfrom CA\nleft join (\nselect\nxx,\nsum(xx) as xx,\nxx\nfrom (\nselect\nsum(MONTANT) as MONTANT,\nCONCAT(NUM_SIN, CLE_SIN) as cle,\nEXER_SIN\nfrom fa\nwhere CD_TYP_CNT='PREV'\ngroup by NUM_SIN, CLE_SIN, EXER_SIN\nunion\nselect\nsum(MONTANT) as MONTANT,\nCONCAT(NUM_SIN, CLE_SIN) as cle,\nEXER_SIN\nfrom table2014\nwhere CD_TYP_CNT='PREV'\ngroup by NUM_SIN, CLE_SIN, EXER_SIN\nunion\nselect\nsum(MONTANT) as MONTANT,\nCONCAT(NUM_SIN, CLE_SIN) as cle,\nEXER_SIN\nfrom table2015\nwhere CD_TYP_CNT='PREV'\ngroup by NUM_SIN, CLE_SIN, EXER_SIN\nunion\nselect\nsum(MONTANT) as MONTANT,\nCONCAT(NUM_SIN, CLE_SIN) as cle,\nEXER_SIN\nfrom table2016\nwhere CD_TYP_CNT='PREV'\ngroup by NUM_SIN, CLE_SIN, EXER_SIN\nunion\nselect\nsum(MONTANT) as MONTANT,\nCONCAT(NUM_SIN, CLE_SIN) as cle,\nEXER_SIN\nfrom table2017\nwhere CD_TYP_CNT='PREV'\ngroup by NUM_SIN, CLE_SIN, EXER_SIN ) as tab\ngroup by cle, EXER_SIN) as reglmt on reglmt.cle = CPM.dossiers\n left join (\n select \n CONCAT(colonne, colonne) as cle, \n \n from production\n group by colonne, colonne1, colonne3, colonne4) as xx on ptf_CPM.cle = CPM.dossiers\ngroup by xx, xx\n\n) as xx\nwhere v\u00e9rif <> 0\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/73792070", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Webpack \"Not a function\" error for calling a class in React In a react app, I have some business logic I'm trying to encapsulate in class called Authentication. When I try to call a method called configure on the Authentication class I get the following error:\n\nTypeError:\n WEBPACK_IMPORTED_MODULE_5__authentication_js.a.configure is not a function\n\nIn my React app.js file I import the authentication class with:\nimport Authentication from './authentication.js';\n\nand then I try to access it inside my constructor as follows:\nconstructor(props) {\n super(props);\n Authentication.configure();\n}\n\nThe code for authentication.js is as follows:\nclass Authentication {\n\n constructor(props) {\n console.log('inside constructor of Authentication class'); \n }\n\n configure(){\n //some setup logic, still fails if I comment it all out\n }\n}\nexport default Authentication;\n\nI'm unsure how exactly to troubleshoot this issue. I know I've seen similar issues in react before where an internal method has not had the bind method called against it, but I'm unsure if that is needed for a public method of an external class and if it is required, I'm not sure how to implement it. Any help/guidance would be greatly appreciated.\n\nA: configure is an instance method of the Authentication class. \nEither make configure static, or export an instance of Authentication.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/51620624", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Google Places Autocomplete Dropdown Invisible In my site, I have a functional google places autocomplete, but it is invisible. I know that it works because if I type in \"123 Main Street\" and then move my arrow key down and hit enter- the address information will append to the inputs as normal. \nI attempted adding this to my CSS:\n.pac-container { z-index: 1051 !important; } \n\nBut it did not work.\nHas anyone else had this issue?\n\nA: My solution was simple.\nI just increased the z-index even more.\n.pac-container { z-index: 9999 !important; } \n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/39733079", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Dual Monitor, Dual Actions I have a simple dual monitor setup, and I need to use to very similar programs simultaneously. For instance, if I click on program1 which is on one monitor1, it will simultaneously click on the other program2 which is on monitor2.\nIs there anyway to mirror the actions of one monitor to the other? Any pointers/help would be greatly appreciated. A link for a program that does this would be awesome!\nMy OS is Windows 7, and the two programs I am using are ArcGis and Mapviewer that both read similar maps.\nUPDATE: Thanks to Julian Knight's suggestion, here is the autohotkey script I have come up with: \nLButton:: ; press alt+k to activate\nCoordMode, Mouse, Relative\nWinActivate, Partner\nClick down 500, 500\nWinActivate, Test Electric - ArcMap\nClick down 500, 500\nreturn\n\nEscape:: \nExitApp\nReturn\n\nAfter running this script however, i merely get two clicks at those two points(500,500) on each window. I would like to be able to click and drag both windows simultaneously. Any suggestions?\n\nA: To achieve this, you would need an application that sent scroll commands to both windows simultaneously.\nI am not aware of any application on any platform that would do this natively. However, on Windows you could use something like AutoHotKey to set up a hotkey combination that would send a scroll command to both windows as long as you could identify the two windows (AHK and similar applications have tools that help with this).\nFurther help is not possible without knowing more about the OS and applications you are using.\nUPDATE: Now we know the OS is Windows, I can suggest something like AutoHotKey.\nThat is able to send mouse and/or keyboard clicks to specific windows in specific places. So you could create a macro that, for example, sends page-down keyboard \"clicks\" to each application window. It comes with a \"spy\" tool that lets you easily find out the technical identifiers for specific application windows so that you can send the commands to the right place.\nIf the applications don't support keyboard scrolling, you would have to do it via mouse clicks which is also possible. In that case, however, you need to know the size and position of the windows so that you can successfully \"click\" on the right bit of the window to scroll.\n", "meta": {"language": "en", "url": "https://superuser.com/questions/914397", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Merge Duplicate Columns On the top column of my report are dates (mm/dd/yyyy) with corresponding data below. When I run the report, it shows multiple columns with the same date but different data. For example\n5/12/2011 | 5/12/2011 | 6/7/2011\n---------------------------------\n 10 | 6 | 11\n\nHow do I merge columns with the same dates while also combining the data as well?\n\nA: You should create a column group to your tablix on the date field so that it will actually group your dates instead of displaying each one individually. You can then use the SSRS aggregate functions in your details fields to combine the data from the grouped columns & rows.\nMore info:\n\n\n*\n\n*Understanding Groups (Report Builder and SSRS)\n\n*Aggregate Functions Reference (Report Builder and SSRS)\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/24497853", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Javascript ignores # in url I was trying to extract url after domain. According to this question it is possible by calling window.location.pathname, but in my url http://domain:host/something#random=123 it drops everything after # inclusive. Is there anything better out there than splitting or regex?\nIn code:\nwindow.location.pathname(\"http://domain:host/something#random=123\")\n\nreturns /something\nDesired behavior:\nwindow.location.unknownMethodToMe(\"http://domain:host/something#random=123\")\n\nshould return /something#random=123\nThanks in advance.\n\nA: Try using location.hash which should return #random=123\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/37903559", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: jQuery resizable problem on rotated elements I am truing to do a jQuery UI resize on a div that is rotated with 77deg. The result is totally uncontrollable.\nTo replicate this please:\n\n\n*\n\n*Go to http://jqueryui.com/demos/resizable/\n\n*Click on inspect with the Chrome/Mozila console the gray resizable element should be id=\"resizable\".\n\n*Apply -webkit-transform: rotate(77deg) or -moz-transform: rotate(77deg)\n\n*Now try to resize that element\n\n\nIs there a way to fix this?\nThank you\n\nA: Change the following functions in JQuery-ui resizable plugin \n_mouseStart: function(event) {\n\nvar curleft, curtop, cursor,\no = this.options,\niniPos = this.element.position(),\nel = this.element;\n\nthis.resizing = true;\n\n// bugfix for http://dev.jquery.com/ticket/1749\nif ( (/absolute/).test( el.css(\"position\") ) ) {\n el.css({ position: \"absolute\", top: el.css(\"top\"), left: el.css(\"left\") });\n} else if (el.is(\".ui-draggable\")) {\n el.css({ position: \"absolute\", top: iniPos.top, left: iniPos.left });\n}\n\nthis._renderProxy();\n\ncurleft = num(this.helper.css(\"left\"));\ncurtop = num(this.helper.css(\"top\"));\n\nif (o.containment) {\n curleft += $(o.containment).scrollLeft() || 0;\n curtop += $(o.containment).scrollTop() || 0;\n}\n\n//Store needed variables\nthis.offset = this.helper.offset();\nthis.position = { left: curleft, top: curtop };\nthis.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };\nthis.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };\nthis.originalPosition = { left: curleft, top: curtop };\nthis.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };\nthis.originalMousePosition = { left: event.pageX, top: event.pageY };\nvar angle=0;\nvar matrix = $(el).css(\"-webkit-transform\") ||\n$(el).css(\"-moz-transform\") ||\n$(el).css(\"-ms-transform\") ||\n$(el).css(\"-o-transform\") ||\n$(el).css(\"transform\");\nif(matrix !== 'none') {\n var values = matrix.split('(')[1].split(')')[0].split(',');\n var a = values[0];\n var b = values[1];\n var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));\n} \nelse { \n var angle = 0; \n}\nif(angle < 0) \n angle +=360;\nthis.angle = angle;\nthi.rad = this.angle*Math.PI/180;\n//Aspect Ratio\nthis.aspectRatio = (typeof o.aspectRatio === \"number\") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1);\n\ncursor = $(el).find(\".ui-resizable-\" + this.axis).css(\"cursor\");\n\n$(\"body\").css(\"cursor\", cursor === \"auto\" ? this.axis + \"-resize\" : cursor);\nvar cornerItem = 0;\nif(this.axis == 'ne')\n cornerItem = 3;\nelse if(this.axis == 'nw')\n cornerItem = 2;\nelse if(this.axis == 'sw')\n cornerItem = 1;\nelse if(this.axis == 'se')\n cornerItem = 0;\nthis.cornerItem = cornerItem;\nvar t1 = this.position.top;\nvar l1 = this.position.left;\nvar w1 = this.size.width;\nvar h1 = this.size.height;\nvar midX = l1 + w1/2;\nvar midY = t1 + h1/2;\nvar cornersX = [l1-midX, l1+w1-midX , l1+w1-midX, l1-midX];\nvar cornersY = [t1-midY, midY-(t1+h1), midY-t1, t1+h1-midY];\nvar newX = 1e10;\nvar newY = 1e10;\nfor (var i=0; i<4; i++) {\n if(i == this.cornerItem){\n this.prevX = cornersX[i]*Math.cos(this.rad) - cornersY[i]*Math.sin(this.rad) + midX;\n this.prevY = cornersX[i]*Math.sin(this.rad) + cornersY[i]*Math.cos(this.rad) + midY;\n }\n}\nel.addClass(\"ui-resizable-resizing\");\nthis._propagate(\"start\", event);\nreturn true;\n},\n\n_mouseDrag: function(event) {\n //Increase performance, avoid regex\n var data,\n el = this.helper, props = {},\n smp = this.originalMousePosition,\n a = this.axis,\n prevTop = this.position.top,\n prevLeft = this.position.left,\n prevWidth = this.size.width,\n prevHeight = this.size.height;\n dx1 = (event.pageX-smp.left)||0,\n dy1 = (event.pageY-smp.top)||0;\n dx = ((dx1)*Math.cos(this.rad) + (dy1)*Math.sin(this.rad));\n dy =((dx1)*Math.sin(this.rad) - (dy1)*Math.cos(this.rad));\n el = this.element;\n var t1 = this.position.top;\n var l1 = this.position.left;\n var w1 = this.size.width;\n var h1 = this.size.height;\n var midX = l1 + w1/2;\n var midY = t1 + h1/2;\n var cornersX = [l1-midX, l1+w1-midX , l1+w1-midX, l1-midX];\n var cornersY = [t1-midY, midY-(t1+h1), midY-t1, t1+h1-midY];\n var newX = 1e10 , newY = 1e10 , curX =0, curY=0;\n for (var i=0; i<4; i++) { \n if(i == this.cornerItem){\n newX = cornersX[i]*Math.cos(this.rad) - cornersY[i]*Math.sin(this.rad) + midX;\n newY = cornersX[i]*Math.sin(this.rad) + cornersY[i]*Math.cos(this.rad) + midY;\n curX = newX - this.prevX;\n curY = newY - this.prevY;\n }\n }\n trigger = this._change[a];\n if (!trigger) {\n return false;\n }\n\n // Calculate the attrs that will be change\n data = trigger.apply(this, [event, dx, dy]);\n\n // Put this in the mouseDrag handler since the user can start pressing shift while resizing\n this._updateVirtualBoundaries(event.shiftKey);\n if (this._aspectRatio || event.shiftKey) {\n data = this._updateRatio(data, event);\n }\n\n data = this._respectSize(data, event);\n\n this._updateCache(data);\n\n // plugins callbacks need to be called first\n this._propagate(\"resize\", event);\n\n this.position.left = this.position.left - curX;\n this.position.top = this.position.top - curY;\n if (this.position.top !== prevTop) {\n props.top = this.position.top + \"px\";\n }\n if (this.position.left !== prevLeft) {\n props.left = this.position.left + \"px\";\n }\n if (this.size.width !== prevWidth) {\n props.width = this.size.width + \"px\";\n }\n if (this.size.height !== prevHeight) {\n props.height = this.size.height + \"px\";\n }\n el.css(props);\n\n if (!this._helper && this._proportionallyResizeElements.length) {\n this._proportionallyResize();\n }\n\n // Call the user callback if the element was resized\n if ( ! $.isEmptyObject(props) ) {\n this._trigger(\"resize\", event, this.ui());\n }\n\n\n return false;\n},\n\n_mouseStop: function(event) {\n\n this.resizing = false;\n var pr, ista, soffseth, soffsetw, s, left, top,\n o = this.options, that = this;\n\n if(this._helper) {\n\n pr = this._proportionallyResizeElements;\n ista = pr.length && (/textarea/i).test(pr[0].nodeName);\n soffseth = ista && $.ui.hasScroll(pr[0], \"left\") /* TODO - jump height */ ? 0 : that.sizeDiff.height;\n soffsetw = ista ? 0 : that.sizeDiff.width;\n\n s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) };\n left = (parseInt(that.element.css(\"left\"), 10) + (that.position.left - that.originalPosition.left)) || null;\n top = (parseInt(that.element.css(\"top\"), 10) + (that.position.top - that.originalPosition.top)) || null;\n\n if (!o.animate) {\n this.element.css($.extend(s, { top: top, left: left }));\n }\n\n that.helper.height(that.size.height);\n that.helper.width(that.size.width);\n\n if (this._helper && !o.animate) {\n this._proportionallyResize();\n }\n\n }\n\n $(\"body\").css(\"cursor\", \"auto\");\n this.element.removeClass(\"ui-resizable-resizing\");\n\n this._propagate(\"stop\", event);\n\n if (this._helper) {\n this.helper.remove();\n }\n return false;\n\n},\n_change: {\n e: function(event, dx, dy) {\n var cs = this.originalSize, sp = this.originalPosition,elwidth, elheight,lleft=0, ttop =0;\n if(this.axis == 'se'){\n elwidth = this.originalSize.width + dx;\n elheight = this.originalSize.height - dy;\n return { height: elheight , width: elwidth };\n }\n else{\n elwidth = this.originalSize.width + dx;\n elheight = this.originalSize.height + dy;\n return { height: elheight , width: elwidth };\n }\n },\n w: function(event, dx, dy) {\n var cs = this.originalSize, sp = this.originalPosition,elwidth, elheight,lleft=0, ttop =0;\n if(this.axis == 'nw'){\n elwidth = cs.width - dx;\n elheight = this.originalSize.height + dy;\n return { height: elheight , width: elwidth };\n\n }\n else{\n elwidth = cs.width - dx;\n elheight = this.originalSize.height - dy;\n return { height: elheight , width: elwidth };\n }\n },\n n: function(event, dx, dy) {\n var cs = this.originalSize, sp = this.originalPosition,elwidth, elheight,lleft=0, ttop =0;\n if(this.axis == 'nw'){\n elwidth = this.originalSize.width - dx;\n elheight = cs.height + dy;\n return { height: elheight , width: elwidth };\n }\n else{\n elwidth = this.originalSize.width + dx;\n elheight = cs.height + dy;\n return { height: elheight , width: elwidth };\n } \n },\n s: function(event, dx, dy) {\n var cs = this.originalSize, sp = this.originalPosition,elwidth, elheight,lleft=0, ttop =0;\n if(this.axis == 'se'){\n elwidth = this.originalSize.width + dx;\n elheight = this.originalSize.height - dy;\n return { height: elheight , width: elwidth };\n }\n else {\n elwidth = this.originalSize.width - dx;\n elheight = this.originalSize.height - dy;\n return { height: elheight , width: elwidth };\n }\n },\n se: function(event, dx, dy) {\n return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));\n },\n sw: function(event, dx, dy) {\n return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));\n },\n ne: function(event, dx, dy) {\n return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));\n },\n nw: function(event, dx, dy) {\n return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));\n }\n},\n\n\nA: The mouse movements for the handles have not been rotated with the element.\nIf you select the right handle (which will be near the bottom if you use rotate(77deg), moving it left will shrink the width of the element, (which will appear similar to the height due to the rotation.)\nTo adjust the element size relative to its center, you will most probably have to update the code that resizes the element by vectoring the mouse movements to adjust the width/height.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/7026061", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "6"}} {"text": "Q: PHP: Mathematical Calculations on a \"Multibyte\" String Representing a Number In PHP, I have a string variable that contains a number. The string is a multibyte string and with UTF-8 encoding.\nWhen I echo the variable($str), it prints 1392. But the problem is that calculations on this variable fails. Consider the output of the following lines:\necho $str; // Prints 1392\n\necho $str + 0; // Prints 0 (it should print 1392)\n\necho $str + 1; // Prints 1 (it should print 1393)\n\necho bin2hex($str); // Prints: dbb1dbb3dbb9dbb2\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/21935259", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: How to get json banner by selecting key:value pair I have a json banner file as \"extract_3month_fromshodan.json\" which have key-value for multiple tag i.e. ip_str=XXX.XX.XXX.XX, port=80, timestamp=\"2018-08-11T04:56:17.312039\", data= \"210!connection successful\" etc. In this way the file has banner for almost 400 IP's.\nSample of source/json banner (extract_3month_fromshodan.json) file:\n{\n \"asn\": \"AS17676\",\n \"hash\": -619087650,\n \"ip\": 2120548325,\n \"isp\": \"Softbank BB\",\n \"transport\": \"udp\",\n \"data\": \"HTTP/1.1 200 OK\\r\\nCache-Control: max-age=120\\r\\nST: upnp:rootdevice\\r\\nUSN: uuid:12342409-1234-1234-5678-ee1234cc5678::upnp:rootdevice\\r\\nEXT:\\r\\nServer: miniupnpd/1.0 UPnP/1.0\\r\\nLocation: http://192.168.2.1:52869/picsdesc.xml\\r\\n\\r\\n\",\n \"port\": 1900,\n \"hostnames\": [\n \"softbank126100255229.bbtec.net\"\n ],\n \"location\": {\n \"city\": \"Toyota\",\n \"region_code\": \"01\",\n \"area_code\": null,\n \"longitude\": 137.14999999999998,\n \"country_code3\": \"JPN\",\n \"latitude\": 35.08330000000001,\n \"postal_code\": \"457-0844\",\n \"dma_code\": null,\n \"country_code\": \"JP\",\n \"country_name\": \"Japan\"\n },\n \"timestamp\": **\"2018-09-12T15:42:34.012436\",**\n \"domains\": [\n \"bbtec.net\"\n ],\n \"org\": \"XXXXXX BB\",\n \"os\": null,\n \"_shodan\": {\n \"crawler\": \"d264629436af1b777b3b513ca6ed1404d7395d80\",\n \"options\": {},\n \"module\": \"upnp\",\n \"id\": null\n },\n \"opts\": {},\n \"ip_str\": **\"126.100.255.229\"**\n}\n\n{\n \"asn\": \"AS17676\",\n \"hash\": 1371060454,\n \"ip\": 2120509894,\n \"isp\": \"Softbank BB\",\n \"transport\": \"udp\",\n \"data\": \"HTTP/1.1 200 OK\\r\\nCache-Control: max-age=1800\\r\\nST: upnp:rootdevice\\r\\nUSN: uuid:63041253-1019-2006-1228-00018efed688::upnp:rootdevice\\r\\nEXT:\\r\\nServer: OS 1.0 UPnP/1.0 Realtek/V1.3\\r\\nLocation: http://192.168.2.1:52881/simplecfg.xml\\r\\n\\r\\n\",\n \"port\": 1900,\n \"hostnames\": [\n \"softbank126100105198.bbtec.net\"\n],\n \"location\": {\n \"city\": \"Yamashitacho\",\n \"region_code\": \"18\",\n \"area_code\": null,\n \"longitude\": 130.55,\n \"country_code3\": \"JPN\",\n \"latitude\": 31.58330000000001,\n \"postal_code\": \"892-0816\",\n \"dma_code\": null,\n \"country_code\": \"JP\",\n \"country_name\": \"Japan\"\n},\n \"timestamp\": **\"2018-08-11T04:56:17.312039\"**,\n \"domains\": [\n \"bbtec.net\"\n],\n \"org\": \"Softbank BB\",\n \"os\": null,\n \"_shodan\": {\n \"crawler\": \"6ff540e4d43ec69d8de2a7b60e1de2d9ddb406dc\",\n \"options\": {},\n \"module\": \"upnp\",\n \"id\": null\n },\n \"opts\": {},\n \"ip_str\": **\"126.100.105.198\"**\n}\n\nNow I want to get another new json banner from the source json file above (extract_3month_fromshodan.json) by filtering the parameter i.e. ip_str=\"126.100.105.198\" and timestamp=\"2018-08-11T04:56:17.312039\". \nThe iterative values for each ip_str and timestamp are to come from separate .csv and/or .txt file. And the output (filtered banner) is needed to save as json format.\nWhat I have done so far :\njq '. | select (.timestamp=\"2018-08-11T04:56:17.312039\") | select(.ip_str==\"\"12X.10X.XXX.X9X\")' extract_3month_fromshodan.json > all.json\n\nIn this way I need to get for almost 290 times of ip_str,timestamp values which are kept in a csv and or .txt file. What I have done is for single ip_str and timestamp. But I could not able to run the above command as a loop.\nExpected Output :\nI should get extracted/filtered json banner including all relevant fields w.r.t 290 IPs and timestamp (kept in csv or txt file) from the main json banner (containing more than 500 IPs). The extraction should be done automatically i.e. like a loop command by one/group of code. the values (timestamp and ip_str) for loop will come from .csv or .txt file.\nFor the mini use case here (filtering 1 out of two ), In input,I have input banner for two IPs i.e. 126.100.255.229 and 126.100.105.198. Now after running loop command I should get banner for ip_str=126.100.105.198 having timestamp = 2018-08-11T04:56:17.312039 as below. In real case I will have banner for more than 500 IPs and timestamp in one json file from I which I have to filtered for 290 IPs and timestamp.\nOutput :\n{\n \"asn\": \"AS17676\",\n \"hash\": 1371060454,\n \"ip\": 2120509894,\n \"isp\": \"Softbank BB\",\n \"transport\": \"udp\",\n \"data\": \"HTTP/1.1 200 OK\\r\\nCache-Control: max-age=1800\\r\\nST: upnp:rootdevice\\r\\nUSN: uuid:63041253-1019-2006-1228-00018efed688::upnp:rootdevice\\r\\nEXT:\\r\\nServer: OS 1.0 UPnP/1.0 Realtek/V1.3\\r\\nLocation: http://192.168.2.1:52881/simplecfg.xml\\r\\n\\r\\n\",\n \"port\": 1900,\n \"hostnames\": [\n \"softbank126100105198.bbtec.net\"\n],\n \"location\": {\n \"city\": \"Yamashitacho\",\n \"region_code\": \"18\",\n \"area_code\": null,\n \"longitude\": 130.55,\n \"country_code3\": \"JPN\",\n \"latitude\": 31.58330000000001,\n \"postal_code\": \"892-0816\",\n \"dma_code\": null,\n \"country_code\": \"JP\",\n \"country_name\": \"Japan\"\n},\n \"timestamp\": \"2018-08-11T04:56:17.312039\",\n \"domains\": [\n \"bbtec.net\"\n],\n \"org\": \"Softbank BB\",\n \"os\": null,\n \"_shodan\": {\n \"crawler\": \"6ff540e4d43ec69d8de2a7b60e1de2d9ddb406dc\",\n \"options\": {},\n \"module\": \"upnp\",\n \"id\": null\n },\n \"opts\": {},\n \"ip_str\": **\"126.100.105.198\"**\n}\n\nActual Result:\nI am getting the filtered output/json banner based on filter parameter (here in this case ip_str and timestamp) for one single combination by running the above code.\n jq '. | select (.timestamp=\"2018-08-11T04:56:17.312039\") | select(.ip_str==\"126.100.105.198\")' extract_3month_fromshodan.json > all.json\nActual Problem:\nBut the problem is I have to run the above code manually for 290 times for IP's which is trouble some. So, how can I use this command so that it could run for other 290 times repetitively automatically.\n\nA: It would seem that the piece of the puzzle you're missing is the ability to pass values into jq using command-line options such as --arg. The following should therefore get you over the hump:\nwhile read -r ts ip\ndo\n jq --arg ts \"$ts\" --arg ip \"$ip\" '\n select(.timestamp==$ts and .ip_str==$ip)\n ' extract_3month_fromshodan.json\ndone < <(cat<\n \n \n \n \n \n \n \n\nSo my question is, what should I do now to make the web page load the css style sheet properly?\n.nav{\nheight: 50px;\nbackground:blue;\n}\n.nav div{\ndisplay: inline-block;\nposition:absolute;\nleft:0;\npadding:15px;\nfont-size:20px;\ncolor:white;\n}\n.nav ul{\nposition:absolute;\nright:5px;\n}\n.nav ul li{\ndisplay:inline-block;\n}\n.nav ul li a{\ncolor:white;\npadding:5px;\n}\n\n\nA: Are you sure about your css file address?\nI suggest you to move your css file in the root of your project and change your address like this:\n\n\n\n\n\nIf it will be work then you should resolve your css address and move your file.\n\nA: You may have to press CTRL + F5 to clear your browser cache, or failing that add a meaningless parameter to the css link to force the browser to take the latest file instead of a cached version eg add ?version=1.1\n\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/63585206", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Jquery - response text as a variable I'm using this following jquery code to insert the responsetext in the div.\n$(\"#div\").load('page.php?val='+myvalue)\n\nIs it possible to get the responsetext into a javascript variable instead of applying it to a div.?\n\nA: You would need to replace .load() with .get() for instance.\n$.get('page.php?val='+myvalue, function( data ) {\n console.log( data ); \n // you might want to \"store\" the result in another variable here\n});\n\nOne word of caution: the data parameter in the above snippet does not necesarilly shim the responseText property from the underlaying XHR object, but it'll contain whatever the request returned. If you need direct access to that, you can call it like\n$.get('page.php?val='+myvalue, function( data, status, jXHR ) {\n console.log( jXHR.responseText ); \n});\n\n\nA: Define a callback function like:\n$(\"#div\").load('page.php?val='+myvalue, function(responseText) {\n myVar = responseText;\n});\n\nNoticed everyone else is saying use $.get - you dont need todo this, it will work fine as above. \n.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )\nSee http://api.jquery.com/load/\n\nA: Yes, you should use $.get method:\nvar variable = null;\n\n$.get('page.php?val='+myvalue,function(response){\n variable = response;\n});\n\nMore on this command: http://api.jquery.com/jQuery.get/\nThere's also a $.post and $.ajax commands\n\nA: Try something like this: \n var request = $.ajax({\n url: \"/ajax-url/\",\n type: \"GET\",\n dataType: \"html\"\n });\n request.done(function(msg) {\n // here, msg will contain your response.\n });\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/8726375", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Why is my DelegatingHandler firing for MVC requests? I have a hybrid MVC/Web API project and I added a simple DelegatingHandler implementation to wrap the API responses. This works great, but the handler is also being invoked for requests to MVC controllers. My understanding is that DelegatingHandlers are only invoked for API routes.\nI'm using OWIN and some attribute routes if that matters. The relevant code in Startup.cs is:\nvar config = new HttpConfiguration();\n// ...\nvar debugging = HttpContext.Current == null || HttpContext.Current.IsDebuggingEnabled;\nconfig.MessageHandlers.Add(new ApiResponseDelegatingHandler(debugging));\n\nThis causes both API and web requests to be wrapped and sent as JSON. Commenting it out resolves the problem but API requests are not wrapped. The error message on a web page is:\n\nNo HTTP resource was found that matches the request URI 'xxx'. No\n route data was found for this request.\n\nI tried forcing the order that routes are registered so that MVC routes are added before Web API but that didn't help.\n\nA: This is easy to reproduce and I'm not sure if it's a bug or not.\n\n\n*\n\n*Create a new web app using the ASP.NET MVC template\n\n*Install the Microsoft.AspNet.WebApi.Owin and\nMicrosoft.Owin.Host.SystemWeb NuGet packages \n\n*Move Web API startup from WebApiConfig.cs to a new Startup.cs file\n\n*Create a DelegatingHandler and add it to config.MessageHandlers in the Startup class\n\n*The DelegatingHandler will be invoked for MVC and API requests\n\n\nI tried several combinations of initializing in Startup.cs and WebApiConfig.cs without success. If you;re not using attribute routing, the solution is to add the handler to the route. If you are, the only workaround I found was to examine the route in the handler and only wrap the API response if the route starts with \"/api/\".\npublic class WtfDelegatingHandler : DelegatingHandler\n{\n protected async override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n {\n var response = await base.SendAsync(request, cancellationToken);\n\n if (request.RequestUri.LocalPath.StartsWith(\"/api/\", StringComparison.OrdinalIgnoreCase))\n {\n response = new HttpResponseMessage()\n {\n StatusCode = HttpStatusCode.OK,\n Content = new StringContent(\"I'm an API response\")\n };\n }\n\n return response;\n }\n\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/36654088", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Combine multiple es6 classes into single library using rollup js How can I import a.js and b.js and export as combined bundle.js in UMD format using rollupjs?\nHere is the example:\n//a.js\nexport default class A {\n...\n}\n\n//b.js\nexport default class B {\n...\n}\n\nMy current rollup.config.js is:\nexport default [\n {\n input: [\"path/a.js\", \"path/b.js\"],\n output: {\n file: \"path/bundle.js\",\n format: \"umd\",\n name: \"Bundle\"\n },\n plugins: [\n // list of plugins\n ]\n }\n}\n\nHowever, this is not working as intended.\nAnything wrong with this config?\nThanks for your help.\n\nA: You need a file to tie them together. So along with a.js and b.js, have a main.js that looks like this:\nimport A from './a';\nimport B from './b';\n\nexport default {\n A,\n B,\n};\n\nThen update your rollup.config.js with input: path/main.js.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/50685153", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "5"}} {"text": "Q: custom placed arrows in magnific-popup I'd like to have arrows placed next to counter, roughly like this:\n< 2 of 19 > \nwhere '<' and '>' are the arrow buttons under the photo in \"figcaption .mfp-bottom-bar\". \nSince the default arrows are in the .mfp-container, I cannot just absolutely position them, because the picture can have any height and width and I need it to be pixel perfect. \nI have one nonfunctional solution:\nin the gallery object in the $('').magnificPopup call\n{\ntCounter: \n\"\" \n+ \n\" %curr%/%total% \"\n+\n\"\"\n}\n\nthis unfortunately doesn't trigger anything even though original arrows still work.\nSo I would like to know either:\n\n\n*\n\n*How can I place the default arrows to the figcaption in the HTML?\n\n*How to make the buttons in the tCounter trigger the previous and next picture functions\n\n\nA: Looks like I didn't read api carefully enough\nvar magnificPopup = $.magnificPopup.instance;\n\n$('body').on('click', '#photo-prev', function() {\n magnificPopup.prev();\n});\n\nwhere #photo-prev is id of previous button\n\nA: I think it's a better solution\nhttps://codepen.io/dimsemenov/pen/JGjHK\njust make a small change if you want to append it to the counter area.\nthis.content.find('div.mfp-bottom-bar').append(this.arrowLeft.add(this.arrowRight));\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/20940348", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Models haskell Beginner Hi there im new to haskell and im stuck on this Question, which is given a formula, it returns the model of that formula, where the Model is a valuation which makes the formula true. An example would be model eg ==[[(\"p\",True),(\"q\",True)],[(\"p\",True),(\"q\",False)]]\nUsing this definiton of Prop:\n data Prop = Falsum -- a contradiction, or\n |Var Variable -- a variable,or \n |Not Prop -- a negation of a formula, or\n |Or Prop Prop -- a disjunction of two formulae,or\n |And Prop Prop -- a conjunction of two formulae, or \n |Imp Prop Prop -- a conditional of two formulae\n deriving (Eq,show)\n\nAnd Valuations:\nvaluations ::[Variable]->[Valuation]\nvaluations [] = [[]]\nvaluations (v:vs) = map ((v,True):) ds ++ map ((v,False):) ds \n where ds = valuations vs \n\nSo far I have this code:\nmodels :: Prop-> Prop-> Bool\nmodels p q = and $ valuations (p == q)\n\nHowever it doesn't seem to be working and I've been stuck on this for a while so was wondering if anyone can help out?\n\nA: This is the same homework question that I am trying to answer. It appears that your understanding of the question is somewhat incorrect. They type line for models should be:\nmodels :: Prop -> [Valuation]\nYou are trying to return only the formulas that give an overall evaluation of True.\nexample = And p (Or q (Not q))\nWhen 'example' is passed to the models function it produces the following list:\n[[(\"p\",True),(\"q\",True)],[(\"p\",True),(\"q\",False)]]\nThis is because an And statement can only ever evaluate to True if both inputs are True. The second input of the And statement, (Or q (Not q)) always evaluates to True as an Or statement always evaluates to True if one of the inputs is True. This is always the case in our example as our Or can be either (Or True (Not True)) or (Or False (Not False)) and both will always evaluate to True. So as long as the first input evaluates to True then the overall And statement will evaluate to True.\nValuations has to be passed a list of Variables and you have a function that does this. If you pass it just the Var \"p\" then you get [[(\"p\",True)],[(\"p\",False)]] as those are the only two possible combinations.\nWhat you (we) are wanting is to pass the Valuations list and only return those that evaluate to True. For example if your list was just Var \"p\" and your formula was Not p then only the second list, [(\"p\",False)], would be returned as p only evaluates to True when you assign False to Not p as Not False = True.\nAlmost forgot, all the possible combinations for And p (Or q (Not q)) --remember (Or q (Not q) is True\nAnd False (False (Not False)) = And False True = False -- [(\"p\",False),(\"q\",False)]]\nAnd False True (True (Not True) = And False True = False -- [(\"p\",False),(\"q\",True)]]\nAnd True (False (Not False)) = And True True = True -- [(\"p\",True),(\"q\",False)]]\nAnd True (True (Not True) = And True True = True -- [(\"p\",True),(\"q\",True)]]\nAs you can see the bottom two lines are the ones the homework question says will be returned. I just haven't worked out how to finish it myself yet. I can get the full list of [Valuations] I just can't work out how to get only the True ones and discard the ones that evaluate False.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/20036293", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-2"}} {"text": "Q: Import error with GeoPandas in Jupyter Notebook on OSX10.11.6 When importing geopandas into my Jupyter Notebook, it throws the following error.\nImportError: dlopen(/opt/anaconda3/lib/python3.7/site-packages/pyproj/_datadir.cpython-37m-darwin.so, 2): Symbol not found: _clock_gettime\n Referenced from: /opt/anaconda3/lib/python3.7/site-packages/pyproj/.dylibs/liblzma.5.dylib (which was built for Mac OS X 10.13)\n Expected in: /usr/lib/libSystem.B.dylib\n in /opt/anaconda3/lib/python3.7/site-packages/pyproj/.dylibs/liblzma.5.dylib\n\nI have installed geopandas through a pip install from the command line.\nMy machine runs OSX 10.11.6 (and can't upgrade).\nI have also tried uninstalling the pip install and installing through conda instead. Importing geopandas in my JN then throws the following error:\nImportError: cannot import name 'Iterable' from 'geopandas._compat' (/opt/anaconda3/lib/python3.7/site-packages/geopandas/_compat.py)\n\n\nA: Problem solved by restarting Jupyter Notebooks.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/64587562", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: I have a problem with uploading the image to the canvas in UWP In my MainPage when I try to run the function(ShowEntity) the image wont show on the background.\nWhen i run it on my player(class in my project) then the image wont show up on the screen.\ni tried to change the format few time but i dont find the problem.\ni think there is something wrong in the ShowEntity function.\nthis is an example of how i try to make it work.\nPlayer _player1 = new Player(500, 500, 150, 150, \"ms-appx:///Asssets/Player5.gif\");\n public class Piece\n {\n private double _x;\n\n private double _y;\n\n public int _width;\n\n private int _height;\n\n public string _image;\n\n public Image _imagesource { get; set; }\n\n public Piece(double x, double y, int width, int height, string image)//BitmapImage imagesource)\n {\n _x = x;\n\n _y = y;\n\n _image = image;\n\n _width = width;\n\n _height = height;\n\n _imagesource = ShowEntity(); \n }\n\n private Image ShowEntity()\n {\n Image _img = new Image();\n\n _img.Source = new BitmapImage(new Uri(_image));\n\n _img.Height = _height;\n\n _img.Width = _width;\n\n Canvas.SetLeft(_img, _x);\n\n Canvas.SetTop(_img, _y);\n\n GameManager.MyCanvas.Children.Add(_img);\n\n return _img;\n }\n\n\nA: The problem looks your image was covered by other element, if you want to show element in the Canvas, you need to set ZIndex for element.\nCanvas.ZIndex declares the draw order for the child elements of a Canvas. This matters when there is overlap between any of the bounds of the child elements. A higher z-order value will draw on top of a lower z-order value. If no value is set, the default is -1.\nIf you want to set image as background, you could set it's ZIndex with samll value. And other way is set Canvas Background with ImageBrush directly like the fllowing.\nMyCanvas.Background = new ImageBrush { ImageSource = new BitmapImage(new Uri(this.BaseUri, \"ms-appx:///Assets/enemy.png\")), Stretch = Stretch.Fill };\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/72437831", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Sound gets distorted on Linux Mint I'm having issues with sound on Linux Mint, it worked fine for long time but suddenly begin to distort sporadically. \nFirst I thought it was software related issue but reinstalled Mint from zero and the problem persist. Then I concluded it was the onboard sound chip failing. \nI decided to use a cheap external soundcard (it's a generic one listed as Texas Instruments PCM2902 Audio Codec on lsusb) and the problem was fixed! So I thought my conclusion was right. \nThe problem is recently I upgraded the cheap external sound card with a better one (Focusrite Scarlett Solo) and with this soundcard I have exactly same problem of crackling and distorted sound that I had with the onboard sound chip (the cheap card still working fine). \nSo at this point I can't tell if it's a problem of hardware or software. I tried the Scarlett Solo on other machine with Ubuntu and worked fine. \nIt is possible that it's a Linux Mint sound config that isn't working either with onboard nor scarlett solo?\n", "meta": {"language": "en", "url": "https://unix.stackexchange.com/questions/547981", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: Orientdb - Traverse all possible N degree separation paths between vertexes Is it possible to find out all possible paths with N degree of separation between two nodes in Orientdb?\n\nA: Try this:\nSELECT $path FROM ( TRAVERSE out() FROM (select from entities where id ='A') WHILE $depth <= N ) where id ='B'\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/46324051", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Find maximum of the difference between each cell of a raster and its surrounding cells I would like to do the following for each cell (let's call it cell_i) of a raster:\n\n\n*\n\n*Define a neighboring region around cell_i (for instance, a region defined by the 8 surrounding cells of cell_i).\n\n*For each cell in the region defined in (1), find the difference between its value and the value of cell_i.\n\n*For all the differences computed in (2), find the minimum.\n\n*Store the minimum value from (3) in a new raster in the same spatial location as cell_i.\n\n\nAre there existing tools that can do this? \nIf not, can you provide pointers on how to script this (ideally in ArcPy)? \nI think that I have the algorithm down (for instance, I would know how to implement this if the raster was a matrix in matlab or 2D array in C#). \nWhat are the commands needed, such as iterating through the original raster and saving values in a new raster?\n\nA: This workaround can be done with GDAL python module. I used a small raster to make easier the corroboration of minimum values of the difference between each raster cell and its neighboring region around it. As the values in the periphery of raster has not 8 surrounding cells, next code add a \"ring\" of -999 values to facilitate the evaluation of differences (incorporated in 'new_list' list) in this area. This 'new_list' was used for determining minimum values before they be incorporated in 'raster' list. This 'raster' list was reshaped as one numpy array, with the same number of rows and columns that the original raster, and used for obtaining resulting raster. \nfrom osgeo import gdal, osr\nimport numpy as np\n\ndriver = gdal.GetDriverByName('GTiff')\nfilename = \"/home/zeito/pyqgis_data/test.tif\"\ndataset = gdal.Open(filename)\nband = dataset.GetRasterBand(1)\n\ncols = dataset.RasterXSize\nrows = dataset.RasterYSize\n\ndata = band.ReadAsArray()\n\n#inserting ring of -999 around data values \ndata = np.insert(data, 0, -999, axis = 0)\ndata = np.insert(data, 0, -999, axis = 1)\ndata = np.insert(data, len(data), -999, axis = 0)\ndata = np.insert(data, len(data[0]), -999, axis = 1)\n\nprint data\n\nraster = [ ]\n\nfor i in range(1, rows + 1):\n for j in range(1, cols + 1):\n val = data[i][j]\n new_list = [ data[i-1][j-1], data[i-1][j], data[i-1][j+1],\n data[i][j-1], data[i][j+1], \n data[i+1][j-1], data[i+1][j], data[i+1][j+1]] \n\n print val\n print new_list\n\n #list with differences\n new_list = [ val - item for item in new_list if item != -999]\n\n #determining minimum\n raster.append(np.min(new_list))\n\n#creating numpy array with minimum values by cell\nraster = np.asarray(np.reshape(raster, (rows, cols)))\n\ntransform = dataset.GetGeoTransform()\n\n# Create gtif file \ndriver = gdal.GetDriverByName(\"GTiff\")\n\noutput_file = \"/home/zeito/pyqgis_data/minimum_differences.tif\"\n\ndst_ds = driver.Create(output_file, \n cols, \n rows, \n 1, \n gdal.GDT_Float32)\n\n#writting output raster\ndst_ds.GetRasterBand(1).WriteArray( raster )\n\n#setting extension of output raster\n# top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution\ndst_ds.SetGeoTransform(transform)\n\nwkt = dataset.GetProjection()\n\n# setting spatial reference of output raster \nsrs = osr.SpatialReference()\nsrs.ImportFromWkt(wkt)\ndst_ds.SetProjection( srs.ExportToWkt() )\n\n#Close output raster dataset \ndataset = None\ndst_ds = None\n\nAbove code was run at the Python Console of QGIS and, there were printed the corroboration values (see next image).\n\nResulting raster was obtained as expected (by using Value Tool plugin to corroborate cell raster values):\n\n\nA: I agree, focal statistics is probably the way to go :\nhttp://desktop.arcgis.com/en/arcmap/10.3/tools/spatial-analyst-toolbox/focal-statistics.htm\nUse the \"Minimum\" setting to get what you are looking for, except that will include the value of the central cell itself if this happens to be the lowest value. Is that acceptable?\n", "meta": {"language": "en", "url": "https://gis.stackexchange.com/questions/221531", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Can I manually make tcp zero window and drop? I have to request specific directory repeatedly. ex) https://example.org/home/dir/aaa/11\nThere is case if http response status code is 200 or else. If 200? read data from raw socket&and if there is 404, drop remainder packets. ex\n int bytes_received = SSL_read(ssl, response, 1370);\n printf(\"%s\\nreceive : %d\", response, bytes_received);\n if(strstr(response, \"HTTP1.1 200 OK\") goto(specific behavior);\nelse{drop; goto(ssl_write)}; // goto first send point, I want to drop remainder packets in kernel buffer from this point. \n puts(\"\");\n\nIs this possible by manually modifying Kernel, or tcp structure or size of sliding window? Or else? If can't, then why? Thx.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/71707205", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Linking models to assets on Swift Playgrounds for iPad (no Xcode) -- iOS App Dev Tutorials StackOverflow. This is my first post. Please excuse any issues with the format.\nI've been trying to teach myself some iOS development in order to create an app to help me at work (I'm a farmer). I do not own a Mac computer and am not able to get one currently, which means no Xcode, but I do have an iPad. Recently, Apple made it possible to develop and publish apps from iPad on Swift Playgrounds.\nI scoured the internet for Playgrounds-specific tutorials and didn't find a lot of stuff, I guess because the functionality is fairly new. The best SwiftUI tutorials I found come from Apple's own iOS App Dev Tutorials. I'm now working through the code for Scrumdinger and I ran into a problem with colors that were defined within an Assets folder in Xcode from .json files.\nPlease, refer to this structure for my question:\nimport Foundation\n\nstruct DailyScrum {\n var title: String\n var attendees: [String]\n var lengthInMinutes: Int\n var theme: Theme\n}\n\nextension DailyScrum {\n static let sampleData: [DailyScrum] =\n [\n DailyScrum(title: \"Design\", attendees: [\"Cathy\", \"Daisy\", \"Simon\", \"Jonathan\"], lengthInMinutes: 10, theme: .yellow),\n DailyScrum(title: \"App Dev\", attendees: [\"Katie\", \"Gray\", \"Euna\", \"Luis\", \"Darla\"], lengthInMinutes: 5, theme: .orange),\n DailyScrum(title: \"Web Dev\", attendees: [\"Chella\", \"Chris\", \"Christina\", \"Eden\", \"Karla\", \"Lindsey\", \"Aga\", \"Chad\", \"Jenn\", \"Sarah\"], lengthInMinutes: 5, theme: .poppy)\n ]\n}\n\nThis piece of code from Apple's tutorial\nimport SwiftUI\n\nstruct CardView: View {\n let scrum: DailyScrum\n \n var body: some View {\n VStack(alignment: .leading) {\n Text(scrum.title)\n .font(.headline)\n Spacer()\n HStack {\n Label(\"\\(scrum.attendees.count)\", systemImage: \"person.3\")\n Spacer()\n Label(\"\\(scrum.lengthInMinutes)\", systemImage: \"clock\")\n .labelStyle(.trailingIcon)\n }\n .font(.caption)\n }\n .padding()\n .foregroundColor(scrum.theme.accentColor)\n }\n}\n\nstruct CardView_Previews: PreviewProvider {\n static var scrum = DailyScrum.sampleData[0]\n static var previews: some View {\n CardView(scrum: scrum)\n .background(scrum.theme.mainColor)\n .previewLayout(.fixed(width: 400, height: 60))\n }\n}\n\nis supposed to generate this preview on Xcode. However, this is what I get on iPad Playgrounds. Both the color and the preview size are off. I don't really care about the preview size, because it doesn't affect the app (this card will be shown into a list and have the appropriate size later), but I'd like to get the color right.\nThe structure Theme that's used to specify the colors is defined in the file Theme.swift:\nimport SwiftUI\n\nenum Theme: String {\n case bubblegum\n case buttercup\n case indigo\n case lavender\n case magenta\n case navy\n case orange\n case oxblood\n case periwinkle\n case poppy\n case purple\n case seafoam\n case sky\n case tan\n case teal\n case yellow\n \n var accentColor: Color {\n switch self {\n case .bubblegum, .buttercup, .lavender, .orange, .periwinkle, .poppy, .seafoam, .sky, .tan, .teal, .yellow: return .black\n case .indigo, .magenta, .navy, .oxblood, .purple: return .white\n }\n }\n var mainColor: Color {\n Color(rawValue)\n }\n}\n\nAnd the specified colors in the enumeration are .json Assets in Xcode with this folder structure. However, the online tutorial doesn't specify how Xcode knows to look for them without any explicit references to these folders or .json files in the code for Theme.swift.\nI tried recreating the same folder structure within Playgrounds (which was painful since you can't import folders), but my output didn't change.\nSo here are my questions:\n\n*\n\n*How does Xcode link assets to custom data models (such as the enum in Theme.swift) that don't specifically reference it? Can I reproduce this with just code in Swift Playgrounds on iPad?\n\n*If I can't do that in Swift Playgrounds, do I have an alternative for creating custom colors and having them work with the enum in Theme.swift?\n\nThank you very much.\n\nA: Following @loremipsum's suggestion, I replaced the mainColor property of the Theme enumeration with\nvar mainColor: Color {\n switch self {\n case .bubblegum: return Color(red: 0.933, green: 0.502, blue: 0.820)\n case .buttercup: return Color(red: 1.000, green: 0.945, blue: 0.588)\n case .indigo: return Color(red: 0.212, green: 0.000, blue: 0.443)\n case .lavender: return Color(red: 0.812, green: 0.808, blue: 1.000)\n case .magenta: return Color(red: 0.647, green: 0.075, blue: 0.467)\n case .navy: return Color(red: 0.000, green: 0.078, blue: 0.255)\n case .orange: return Color(red: 1.000, green: 0.545, blue: 0.259)\n case .oxblood: return Color(red: 0.290, green: 0.027, blue: 0.043)\n case .periwinkle: return Color(red: 0.525, green: 0.510, blue: 1.000)\n case .poppy: return Color(red: 1.000, green: 0.369, blue: 0.369)\n case .purple: return Color(red: 0.569, green: 0.294, blue: 0.949)\n case .seafoam: return Color(red: 0.796, green: 0.918, blue: 0.898)\n case .sky: return Color(red: 0.431, green: 0.573, blue: 1.000)\n case .tan: return Color(red: 0.761, green: 0.608, blue: 0.494)\n case .teal: return Color(red: 0.133, green: 0.561, blue: 0.620)\n case .yellow: return Color(red: 1.000, green: 0.875, blue: 0.302)\n }\n}\n\ncopying the RGB values for the themes from the .json asset files. This has fixed the problem and now colors appear as intended.\nWhat I don't understand is why SwiftUI couldn't process Color(rawValue) for the example data used in CardView(), which was DailyScrum(title: \"Design\", attendees: [\"Cathy\", \"Daisy\", \"Simon\", \"Jonathan\"], lengthInMinutes: 10, theme: .yellow). Sure, .periwinkle might not be previously defined, but .yellow certainly is. In fact, if I rewrite mainColor from Color(rawValue) to Color(.yellow), I get all cards colored yellow without having to pass any RGB value.\nSo what's Color(rawValue) getting from the enumeration that it's unable to process .yellow when passed from rawValue?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/70765916", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Untrusted data is embedded straight into the output I am currently facing Checkmarx scan issue for the below snippet:\n\nThe application's getResponse embeds untrusted data in the generated output with setCatList, at line 10 of MyClass.java.\nThis untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output.\nThis can enable a Reflected Cross-Site Scripting (XSS) attack.\n\nGetCatSP sp = getCatSP(); // GetCatSP extends StoredProcedure\nMap output = sp.getMyData(inParams); // This executes super.execute(inParams) and returns it\nList catList = (List) output.get(\"cat_info\");\n\nresponse.setCatList(catList); \n\nHow do I handle this?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/74993277", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Moving towards a point when said point is within a radius Just as a disclaimer, I am new to Python.\n(this is in graphics.py)\nI have two points on a plane. One point \"a\" is the dot with a circle around it. Currently they look something akin to this:\n\nAssume that point \"a\" is moving on a trajectory that will cause the circle to touch the other point.\nMy goal is to have point \"a\" begin moving towards the other point once the other point is within the bounds of the circle surrounding point \"a\" kinda like this situation:\n\nIt should also be noted that point \"a\" is the only point that is supposedly moving.\nUltimately, I want the points to touch.\nIs there a way for me to do this? One possible solution I can currently think of is to have point \"a\" move to the (x,y) coordinates on which the other point lies, but that would mean that point \"a\" isn't moving to the other point due to the circle coming in contact with the other point.\nAny and all help is appreciated!\n\nA: here's some pseudo code\nif (a.x-b.x)**2 + (a.y-b.y)**2 <= a.radius**2:\n vec_a_b = b-a # or you can do this component wise \n a.velocity = normalized(vec_a_b)*a.velocity.magnitude\n\nthis assumes point a has a velocity vector, which encodes the direction it's currently headed in and its speed.\nnow you can use the velocity to move a:\na.x += a.velocity.x\na.y += a.velocity.y\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/54745288", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Ruby on Rails - Activeadmin - Update model with virtual attribute I have a activeadmin form to which allows to add a youtube URL. I validate this URL in my video model. It does works well when I want to add a new video but does nothing when I'm editing the video.\napp/admin/video.rb :\nActiveAdmin.register Media, as: 'Videos' do \nform do |f|\n f.inputs \"Add youtube video\" do\n f.input :category\n f.semantic_errors :error\n f.has_many :videos, allow_destroy: true do |g|\n g.input :mylink, :label => \"Youtube link : \", :type => :text\n end\n actions\n end\n end\nend\n\nmodel/video.rb :\nclass Video < ApplicationRecord\n belongs_to :media\n attr_accessor :mylink \n YT_LINK_FORMAT = /\\A.*(youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=|\\&v=)([^#\\&\\?]*).*\\z/i\n before_create :before_add_to_galerie\n before_update :before_add_to_galerie\n\n def before_add_to_galerie\n uid = @mylink.match(YT_LINK_FORMAT)\n self.uid = uid[2] if uid && uid[2]\n if self.uid.to_s.length != 11\n self.errors.add(:mylink, 'is invalid.')\n throw :abort\n false\n elsif Video.where(uid: self.uid).any?\n self.errors.add(:mylink, 'is not unique.')\n throw :abort\n false\n end\nend\n\nvalidates :mylink, presence: true, format: YT_LINK_FORMAT\nend\n\nIt looks like the before_update method is never triggered.\nHow can I make my edit work ?\nEDIT :I figured out that it is calling the before_update link for the Media model and not for the Video one.But the create is fine.\n\nA: Let me try to rephrase the issue:\n\n\n*\n\n*You have a model Video\n\n*Video has a virtual attribute my_link\n\n*Video has a before_update callback before_add_to_galerie\n\n*You want this callback to trigger when only my_link was changed\n\n\ndoes this look correct?\nIf so you have 2 options, first - if you have updated_at change it along with my_link\nclass Video < ApplicationRecord\n attr_reader :my_link\n # ...\n def my_link=(val)\n return val if val == my_link\n @my_link = val\n self.updated_at = Time.zone.now\n end\nend\n\nor you can use ActiveModel\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/43455063", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Retrieve queue length with Celery (RabbitMQ, Django) I'm using Celery in a django project, my broker is RabbitMQ, and I want to retrieve the length of the queues. I went through the code of Celery but did not find the tool to do that. I found this issue on stackoverflow (Check RabbitMQ queue size from client), but I don't find it satisfying.\nEverything is setup in celery, so there should be some kind of magic method to retrieve what I want, without specifying a channel / connection.\nDoes anyone have any idea about this question ?\nThanks !\n\nA: Here is an example on how to read the queue length in rabbitMQ for a given queue:\ndef get_rabbitmq_queue_length(q):\n from pyrabbit.api import Client\n from pyrabbit.http import HTTPError\n\n count = 0\n\n try:\n cl = Client('localhost:15672', 'guest', 'guest')\n if cl.is_alive():\n count = cl.get_queue_depth('/', q)\n except HTTPError as e:\n print \"Exception: Could not establish to rabbitmq http api: \" + str(e) + \" Check for port, proxy, username/pass configuration errors\"\n raise\n\n return count\n\nThis is using pyrabbit as previously suggested by Philip\n\nA: PyRabbit is probably what you are looking for, it is a Python interface to the RabbitMQ management interface API. It will allow you to query for queues and their current message counts.\n\nA: You can inspect the workers in celery by using inspect module. Here is the guide.\nAlso for RabbitMQ there are some command line command.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/17863626", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "11"}} {"text": "Q: How to add image in google chart function test()\n{\n$array['cols'][] = array('type' => 'string');\n$array['cols'][] = array('type' => 'string');\n$array['cols'][] = array('type' => 'string');\n\n$array['rows'][] = array('c' => array( array('v'=>'Name'), array('v'=>22)) );\n$array['rows'][] = array('c' => array( array('v'=>'Name1'), array('v'=>26)));\n$array['rows'][] = array('c' => array( array('v'=>'Name2'), array('v'=>12)));\n\nreturn $array;\n}\nprint json_encode(test());\n\nI am using above code to build organization chart in using google chart. I want to add image and designation with name. Could you please tell me how can i modify the code.\n\nA: I Tried to solve your problem.\nWe can use {allowHtml:true} to embed and process HTML code with Google chart.\nfunction drawChart() {\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Name');\n data.addColumn('string', 'Parent');\n\n data.addRows([\n [{\n v: 'parent_node',\n f: 'Parent Node'\n },\n null],\n [{\n v: 'child_node_1',\n f: 'Child Node '\n }, 'parent_node'],\n [{\n v: 'child_node_2',\n f: 'Child Node'\n }, 'parent_node']\n ]);\n\n var chart = new google.visualization.OrgChart(document.querySelector('#chart_div'));\n chart.draw(data, {\n allowHtml: true\n });\n}\ngoogle.load('visualization', '1', {\n packages: ['orgchart'],\n callback: drawChart\n});\n\nHere I created Example Please check it: https://jsfiddle.net/1gvwLy8n/5/\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/26814414", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: php call function name from array hi i want get function name from array\nhow to do that\npublic function cuturls($url){\n $long_url = urlencode($url);\n $api_token = 'xxx';\n $api_url = \"https://cut-urls.com/api?api={$api_token}&url={$long_url}\";\n $result = @json_decode(file_get_contents($api_url),TRUE);\n if($result[\"shortenedUrl\"]) {\n return $result[\"shortenedUrl\"];\n } else {\n return $this->ouo($url);\n }\n}\n\nwant to convert this function\npublic function docut($url){\n global $filesize77;\n global $cutpost;\n if(empty($cutpost) or $cutpost==='cutearn'){\n if($filesize77 <= '1073741824'){\n return array($this->cuturls($url),'cuturls');\n }else if($filesize77 > '1073741824' and $filesize77 <= '2147483648'){\n return array($this->cuturls($this->adlinkme($url)),'cuturls');\n }else if($filesize77 > '2147483648' and $filesize77 <= '3221225472'){\n return array($this->cuturls($this->adlinkme($this->cutearn($url))),'cuturls');\n }\n }\n\nwant to convert for this type by using array have functions names\nhow to callback\npublic function docut($url){\n global $filesize77;\n global $cutpost;\n $cutarray = array('cuturls', 'adlinkme', 'cutearn', 'cutwin');\n if(empty($cutpost) or $cutpost===$cutarray[3]){\n if($filesize77 <= '1073741824'){\n return array($this->$cutarray[0]($url),$cutarray[0]);\n }else if($filesize77 > '1073741824' and $filesize77 <= '2147483648'){\n return array($this->$cutarray[0]($this->$cutarray[1]($url)),$cutarray[0]);\n }else if($filesize77 > '2147483648' and $filesize77 <= '3221225472'){\n return array($this->$cutarray[0]($this->$cutarray[1]($this->$cutarray[2]($url))),$cutarray[0]);\n }\n }\n\n\nA: call_user_func_array($func,$parameters);\n\n$func is function name as string , $parameters is parameteres to $func as array.\nread the doc :-\nhttp://php.net/manual/en/function.call-user-func-array.php\nusage:-\n\n\nWhen it put in your question:-\npublic function docut($url){\n global $filesize77;\n global $cutpost;\n $cutarray = array('cuturls', 'adlinkme', 'cutearn', 'cutwin');\n if(empty($cutpost) or $cutpost===$cutarray[3]){\n if($filesize77 <= '1073741824'){\n return array(call_user_func_array(array($this,$cutarray[0]),$url),$cutarray[0]);\n }else if($filesize77 > '1073741824' and $filesize77 <= '2147483648'){\n return array( call_user_func_array(array($this,$cutarray[0]),call_user_func_array(array($this,$cutarray[0]),$url)),$cutarray[0]);\n }else if($filesize77 > '2147483648' and $filesize77 <= '3221225472'){\n return array(call_user_func_array(array($this,$cutarray[0]),call_user_func_array(array($this,$cutarray[1]),call_user_func_array(array($this,$cutarray[2]),$url))),$cutarray[0]);\n }\n }\n}\n\n\nA: Just use the {..}(..) syntax. I.e $this->{$cutarray[0]}(...)\npublic function docut($url){\n global $filesize77;\n global $cutpost;\n $cutarray = ['cuturls', 'adlinkme', 'cutearn', 'cutwin'];\n if(empty($cutpost) or $cutpost===$cutarray[3]){\n if($filesize77 <= '1073741824') {\n return [$this->{$cutarray[0]}($url), $cutarray[0]];\n } else if($filesize77 > '1073741824' and $filesize77 <= '2147483648'){\n return [$this->{$cutarray[0]}($this->$cutarray[1]($url)), $cutarray[0]];\n } else if($filesize77 > '2147483648' and $filesize77 <= '3221225472') {\n return [$this->{$cutarray[0]}($this->{$cutarray[1]}($this->{$cutarray[2]}($url))), $cutarray[0]];\n }\n }\n\nIf you add more cases to this function, you should really think about wrapping this inside an loop or something else. Currently your code is very hard to read and understand...\npublic function docut($url){\n global $filesize77;\n global $cutpost;\n $cutarray = ['cuturls', 'adlinkme', 'cutearn', 'cutwin'];\n if(empty($cutpost) or $cutpost === $cutarray[3]) {\n switch {\n case: $filesize77 > 0x80000000 && $filesize77 <= 0xC0000000:\n $url = $this->{$cutarray[2]}($url);\n case: $filesize77 > 0x40000000 && $filesize77 <= 0x80000000:\n $url = $this->{$cutarray[1]}($url);\n case $filesize77 < 0x40000000;\n $url = $this->{$cutarray[0]}($url);\n }\n\n return [$url, $cutarray[0]];\n }\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/47798244", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: How to set value in createMaterialBottomTabNavigator from AsyncStorage I am using createMaterialBottomTabNavigator , but before export that i want to assign value for its navigationOptions \nbarStyle: { backgroundColor:someVariable}\n\nhere problem is , i want to get value of someVariable from AsyncStorage.\nAnd it returns promise , because of that createMaterialBottomTabNavigator is getting exported first , after that I get value of someVariable . I can't write \nexport default in async function otherwise createMaterialBottomTabNavigator will returned as promise again .Please give suggestions.\nI am using redux , but there also i have to update store from AsyncStorage before exporting createMaterialBottomTabNavigator.\nSample code \n// tabnavigator.js\n// I Imported this file in app.js , there i use this in \ncreateSwitchNavigator\n// so this will execute on app starts only\n\nvar theme = {};\nAsyncStorage.getItem('theam').then((res) => {\n theme = res\n});\n\n// I want theme from storage because i am going to apply theme on app \n// start\n// Here I can get theme from ReduxStore but i returns the initial one \n\nconst DashTabsNav = createMaterialBottomTabNavigator({\n ProfileStack: {\n screen: ProfileStack,//this is stack created with \ncreateStacknavigator , \n navigationOptions: {\n tabBarIcon: ({ tintColor }) => (),\n },\n },\n Messages: {\n screen: MessageScreen,\n navigationOptions: {\n tabBarColor: 'red',\n tabBarIcon: ({ tintColor }) => ()\n },\n\n },\n},\n {\n activeColor: 'white',\n inactiveColor: 'white',\n barStyle: { backgroundColor: theme.themeColor },\n },\n);\nexport default DashTabsNav;\n\n\nA: Read https://reactnavigation.org/docs/en/headers.html#overriding-shared-navigationoptions\nwithin your ProfileScreen and MessageScreen override the header color by doing\n static navigationOptions = ({ navigation, navigationOptions }) => {\n return {\n headerStyle: {\n backgroundColor: theme.themeColor,\n },\n };\n };\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/56649973", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Check if any of the files within a folder contain a pattern then return filename I'm writing a script that aim to automate the fulfill of some variables and I'm looking for help to achieve this:\nI have a nginx sites-enabled folder which contain some reverses proxied sites.\nI need to:\n\n*\n\n*check if a pattern $var1 is found in any of the files in \"/volume1/nginx/sites-enabled/\"\n\n*return the name of the file containing $var1 as $var2\n\nMany thanks for your attention and help!\nI have found some lines but none try any files in a folder\nif grep -q $var1 \"/volume1/nginx/sites-enabled/testfile\"; then\n echo \"found\"\nfi\n\n\nA: This command is the most traditional and efficient one which works on any Unix\nwithout the requirement to have GNU versions of grep with special features.\nThe efficiency is, that xargs feeds the grep command as many filenames as arguments as it is possible according to the limits of the system (how long a shell command may be) and it excecutes the grep command by this only as least as possible.\nWith the -l option of grep it shows you only the filename once on a successful pattern search.\nfind /path -type f -print | xargs grep -l pattern\n\n\nA: Assuming you have GNU Grep, this will store all files containing the contents of $var1 in an array $var2.\nfor file in /volume1/nginx/sites-enabled/*\ndo\n if grep --fixed-strings --quiet \"$var1\" \"$file\"\n then\n var2+=(\"$file\")\n fi\ndone\n\nThis will loop through NUL-separated paths:\nwhile IFS= read -d'' -r -u9 path\ndo\n \u2026something with \"$path\"\ndone 9< <(grep --fixed-strings --files-without-match --recursive \"$var1\" /volume1/nginx/sites-enabled)\n\n\nA: find and grep can be used to produce a list of matching files:\nfind /volume1/nginx/sites-enabled/ -type f -exec grep -le \"${var1}\" {} +\n\nThe \u2018trick\u2019 is using find\u2019s -exec and grep\u2019s -l.\nIf you only want the filenames you could use:\nfind /volume1/nginx/sites-enabled/ -type f -exec grep -qe \"${var1}\" {} \\; -exec basename {} \\;\n\nIf you want to assign the result to a variable use command substitution ($()):\nvar2=\"$(find \u2026)\"\n\nDon\u2019t forget to quote your variables!\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/56355405", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Set annotation params from environment variable Say you have:\n@NotBlank(message = \"forenames must not be blank\")\n...and a dubious requirement comes along that the message needs to be configured via an environment variable.\nIt looks like in with SpringBoot (as per here) you can do something like:\n@NotBlank(message = '${MESSAGE}')\nIs there a standard/known way to do this outside of spring?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/72994357", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: UINavigationBar title label text Is it possible to get the title text to shrink to fit in the UINavigationBar in iOS.\n(for portrait iPhone app with no autolayout).\nI'm setting the title bar dynamically but sometimes the text is too long and at the moment it just cuts it off with an ellipsis.\ni.e. \"This is the t...\"\nI'd like it to shrink the text instead.\n\nA: Xcode 7.1 - Swift 2.0\n\n\n//Adding Title Label\n var navigationTitlelabel = UILabel(frame: CGRectMake(0, 0, 200, 21))\n navigationTitlelabel.center = CGPointMake(160, 284)\n navigationTitlelabel.textAlignment = NSTextAlignment.Center\n navigationTitlelabel.textColor = UIColor.whiteColor()\n navigationTitlelabel.text = \"WORK ORDER\"\n self.navigationController!.navigationBar.topItem!.titleView = navigationTitlelabel\n\n\nA: You can create your own title view to make it. \nSomething like this: \n- (void)viewDidLoad\n{\n [super viewDidLoad];\n\n //Do any additional setup after loading the view, typically from a nib.\n UILabel *titleLabelView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)]; //<<---- Actually will be auto-resized according to frame of navigation bar;\n [titleLabelView setBackgroundColor:[UIColor clearColor]];\n [titleLabelView setTextAlignment: NSTextAlignmentCenter];\n [titleLabelView setTextColor:[UIColor whiteColor]];\n [titleLabelView setFont:[UIFont systemFontOfSize: 27]]; //<<--- Greatest font size\n [titleLabelView setAdjustsFontSizeToFitWidth:YES]; //<<---- Allow shrink\n // [titleLabelView setAdjustsLetterSpacingToFitWidth:YES]; //<<-- Another option for iOS 6+\n titleLabelView.text = @\"This is a Title\";\n\n navigationBar.topItem.titleView = titleLabelView;\n\n //....\n}\n\nHope this helps.\n\nA: I used this code for swift 4 (note label rect is NOT important..)\nfunc navBar()->UINavigationBar?{\n let navBar = self.navigationController?.navigationBar\n return navBar\n }\n\n\noverride func viewDidLoad() {\n super.viewDidLoad()\n\n setTNavBarTitleAsLabel(title: \"VERYYYY VERYYYY VERYYYY VERYYYY VERYYYY VERYYYY VERYYYY LONGGGGGG\")\n }\n\n // will shrink label...\n\n func setTNavBarTitleAsLabel(title: String, color: UIColor ){\n\n // removed some code..\n\n let navigationTitlelabel = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 20))\n navigationTitlelabel.numberOfLines = 1\n navigationTitlelabel.lineBreakMode = .byTruncatingTail\n\n navigationTitlelabel.adjustsFontSizeToFitWidth = true\n navigationTitlelabel.minimumScaleFactor = 0.1\n navigationTitlelabel.textAlignment = .center\n navigationTitlelabel.textColor = color\n navigationTitlelabel.text = title\n\n if let navBar = navBar(){\n //was navBar.topItem?.title = title\n\n self.navBar()?.topItem?.titleView = navigationTitlelabel\n //navBar.titleTextAttributes = [.foregroundColor : color ?? .black]\n }\n }\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/14505331", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "6"}} {"text": "Q: Python 2.6 Generator expression must be parenthesized if not sole argument I rewrote the following Python 2.7+ code as follows for Python 2.6.\nPython 2.7+ \noptions = {key: value for key, value in options.items() if value is not None}\n\nPython 2.6\noptions = dict((key, value) for key, value in options.items() if value is not None)\n\nBut I am getting the following error\nSyntaxError: Generator expression must be parenthesized if not sole argument\n\nWhat did I do wrong?\n\nA: I found this question while looking for the \"SyntaxError: Generator expression must be parenthesized\" in a \"code wars\" kata I did in 3.8.\nMy presumably similar example was:\nmax(word for word in x.split(), key=score)\n\nI was looking for the word in the given string x with the highest score that was calculated by the existing but (at least here) irrelevant method named score. After reducing my code down to this statement, I found the problem in word for word in x.split() not being in parenthesized seperately from the second argument. Changing that made my code run just fine:\nmax((word for word in x.split()), key=score)\n\nSince your example does not have additional arguments but there is a comma between key dan value, I assume there is a hiccup in the parser when faced with comma and generator expressions. Avoiding to unpack the item and thus removing the comma should solve the problem:\noptions = dict(item for item in options.items() if item[1] is not None)\n\nWe only have to fetch the value from the tuple instead of using a separate variable.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/50935610", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How do I require a node module in my client side javascript? I am trying to build a natural language processing bot using javascript and jQuery for the logic and node and express as the framework. I discovered a natural language processing facility that would be extremely useful for my project https://github.com/NaturalNode/natural unfortunately the documentation is sparse and I have only been using node for a couple of weeks.\nThis is the code I have on my server side app.js \n var natural = require('natural'),\n tokenizer = new natural.WordTokenizer();\n stemmer.attach();\n var express = require(\"express\");\n app = express();\n app.set(\"view engine\", \"ejs\");\n app.use(express.static(__dirname + '/public'));\n\nI am requiring the 'natural' module here but I am unable to use the methods that are outlined in the documentation. \nvar natural = require('natural'),\ntokenizer = new natural.WordTokenizer();\nconsole.log(tokenizer.tokenize(\"your dog has fleas.\"));\n// [ 'your', 'dog', 'has', 'fleas' ]\n\nThe method 'tokenizer' is undefined. I have done quite a bit of research on this and looked into using module.export and passing variables through the app.get function for the index.ejs page I am using but I have been unsuccessful so far.\nNOTE: The javascript file I am trying to use these methods in is located in the public/javascript directory while the app.js file is located in the main project directory. I have tried to require the 'natural' package directly in the javascript file I am trying to use the methods in but an error was thrown saying require is an undefined method. \nhere is the package.json file:\n {\n \"name\": \"JSAIN\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"app.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"ejs\": \"^2.3.1\",\n \"express\": \"^4.12.3\",\n \"natural\": \"^0.2.1\",\n \"underscore\": \"^1.8.2\"\n }\n }\n\n\nA: maybe you can try browserify which allow you to use some npm modules in browser.\n\nA: Converting my comment into an answer...\nThe natural module says it's for running in the node.js environment. Unless it has a specific version that runs in a browser, you won't be able to run this in the browser. \n\nA: have you install that module with global mode and have defined that in package.json? Otherwise, try this:\nnpm install -g natural\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/29326211", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: App closes when item on bottom navigation view is selected to replace fragment My app closes, not crashing but just goes to the background,when i select item on the bottom navigation. i was using material botton navigation view but the problem persisted so i decided to use AHBottomNavigation library but the issue is still there.\nSet up bottom navigation code\n AHBottomNavigation bottomNavigation = findViewById(R.id.navigation);\n\n AHBottomNavigationItem item1 = new AHBottomNavigationItem(getString(R.string.orders), R.drawable.ic_m_orders);\n AHBottomNavigationItem item2 = new AHBottomNavigationItem(getString(R.string.pickup), R.drawable.ic_m_location);\n\n bottomNavigation.setAccentColor(Color.parseColor(\"#2DA1D1\"));\n bottomNavigation.setInactiveColor(Color.parseColor(\"#C4C4C4\"));\n bottomNavigation.addItem(item1);\n bottomNavigation.addItem(item2);\n bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);\n bottomNavigation.setOnTabSelectedListener(tabSelectedListener);\n bottomNavigation.setBehaviorTranslationEnabled(true);\n\n openFragment(fragmentHolder);\n\n private void openFragment(final Fragment fragment) {\n FragmentManager fragmentManager = getSupportFragmentManager();\n FragmentTransaction transaction = fragmentManager.beginTransaction();\n transaction.replace(R.id.host_fragment, fragment);\n transaction.addToBackStack(null);\n transaction.commit();\n\n}\nprivate final AHBottomNavigation.OnTabSelectedListener tabSelectedListener = (position, wasSelected) -> {\n\n switch (position) {\n case 0:\n openFragment(fragmentHolder);\n break;\n case 1:\n openFragment(PickupStationFragment.newInstance());\n break;\n }\n\n return true;\n};\n\nthe xml code\n \n\n \n\n\nA: I found the solution, i was overriding ondestroy view on one of my fragment and added requireActivity.finish() in the overridden method\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/66559893", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Brand new soldering iron tip turns black, solder won't stick I have a brand new soldering iron, the tip turned black while heating on my first use, and now solder won't stick to it, it just rolls off.\nAll the answers in similar questions here tell me to stick solder to the tip but it won't stick because the tip is black. I have never used this iron and have been unable to tin it.\nI've tried cleaning with a damped (not wet) sponge as several people suggested, but nothing comes off with several minutes of scrubbing.\nHow do I solve this chicken / egg situation?\n\n\nA: As pointed out in the comments and other answer, you need to clean the tip.\nThere are two options for cleaning, depending on what you have, or what came with the Iron.\n\n\n*\n\n*A Compressed Cellulose sponge, which has been wetted with water. You want it to be damp, but not soaking wet. If it is soaking it just cools the tip down and doesn't help clean it. If it is dry, the sponge will burn, putting more crap on the tip.\n\n\n\nImage from here\n\n\n*A Brass Wire cleaning sponge. These are not the same as steel wool. Steel wool is an abrasive which will damage the tip (as will sand paper). The tips are made internally of copper which is great for heat transfer, but will be damaged/dissolved by the tin in the solder. To allow the tip to work, it is plated with Iron which will withstand the soldering process, and is key to ensuring the tip can be used. This plating is thin and can be easily damaged by abrasives, or scratching against things. The brass wire sponges are not abrasive, they are like the scrubbing pads people sometimes use for washing up. They look like this:\n\n\n\nImage from here\n\nFor both cases you need to do the same thing, basically just drag the tip across the sponge a few times (may only take a couple, may take a dozen, depends on how much grot is on there) at a sort of medium pace (like washing up really). You should see the tip start to go shiny and silver. Once it is, put some solder on, and then again wipe on the sponge. Finally put some more solder on (tin the tip) when not in use.\n\nSo why did it happen so quick? I can think of a couple of reasons:\n\n\n*\n\n*There was some coating on the tip to protect it when sitting on a shelf for ages. Not sure if this would be done - if it was tinned, that should be enough, but you never know.\n\n*If it is not a temperature controlled iron, then who knows what temperature the tip is at - ideally it should be around 360-380\u00b0C, but the non-controlled ones can be anywhere, even as much as 450+\u00b0C. The higher temperature will cause the tip to oxidise from stuff in the air much faster. Hopefully you should be able to clean it off on a sponge. Then once clean always leave it\n\nA: Clean the tip with a brass cleaning sponge.\nNow, when you finish using it, store the tip with solder melted on it. Do not clean it off before you're done, the solder layer keeps the metal of the iron from oxidizing and easily cleans off next time the iron gets hot.\n", "meta": {"language": "en", "url": "https://electronics.stackexchange.com/questions/204026", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "12"}} {"text": "Q: How to use angular.filter in controller's function? On change select choosen type and value passed to the function (ng-change=\"sortEvents(type, value)\")\nI need to filter all elements of $scope.events to select elements with \"state\" equal to \"NSW\" only.\n$scope.sortEvents = function(type, value, $scope, $filter) {\n $scope.events = $filter('filterBy')($scope.events, ['state'], 'NSW');\n console.log($scope.events);\n }\nBut in console is see http://prntscr.com/bmyj74\nAngular filter works appropriately using ng-repeat, and in app.js in dependencies, I have specified angular.filter.\n\nA: You can write your filter like this:\n$scope.events = $filter('filter')($scope.events, function(e){\n return e.state === 'NSW';\n});\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/38118890", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Easiest way to write and read an XML I'd like to know what is the easiest way to write to and parse a XML file in Android.\nMy requirement is very simple. A sample file would be something like:\n\n\nAnd I only want to retrieve an item by the ID and read price and Qty.\nI was referring to Using XmlResourceParser to Parse Custom Compiled XML, but wondering if there is a much lightweight way to do something trivial as this (still using tags).\n\nA: If it's really that simple, you can just write it with printf() or similar.\nFor parsing, you're best off using a real XML parser (perhaps the SimpleXML that @netpork suggested). But for something truly this trivial, you could just use regexes -- here's my usual set, from which you'd need mainly 'attrlist' and 'stag' (for attribute list and start-tag).\nxname = \"([_\\\\w][-_:.\\\\w\\\\d]*)\"; # XML NAME (imperfect charset)\nxnmtoken = \"([-_:.\\\\w\\\\d]+)\"; #\nxncname = \"([_\\\\w][-_.\\\\w\\\\d]*)\"; #\nqlit = '(\"[^\"]*\"|\\'[^\\']*\\')'; # Includes the quotes\nattr = \"$xname\\\\s*=\\\\s*$qlit\"; # Captures name and value\nattrlist = \"(\\\\s+$attr)*\"; #\nstartTag = \"<$xname$attrlist\\\\s*/?>\"; #\nendTag = \"\"; #\ncomment = \"()\"; # Includes delims\npi = \"(<\\?$xname.*?\\?>)\"; # Processing instruction\ndcl = \"(]+>)\"; # Markup dcl (imperfect)\ncdataStart = \"()\"; # Marked section close\ncharRef = \"&(#\\\\d+|#[xX][0-9a-fA-F]+);\"; # Num char ref (no delims)\nentRef = \"&$xname;\"; # Named entity ref\npentRef = \"%$xname;\"; # Parameter entity ref\nxtext = \"[^<&]*\"; # Neglects ']]>'\nxdocument = \"^($startTag|$endTag|$pi|$comment|$entRef|$xtext)+\\$\";\n\nA draft of the XML spec even included a \"trivial\" grammar for XML, that can find node boundaries correctly, but not catch all errors, expanding entity references, etc. See https://www.w3.org/TR/WD-xml-lang-970630#secF.\nThe main drawback is that if you run into fancier data later, it may break. For example, someone might send you data with a comment in there, or a syntax error, or an unquoted attribute, or using &quo;, or whatever.\n\nA: You can use XmlPullParser for first time parsing. Then I would suggest storing the data in sqllite or shared preferences depending on the complexity of queries or size of data.\nhttps://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/8240957", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "9"}} {"text": "Q: Java Spigot, Popultate and block.setType cause StackOverflow i'm actually developing a little ore remover plugin using Spigot 1.15 API.\nHere is my problem. when i use block.setType() in my populate method (which is called by minecraft generator), it seems to call back the minecraft generator.\nThis cause a StackOverflowError. See this log\nMy question is, how could i do to stop this callback.\nHere are my sources :\nPlugin.yml :\n#####################################\n# General Plugin Informations #\n#####################################\n\nname: Remover\n\nauthor: me\n\nversion: 1.0\n\napi-version: 1.15\nprefix: Remover\n\nmain: OresRemover.Remover\n\nload: startup\n\nRemover Class:\npackage OresRemover;\n\nimport org.bukkit.plugin.java.JavaPlugin;\n\npublic class Remover extends JavaPlugin {\n\n @Override\n public void onEnable() {\n getServer().getPluginManager().registerEvents(new RemoverListener(), this);\n }\n\n @Override\n public void onDisable() {\n }\n}\n\nRemoverListener Class\npackage OresRemover;\n\nimport org.bukkit.event.EventHandler;\nimport org.bukkit.event.Listener;\nimport org.bukkit.event.world.WorldInitEvent;\n\nimport java.util.logging.Logger;\n\npublic class RemoverListener implements Listener {\n\n Logger logger;\n\n public RemoverListener () {\n logger = Logger.getLogger(\"Minecraft\");\n\n }\n\n @EventHandler\n public void onWorldInit(WorldInitEvent e) {\n if (e.getWorld().getName().equals(\"world\"))\n e.getWorld().getPopulators().add(new CustomPopulator());\n }\n}\n\nCustomPopulator Class:\npackage OresRemover;\n\nimport org.bukkit.Chunk;\nimport org.bukkit.Material;\nimport org.bukkit.World;\nimport org.bukkit.entity.Entity;\nimport org.bukkit.entity.Player;\nimport org.bukkit.generator.BlockPopulator;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.logging.Logger;\n\npublic class CustomPopulator extends BlockPopulator {\n Logger logger;\n\n public CustomPopulator() {\n logger = Logger.getLogger(\"Minecraft\");\n\n }\n\n @Override\n public void populate(World world, Random random, Chunk chunk) {\n int X, Y , Z;\n for (X = 0; X < 16; X++)\n for (Z = 0; Z < 16; Z++) {\n for (Y = world.getMaxHeight() - 1; chunk.getBlock(X, Y, Z).getType() == Material.AIR; Y--);\n logger.info(\"Surface at x:\" + X + \" y:\" + Y + \" z:\" + Z);\n for (; Y > 0; Y--)\n if (isOreType(chunk.getBlock(X, Y, Z).getType())) {\n logger.info(\"Cave block found at x:\" + X + \" y:\" + Y + \" z:\" + Z + \" and Type is \" + chunk.getBlock(X, Y, Z).getType().toString());\n chunk.getBlock(X, Y, Z).setType(Material.STONE);\n }\n\n }\n }\n\n private List oreMaterial = Arrays.asList(\n // Ores\n Material.COAL_ORE,\n Material.IRON_ORE,\n Material.LAPIS_ORE,\n Material.REDSTONE_ORE,\n Material.GOLD_ORE,\n Material.DIAMOND_ORE,\n Material.EMERALD_ORE\n\n );\n\n\n\n private boolean isOreType(Material block) {\n for (Material material : oreMaterial)\n if (block == material)\n return (true);\n return (false);\n }\n}\n\nAny help would be appreciate. Thanks\n\nA: Block.setType by default updates neighboring blocks, which, if happening near a yet unpopulated chunk, causes it to populate as well, and so on. This needs to be turned off with the second boolean parameter: setType(Material.STONE, false).\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/61844520", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Connect to a remote server mongoDB in Docker via ssh in nodeJS using tunnel-ssh, AuthenticationFailed I am trying to connect to a remote server MongoDB in Docker through ssh in Nodejs as below :\nsshConfig = {\n username: 'username',\n password: 'password',\n host: 'host',\n port: 22,\n dstHost: '172.17.0.3',\n dstPort: 27017,\n localPort: 5000\n};\n\nconst uri = 'mongodb://admin:password@localhost:27017/admin';\n\ntunnel(sshConfig, async error => {\n if (error) {\n throw new Error(`SSH connection error: ${error}`);\n }\n\n const client = new MongoClient(uri);\n\n async function run() {\n try {\n // Connect the client to the server\n await client.connect();\n // Establish and verify connection\n await client.db('admin').command({ ping: 1 });\n console.log('Connected successfully to server');\n } finally {\n // Ensures that the client will close when you finish/error\n await client.close();\n }\n }\n await run().catch(console.dir);\n });\n\nBut I am getting error as below :\nMongoServerError: Authentication failed.\nat MessageStream.messageHandler (/node_modules/mongodb/src/cmap/connection.ts:740:20)\nat MessageStream.emit (node:events:390:28)\nat MessageStream.emit (node:domain:475:12)\nat processIncomingData (/node_modules/mongodb/src/cmap/message_stream.ts:167:12)\nat MessageStream._write (/node_modules/mongodb/src/cmap/message_stream.ts:64:5)\nat writeOrBuffer (node:internal/streams/writable:389:12)\nat _write (node:internal/streams/writable:330:10)\nat MessageStream.Writable.write (node:internal/streams/writable:334:10)\nat Socket.ondata (node:internal/streams/readable:754:22)\nat Socket.emit (node:events:390:28) {\nok: 0,\ncode: 18,\ncodeName: 'AuthenticationFailed'\n},\nand I open http://localhost:5000/ by browser, it shows that:\nIt looks like you are trying to access MongoDB over HTTP on the native driver port.\nI can connect the database via:\n\n\n*\n\n*Use MongoDB compass to connect the database via ssh\n\n*Use mongo 'mongodb://admin:password@remote-host:27017/admin' in local machine terminal\n\n*Use MongoClient(mongodb://admin:password@remote-host:27017/admin) in Nodejs without ssh-tunnel\n\n*Use mongo 'mongodb://admin:password@localhost:27017/admin' in both remote host and remote host docker contaniner\n\n\nI am sure the password is correct.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/69387103", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How can I detect Android library modules that could be plain Kotlin modules? I work on a big project with hundreds of modules. Some of them are declared as Android library modules, but they don't have any Android-specific dependencies, so they could be converted to plain Kotlin modules. Is there a way to detect this fact? How can I detect automatically that an Android library module could be a plain Kotlin module?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/73960089", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Using StreamSocketListener in the background with SocketActivityTrigger In order to make a UWP App act like an HTTP server, restup does the job. But the problem is that it does not provide an HTTP server that works even after the app is closed.\nIn order to achieve this, a background task with SocketActivityTrigger has to be created and the socket ownership of StreamSocketListener has to be transferred to the socket broker so that the background task is triggered when a request comes (as explained here). And here is an example for an app that connects to a socket and keeps receiving messages even after the app is closed.\nI tried to adapt this to make restup work in the background as well, but in vain!\nCould someone help on this please?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/59716347", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to re-calculate a style on sibling elements? Not sure if i'm even asking this correctly. So allow me to explain further.\nHTML\n
    \n
    \n
    \n
    \n
    \n
    \n\nLESS\n@qBlockBG: #ccc;\n.qBlock { color: white; }\n#q1: { background-color: @qBlockBG; }\n#q{n}: { background-color: darken(#q{n-1}, 10%); } <--- doesn't work, but that's the idea\n\nWhat I want to do is have the base style for #q1 be re-calculated for each sibling such that the color is darker for each additional sibling. So #q2 is 10% darker than #q1 and #q3 is 10% darker than #q2, and so on.\n\nA: You can mock loops in LESS using a recursive mixin with a guard expression. Here's an example applied to your case:\n#q1 {\n background-color: #ccc;\n}\n\n/* recursive mixin with guard expression - condition */\n.darker-qs(@color, @index) when (@index < 10) { \n\n @darker-color: darken(@color, 10%);\n\n /* the statement */\n #q@{index} {\n background-color: @darker-color;\n }\n /* end of the statement */\n\n /* the next iteration's call - final expression */\n .darker-qs(@darker-color, @index + 1); \n}\n\n/* the primary call - initialization */\n.darker-qs(#ccc, 2); \n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/66440570", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: QDesktopServices::openUrl() doesn't open page in chrome on windows. Workaround? QDesktopServices::openUrl(QUrl(\"http://google.com\"));\n\nworks if default browser ie9, ie8, firefox or opera\nif default browser is chrome nothing happens\nQtCreator debugger log i can see lines like \nModLoad: 00000000`05250000 00000000`05308000 iexplore.exe\n\nor\nModLoad: 00000000`04db0000 00000000`04ef8000 chrome.exe\n\nso it actually works, but ie, ff etc. opens new tab with specified url and chrome doesn't\ni suppose it's bug\nsome time ago it worked perfectly\ncould it be problem with my system (ENV vars etc.)? \nplease help with workaround\ni prefer crossplatform, but proper work on windows has max priority\npossible solution (winapi SHELLEXECUTE) - really hate that way with ugly #ifdef, but can be an option\nPS: sorry for poor english.\n\nA: I dont think it's really a problem of your application.. I think it's more about how Chrome is treated such invocations. Being on your place I would go for winpai SHELLEXECUTE solution. And #ifdef is not really ugly comparing with benefits that you move default browser invocation to operation system rather then on Qt library.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/16103589", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: Creating a folder in Kotlin I am new to Kotlin and have read lots of tutorials, tried bunches of code but still can't understand how \nto create a folder in internal storage. \nI need to create a folder in which I wil put a json resource file. \nManifest file contains and \n \nMy code sample is: \nclass MainActivity() : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n\n val folder = File(\n Environment.getDataDirectory().toString() + separator.toString() + \"MetroPol\"\n )\n if (folder.exists()) {\n d(\"folder\", \"exists\")\n } else {\n d(\"folder\", \"not exists\")\n folder.mkdirs()\n }\n }\n\nI test it using my phone connected to a pc and recognised by Android Studio. When this app launches I go to a browser and don't see any new folder.\nWhat should be done here? \n\nA: To create a folder inside your Internal Storage, try out this code snippet\nval folder = filesDir\nval f = File(folder, \"folder_name\")\nf.mkdir()\n\nFinally to check if the folder is created open Device Explorer in Android Studio, then follow the path\ndata->data->your app package name -> files-> here should be your folder that you created programmatically. Hope this helps\n\nA: \nI am new to Kotlin and have read lots of tutorials, tried bunches of code but still can't understand how to create a folder in internal storage. \n\nIt seems as though you really want to be creating a directory in external storage.\nSince that is no longer being supported on Android 10 (by default) and Android R+ (for all apps), I recommend that you let the user create the directory themselves, and you get access to it via ACTION_OPEN_DOCUMENT_TREE and the Storage Access Framework.\n\nWhen this app launches I go to a browser and don't see any new folder.\n\nThe root of external storage is Environment.getExternalStorageDirectory().\n\nA: val appDirctory =File(Environment.getExternalStorageDirectory().path + \"/test\")\nappDirctory.mkdirs()\n\n\nA: Can you try this ?\nclass MainActivity() : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n var filename = \"test.txt\"\n val folder = File(\"/sdcard/MetroPol/\")\n folder.mkdirs()\n val outputFile = File(folder, filename)\n try {\n val fos = FileOutputStream(outputFile)\n } catch (e: FileNotFoundException) {\n e.printStackTrace()\n }\n }\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/60004199", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "9"}} {"text": "Q: How to display single quotes inside double quotes in string in python I know this is very basic question, but not able to frame it out.\nI need to execute a customized python command based command with in a script.\nex:\nbelow is the actual commands.\ncommand-dist --host='server1' -- cmd -- 'command1;command2'\n\nI need to use this command in my python script\nform my script , this command needs be to executed on remote server\nI need this command format to use in my script\ncmd=\"ssh -q %s \"command-dist --host=%s -- cmd -- 'cmd1;cmd2'\"\" %(host1,host2)\n\nbut the above is failing due to quotes, tried number of ways still no luck.\nWhen I tried this way\ncmd=\"ssh -q %s \\\"command-dist --host=%s -- cmd -- 'cmd1;cmd2'\\\"\" %(host1,host2)\n\nI don't under why back slashes are appearing before and after cmd1;cmd2?\nThis is what I am not getting.\ncmd\n'ssh -q %s \"command-dist --host=%s -- cmd -- /'cmd1;cmd2'/\"\"' %(host1,host2)\n\nPlease help how do I get the above value\n\nA: This\ncmd=\"ssh -q %s \"command-dist --host=%s -- cmd -- 'cmd1;cmd2'\"\" %(host1,host2)\n\nis understood by Python as\ncmd = command-dist --host=%s -- cmd -- 'cmd1;cmd2'\n\nbecause you use the same quotes inside and outside.\nTry instead to escape the internal quotes with a backslash:\ncmd=\"ssh -q %s \\\"command-dist --host=%s -- cmd -- 'cmd1;cmd2'\\\"\" %(host1,host2)\n\nAside from that, you should use the subprocess module and supply your command as a list to subprocess.Popen.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/40951545", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How can a Bacon.interval be stopped? I have an event that is fired periodically:\nlet periodicEvent = Bacon.interval(1000, {});\nperiodicEvent.onValue(() => {\n doStuff();\n});\n\nWhat I would like is to pause and restart periodicEvent when I need it. How can periodicEvent be paused and restarted? Or is there a better way to do it with baconjs?\n\nA: *\n\n*An impure way to do it is to add a filter that checks for a variable before you subscribe, and then change the variable when you don't want the subscribed action to occur:\nvar isOn = true;\nperiodicEvent.filter(() => isOn).onValue(() => {\n doStuff();\n});\n\n\n*A \"pure-r\" way to do it would be turn an input into a property of true/false and filter you stream based on the value of that property:\n// make an eventstream of a dom element and map the value to true or false\nvar switch = $('input')\n .asEventStream('change')\n .map(function(evt) {\n return evt.target.value === 'on';\n })\n .toProperty(true);\n\n\nvar periodEvent = Bacon.interval(1000, {});\n\n// filter based on the property b to stop/execute the subscribed function\nperiodEvent.filter(switch).onValue(function(val) {\n console.log('running ' + val);\n});\n\nHere is a jsbin of the above code\nThere might be an even better/fancier way of doing it using Bacon.when, but I'm not at that level yet. :)\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/43611681", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Validation DropDownList value from ViewModel in ASP.Net MVC I tried to search posts, without any result either, maybe I didn't use the right words.\nI need a solution in MVC for validate the DropDownList value, populated from database using Model class and the Html.DropDownListFor Helper method and MySql.\nIn the view I have added new DDL and this is populated correctly from database\n @Html.DropDownListFor(m => m.Fruits, Model.Fruits, \"[ === Please select === ]\", new { @Class = \"textarea\" })\n @Html.ValidationMessageFor(m => m.Fruits, \"\", new { @class = \"text-danger\" })\n\n
    \n
    \n \n
    \n
    \n\nBut when on click the\n\n\nThe form is validate and does not stop sending when the DDL has not selected any value.\nWithout DDL the validation working correctly.\nPlease, help me.\nMy code below\nModel\nnamespace InsGE.Models\n{\n public class PersonModel\n {\n [Required]\n [Display(Name = \"Fruits\")] \n public List Fruits { get; set; }\n\n public string Namex { get; set; }\n \n public string Codex { get; set; }\n\n [Required]\n [Display(Name = \"CL\")] \n public string CL { get; set; }\n\n [Required]\n [Display(Name = \"Ticket\")]\n public string Ticket { get; set; }\n }\n}\n\nController\nnamespace InGE.Controllers\n{\n public class HomeController : Controller\n {\n private static List PopulateFruits()\n {\n string sql;\n\n List items = new List();\n\n string constr = ConfigurationManager.ConnectionStrings[\"cn\"].ConnectionString;\n\n using (MySqlConnection con = new MySqlConnection(constr))\n {\n sql = @String.Format(\"SELECT * FROM `dotable`; \");\n\n using (MySqlCommand cmd = new MySqlCommand(sql))\n {\n cmd.Connection = con;\n con.Open();\n\n using (MySqlDataReader sdr = cmd.ExecuteReader())\n {\n while (sdr.Read())\n {\n items.Add(new SelectListItem\n {\n Text = sdr[\"sName\"].ToString(),\n Value = sdr[\"sCode\"].ToString()\n });\n }\n }\n con.Close();\n }\n }\n\n return items;\n }\n\n [HttpPost]\n public ActionResult Index(PersonModel person)\n {\n string sCl = person.CL;\n string sTicket = person.Ticket; \n string sName = person.Namex;\n string sCode = person.Codex;\n\n return View();\n }\n\n [HttpGet]\n public ActionResult Index()\n {\n PersonModel fruit = new PersonModel();\n fruit.Fruits = PopulateFruits();\n return View(fruit);\n }\n\n public ActionResult About()\n {\n ViewBag.Message = \"Your application description page.\"; \n return View();\n }\n\n public ActionResult Contact()\n {\n ViewBag.Message = \"Your contact page.\"; \n return View();\n }\n\nupdate\nController\n public class HomeController : Controller\n {\n public class Fruit\n {\n public string Code { get; }\n public string Name { get; }\n\n public Fruit(string code, string name)\n {\n Code = code;\n Name = name;\n }\n }\n\n public class FruitsRepository\n {\n private static List GetAll()\n {\n string sql;\n\n var fruits = new List();\n\n string constr = ConfigurationManager.ConnectionStrings[\"cn\"].ConnectionString;\n\n using (MySqlConnection con = new MySqlConnection(constr))\n {\n sql = @String.Format(\"SELECT * FROM `dotable`; \");\n\n using (MySqlCommand cmd = new MySqlCommand(sql))\n {\n cmd.Connection = con;\n con.Open();\n\n using (MySqlDataReader sdr = cmd.ExecuteReader())\n {\n while (sdr.Read())\n {\n var fruit = new Fruit(sdr[\"sCode\"].ToString(), sdr[\"sName\"].ToString());\n fruits.Add(fruit);\n }\n }\n con.Close();\n }\n }\n\n return fruits;\n }\n }\n\n [HttpGet]\n public ActionResult Index() <<<<<< Error \u201cnot all code paths return a value\u201d\n {\n var personModel = new PersonModel();\n var fruitsRepo = new FruitsRepository();\n var fruits = fruitsRepo.GetAll(); <<<<<< Error \u201cis inaccessible due to its protection level\u201d\n var fruitsSelecteListItems = fruits.Select(fruit => new SelectListItem\n {\n Text = fruit.Name;\n Value = fruit.Code; <<<<<< Error \u201cThe name 'Value' does not exist in the current context\u201d\n });\n return View(personModel); <<<<< Fruits { get; set; }\n\n public string Namex { get; set; }\n \n public string Codex { get; set; }\n\n [Required]\n [Display(Name = \"CL\")] \n public string CL { get; set; }\n\n [Required]\n [Display(Name = \"Ticket\")]\n public string Ticket { get; set; }\n}\n\n\nComplete View\n@using (Html.BeginForm(\"Index\", \"Home\", FormMethod.Post))\n{\n @Html.AntiForgeryToken()\n
    \n @Html.ValidationSummary(true, \"\", new { @class = \"text-danger\" })\n \n \n \n \n \n \n \n \n \n \n \n \n
    CL\n @Html.TextBoxFor(m => m.CL, new { @Class = \"textarea\", placeholder = \"CL\" })\n @Html.ValidationMessageFor(m => m.CL, \"\", new { @class = \"text-danger\" })\n
    Ticket\n @Html.TextBoxFor(m => m.Ticket, new { @Class = \"textarea\", placeholder = \"Ticket\" })\n @Html.ValidationMessageFor(m => m.Ticket, \"\", new { @class = \"text-danger\" })\n Fruits\n @Html.DropDownListFor(m => m.SelectedFruitCode, Model.Fruits, \"[ === Please select === ]\", new { @Class = \"textarea\" })\n @Html.ValidationMessageFor(m => m.SelectedFruitCode, \"\", new { @class = \"text-danger\" })\n
    \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n}\n
    \n @Html.ActionLink(\"Back to List\", \"Index\")\n
    \n\n@section Scripts {\n\n @Scripts.Render(\"~/bundles/jqueryui\")\n @Styles.Render(\"~/Content/cssjqryUi\")\n\n \n}\n\nComplete Controller\npublic class HomeController : Controller\n{\n\n [HttpPost]\n public ActionResult Index(PersonModel person)\n {\n if (ModelState.IsValid)\n {\n string cl = person.CL;\n string ticket = person.Ticket;\n }\n\n return View();\n }\n\n public class Fruit\n {\n public string Code { get; }\n public string Name { get; }\n\n public Fruit(string code, string name)\n {\n Code = code;\n Name = name;\n }\n }\n\n public class FruitsRepository\n {\n public List GetAll()\n {\n string sql;\n\n var fruits = new List();\n\n string constr = ConfigurationManager.ConnectionStrings[\"cnx\"].ConnectionString;\n\n using (MySqlConnection con = new MySqlConnection(constr))\n {\n sql = @String.Format(\"SELECT * FROM `dotable`; \")\n\n using (MySqlCommand cmd = new MySqlCommand(sql))\n {\n cmd.Connection = con;\n con.Open();\n\n using (MySqlDataReader sdr = cmd.ExecuteReader())\n {\n while (sdr.Read())\n {\n var fruit = new Fruit(sdr[\"sCode\"].ToString(), sdr[\"sName\"].ToString());\n fruits.Add(fruit);\n }\n }\n con.Close();\n }\n }\n\n return fruits;\n }\n }\n\n [HttpGet]\n public ActionResult Index()\n {\n var personModel = new PersonModel();\n var fruitsRepo = new FruitsRepository();\n var fruits = fruitsRepo.GetAll();\n var fruitsSelecteListItems = fruits.Select(fruit => new SelectListItem\n {\n Text = fruit.Name,\n Value = fruit.Code\n }).ToList();\n personModel.Fruits = fruitsSelecteListItems;\n return View(personModel);\n }\n\n public ActionResult About()\n {\n ViewBag.Message = \"Your application description page.\";\n return View();\n }\n\n public ActionResult Contact()\n {\n ViewBag.Message = \"Your contact page.\";\n return View();\n }\n}\n\n\nA: You need some changes. Let's start with database related code. Instead of mixing database related things (MySqlConnection, MySqlCommand etc.) with presentation layer things (SelectListItem, List etc.) and doing that also inside a Controller, you should\n\n*\n\n*Create a separate class for accessing the database and fetching the data.\n\n*The method that would be called should return a List of some kind of domain/entity object that would represent the Fruit.\n\nSo, let's define initially our class, Fruit:\npublic class Fruit\n{\n public string Code { get; }\n public string Name { get; }\n\n public Fruit(string code, string name)\n {\n Code = code; \n Name = name;\n }\n}\n\nThen let's create a class that would be responsible for accessing the database and fetch the fruits:\npublic class FruitsRepository\n{\n public List GetAll()\n {\n string sql;\n\n var fruits = new List();\n\n string constr = ConfigurationManager.ConnectionStrings[\"cn\"].ConnectionString;\n\n using (MySqlConnection con = new MySqlConnection(constr))\n {\n sql = @String.Format(\"SELECT * FROM `dotable`; \");\n\n using (MySqlCommand cmd = new MySqlCommand(sql))\n {\n cmd.Connection = con;\n con.Open();\n\n using (MySqlDataReader sdr = cmd.ExecuteReader())\n {\n while (sdr.Read())\n {\n var fruit = new Fruit(sdr[\"sCode\"].ToString(), sdr[\"sName\"].ToString());\n fruits.Add(fruit);\n }\n }\n con.Close();\n }\n }\n\n return fruits;\n }\n}\n\nNormally, this class should implement an interface, in order we decouple the controller from the actual class that performs the database operations, but let's not discuss this at this point.\nThen at your controller:\n\n*\n\n*We should use the above class to fetch the fruits.\n\n*We should create a list of SelectListItem objects and you would provide that list to the model.\n\n*We should change the model, in a way that it would hold an info about the selected fruit (check below).\n\n*We should change the view.\n\nChanges in the model\npublic class PersonModel\n{\n [Required]\n [Display(Name = \"Fruits\")] \n public string SelectedFruitCode { get; set; }\n\n public List Fruits { get; set; }\n\n public string Namex { get; set; }\n \n public string Codex { get; set; }\n\n [Required]\n [Display(Name = \"CL\")] \n public string CL { get; set; }\n\n [Required]\n [Display(Name = \"Ticket\")]\n public string Ticket { get; set; }\n}\n\nChanges in the View\n@Html.DropDownListFor(model => model.SelectedFruitCode, Model.Fruits, \"[ === Please select === ]\", new { @Class = \"textarea\" })\n@Html.ValidationMessageFor(model => model.SelectedFruitCode, \"\", new { @class = \"text-danger\" })\n\nChanges in the Controller\n [HttpGet]\n public ActionResult Index()\n {\n var personModel = new PersonModel();\n \n // THIS IS **BAD CODE**...Normaly, you should create an interface that describes\n // what is expected from the class that communicates with the DB for operations\n // related with the Fruit and then inject the dependency in the HomeController \n // Constructor. \n \n var fruitsRepo = new FruitsRepository();\n var fruits = fruitsRepo.GetAll();\n var fruitsSelecteListItems = fruits.Select(fruit => new SelectListItem\n {\n Text = fruit.Name,\n Value = fruit.Code\n }).ToList();\n personModel.Fruits = fruitsSelecteListItems; \n return View(personModel);\n }\n\nPlease check thoroughly the comments in the code above ^^. As a starting point for that mentioned in the comments, you could see this.\nUPDATE\nWe have also to change the post action:\n[HttpPost]\npublic ActionResult Index(PersonModel person)\n{\n // Removed the Model.IsValid check since it's redundant in your case\n // Usually we use it and when it is valid we perform a task, like update \n // the corresponding object in the DB or doing something else. Otherwise,\n // we return a view with errors to the client. \n var fruitsRepo = new FruitsRepository();\n var fruits = fruitsRepo.GetAll();\n var fruitsSelecteListItems = fruits.Select(fruit => new SelectListItem\n {\n Text = fruit.Name,\n Value = fruit.Code,\n Selected = String.Equals(fruit.Code, \n person.SelectedFruitCode, \n StringComparison.InvariantCultureIgnoreCase)\n }).ToList();\n\n person.Fruits = fruitsSelecteListItems; \n\n return View(person);\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/64941538", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Clustering lists having maximum overlap with size restriction I have the following group of numbers:\ngroup1: 12 56 57 58 59 60 61 62 63 64 75 89 91 100 105 107 108 Group Size: 40\ngroup2: 56 57 60 71 72 73 74 91 92 93 94 100 105 107 108 110 111 Group Size: 30\ngroup3: 57 58 91 107 108 110 112 114 117 118 120 127 129 139 184 Group Size: 15\ngroup4: 1 2 4 6 7 8 9 10 17 18 20 41 42 43 45 47 Group Size: 40\ngroup5: 57 58 91 201 205 207 210 212 214 216 217 218 219 220 221 225 Group Size: 30\n.\ngroupN: 50 51 52 53 54 210 214 216 219 225 700 701 702 705 706 708 Group Size: 40\n\nNow I want to cluster together groups having maximum overlap such that after clustering, maximum size within a cluster does not exceed 90. For example here, the clusters are: (group1,group2,group3),(group5,groupN) and group4. The overlapping elements in the 3 groups are shown below:\nCluster1: (group1,group2,group3): 57 91 107 108 Cluster Size: (Group1_size+group2_size+group3_size =85 <90) \nCluster2: group4: 1 2 4 6 7 8 9 10 17 18 20 41 42 43 45 47 Cluster Size: (group4_size < 40)\nCluster3: (group5,groupN): 201 214 216 219 225 Cluster Size: (group5_size + groupN_size 70 <90)\n\nIf I include group5 in cluster1 then its size will be 85+30=115 and I want to return a size<90, therefore I can not include group4 in cluster1.\nThe elements in the respective clusters after removing the duplicate overlapping elements are:\nCluster1: (group1, group2, group3): 12 56 57 58 59 60 61 62 63 64 71 72 73 74 75 89 91 92 93 94 100 105 107 108 110 111 112 114 117 118 120 127 129 139 184\nCluster2: group4: 1 2 4 6 7 8 9 10 17 18 20 41 42 43 45 47\nCluster3: (group5,groupN): 50 51 52 53 54 57 58 91 201 205 207 210 212 214 216 217 218 219 220 221 225 700 701 702 705 706 708\n\nIs there some existing algorithm or technique which may help me achieve this clustering with size constraint. \nI tried to form clusters by finding the common elements between any two groups and including in the group if cluster size after inclusion is <90. But is there any existing algorithm in any of the programming language libraries like C++,python,java which may help me achieve this efficiently. If not, then is there any existing algorithm which achieves the same.\nIf possible, it will be great if the algorithm is optimal also.\n\nA: There is no easy optimal solution. One approximation is as follows:\n\n\n*\n\n*Pick the group with the largest size. Let its size be x\n\n*Pick the largest group such that its size is less than 90-x\n\n*Keep repeating step 2 until you cannot find such a group\n\n*Remove the selected groups and repeat the process starting from Step 1\n\n\nEg. You would pick group1 (or group4 or groupN) first is step 1. In step 2 you would pick group4. Now the size is 80 and there are no groups smaller than 90-80=10. So stop and remove these two groups. In the next iteration, you will select groupN, followed by group2, and at last group3. In the last iteration you have only one group, that is group5.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/28560963", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Float number and subquery I have query:\nSELECT \n DISTINCT `g`.`id` , \n `g`.`steam_id` , \n `g`.`type` , \n `g`.`title` ,\n `g`.`price` , \n `g`.`metascore` , \n `g`.`image` ,\n (\n SELECT `id`\n FROM `game_promotions`\n WHERE `game_promotions`.`game_id` = `g`.`id`\n ) AS `promotion_id`,\n (\n\n SELECT `price`\n FROM `game_promotions`\n WHERE `game_promotions`.`game_id` = `g`.`id`\n ) AS `promotion_price`, \n (\n SELECT COUNT( `id` )\n FROM `bot_games`\n WHERE `game_id` = `g`.`id`\n AND `buyer` IS NULL\n ) AS `copies`\nFROM \n `games` AS `g` , \n `game_genres` AS `gg`\nWHERE\n `gg`.`game_id` = `g`.`id`\n AND `g`.`title` LIKE \"Counter%\"\nGROUP BY `promotion_id`\nLIMIT 0 , 30\n\nAnd problem is bad returned promotion_price. In game_promotions table, price is \"24.99\", but in query result promotion_price is \"14.9899997711182\". The returned promotion ID is good. Only float price is invalid. Why this number has changed?\n\nA: Ok, I'm not sure if this is exactly what you wanted, but I'm posting my modified query below. First of all, I got rid of the implicit join and changed it with an explicit INNER JOIN. I also moved your subquerys with LEFT JOINs for better performance. And I deleted the DISTINCT and the GROUP BY because I couldn't really understand why you needed them.\nSELECT \n `g`.`id` , \n `g`.`steam_id` , \n `g`.`type` , \n `g`.`title` ,\n `g`.`price` , \n `g`.`metascore` , \n `g`.`image`,\n `gp`.`id` AS `promotion_id`,\n `gp`.`price` AS `promotion_price`, \n `bg`.`copies`\nFROM \n `games` AS `g`\nINNER JOIN `game_genres` AS `gg`\n ON `gg`.`game_id` = `g`.`id`\nLEFT JOIN `game_promotions` as `gp`\n ON `g`.`id` = `gp`.`game_id`\nLEFT JOIN ( SELECT `game_id`, COUNT(`id`) `copies`\n FROM `bot_games`\n WHERE `buyer` IS NULL\n GROUP BY `game_id`) `bg`\n ON `bg`.`game_id` = `g`.`id`\nWHERE `g`.`title` LIKE \"Counter%\"\nLIMIT 0 , 30\n\n\nA: Do you mean the result is 24.9899997711182? That's within the single precision float margin of error.\nYou get the expected result, you just have to round it to two decimals for display.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/14781353", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Android videoview playable logo Hi my android coding have a videoview and I want to put playable logo overlay on it when it's stop but when it's playing the logo disappear, how can I do it?\nhere is my coding on videoview\nfinal VideoView videoView = (VideoView)rootView.findViewById(R.id.videoview);\n videoView.setVideoURI(Uri.parse(\"android.resource://\" + getActivity().getPackageName() + \"/\" + R.raw.complete));\n videoView.setMediaController(new MediaController(getActivity().getApplicationContext()));\n videoView.requestFocus();\n\n videoView.setOnTouchListener(new View.OnTouchListener() {\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if (event.getAction() == MotionEvent.ACTION_UP) {\n if (videoView.isPlaying()) {\n videoView.pause();\n } else {\n videoView.start();\n }\n }\n return true;\n }\n }); \n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/33819957", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: new column is the sum of two consecutive rows please your gentile help, anyone can help me with pandas-python\nI need a new column, this new column is the sum of two consecutive rows, (figure)\nenter image description here\n\nA: You could look at the table.assign( = ) function to build out your dataframe.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/69730723", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: ProcessPoolExecuter and global variables I have a question regarding global variables and using different processes.\nFor my main python script I have a main function which calls Initialize to initialize a global variable in Metrics.py. I've also created a getter function to retrieve this variable.\nMain.py:\nfrom Metrics import *\nimport pprint\n\ndef doMultiProcess(Files):\n result = {}\n\n with concurrent.futures.ProcessPoolExecutor() as executor:\n futures = [executor.submit(ProcessFile, file) for file in Files]\n\n for f in concurrent.futures.as_completed(futures):\n # future.result needs to be evaluated to catch any exception\n try:\n filename, distribution = f.result()\n\n result[filename] = {}\n result[filename] = distribution\n except Exception as e:\n pprint.pprint(e) \n \n return result \n\nFiles = [\"A.txt\", \"B.txt\", \"C.txt\"]\n\ndef main:\n Initialize()\n\n results = doMultiProcess(Files)\n \nif __name__ == '__name__':\n main()\n\n\nMetrics.py\nKeywords = ['pragma', 'contract']\n\ndef Initialize():\n global Keywords\n Keywords= ['pragma', 'contract', 'function', 'is']\n\ndef GetList():\n global Keywords # I believe this is not necessary.\n return Keywords\n\ndef ProcessFile(filename):\n # Read data and extract all the words from the file, then determine the frequency \n # distribution of the words, using nltk.freqDist, which is stored in: freqDistTokens\n distribution = {keyword:freqDistTokens[keyword] for keyword in Keywords}\n\n return (filename, distribution)\n\nI hope I've simplified the example enough and not left out important information. Now, what I don't understand is why the processes keep working with the initial value of Keywords which contains 'pragma' and 'contract'. I call the initialize before actually running the processes and therefore should set the global variable to something different then the initial value, right? What am I missing that is happening here.\nI've worked around this by actually supplying the Keywords list to the process by using the GetList() function but I would like to understand as to why this is happening.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/67765918", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Clickable ImageView over List view i have a app that has a listview. I want to place a imageview over part of the listview. When i set the onclick Listener for the imageview nothing happens. How do i make it so that the imageview is clickable and not the area of the listview that overlaps with the imageview.\nthe imageview \"id/imagemenu\" should be clickable\nxml:\n \n\n\n \n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\nA: You forgot to add selector, check this out.\n\n\nThe corresponding selector file looks like this:\n\n\n\n\n\n\nAnd in my onCreate I call:\nfinal ImageButton ib = (ImageButton) value.findViewById(R.id.imageButton);\n\nOnClickListener ocl =new OnClickListener() {\n @Override\n public void onClick(View button) {\n if (button.isSelected()){\n button.setSelected(false);\n } else {\n ib.setSelected(false);\n //put all the other buttons you might want to disable here...\n button.setSelected(true);\n }\n }\n};\n\nib.setOnClickListener(ocl);\n//add ocl to all the other buttons\n\nHope this helps.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/21655962", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Array stops working when i update the value of a key to 0 i have a code where sales are made on a sales modal(on an invoice page) with database entry.When a product for sale is selected, the pieces available for that product is entered into another input and on submission, the product id and pieces sold of the product is added to a session array.The purpose of this is because when sales are made it's added to a sales table on the invoice page, just in case the user decides to add too or subtract from the number of pieces of a particular product already on the sales table,let the sales modal (pieces available)input be up to date on the values to display instead of getting it from the database again.\nhere is a sample of the code i use in making a sales db entry and setting session array values:\n $productPieces = get_productPiecesForSale();//fetches product pieces from db\n $product_id = $_POST['product_id'];//product id\n $pieces = $_POST['pieces_sold'];// pieces sold\n $invoice_id = $_SESSION['invoice_id'];\n\n $query = \"SELECT * FROM sales WHERE product_id = '$id' AND invoice_id = '$invoice_id' LIMIT 1\";// check if product is in the sales table already\n $sales_set = mysqli_query($connect,$query);\n $sales = mysqli_fetch_array($sales_set);\n\n if(isset($sales['sales_key'])){\n\n $pieces_update = $pieces + $sales['pieces']; // adds db pieces to pieces sold\n\n if($pieces_update > $productPieces){\n\n if(in_array($product_id, $_SESSION['pieces_available'])){\n $key = array_search($product_id , $_SESSION['pieces_available']);\n $_SESSION['pieces_available'][$key+1] = '0';\n } \n\n//so that pieces can't be sold above what is available\n $query = \"UPDATE sales SET pieces = '{$productPieces}' WHERE product_id = '{$product_id }' LIMIT 1\";\n $sales_set = mysqli_query($connect,$query);\n }else{\n\n if(in_array($product_id , $_SESSION['pieces_available'])){\n $key = array_search($product_id , $_SESSION['pieces_available']);\n $_SESSION['pieces_available'][$key+1] = $productPieces - $pieces_update;\n }\n\n $query = \"UPDATE sales SET pieces = '{$pieces_update}'' WHERE product_id = '{$product_id }' LIMIT 1\";\n $sales_set = mysqli_query($connect,$query);\n }//if($pieces_update > $productPieces){\n\n }else{\n\n $_SESSION['pieces_available'][] = $_POST['product_id'];\n $_SESSION['pieces_available'][] = $_POST['pieces_remaining'];\n $query = \"INSERT INTO sales() VALUE()\";\n $sales_set = mysqli_query($connect,$query);\n }\n\nand here's the php code for my ajax i use to populate my sales form input\nif(isset($_GET['p'])){\n $p = $_GET['p'];\n\n if(isset($_SESSION['pieces_available'])){//$_SESSION['pieces_available'] is set\n\n if(in_array($p, $_SESSION['pieces_available']) !== false){//product_id is in array\n $key = array_search($p, $_SESSION['pieces_available']);\n $pieces = $_SESSION['pieces_available'][$key+1];\n echo $pieces;\n }else{//product_id is not in array\n $query = \"SELECT pieces FROM products WHERE product_id = '{$p}' LIMIT 1\";\n $result_set = mysqli_query($connect, $query);\n $result = mysqli_fetch_array($result_set);\n echo $result['pieces'];\n } \n\n }else{//$_SESSION['pieces_available'] isn't set\n $query = \"SELECT pieces FROM products WHERE product_id = '{$p}' LIMIT 1\";\n $result_set = mysqli_query($connect, $query);\n $result = mysqli_fetch_array($result_set);\n echo $result['pieces'];\n }\n\n }\n\nEverything works how i want it to work, until i update the pieces of a product already existing on the sale table that the pieces remaining now becomes 0, then my sales form stops displaying the pieces available for a selected product. If the pieces remaining becomes any other number this doesn't happen.\nwell just in case let me add my ajax and html code:\n\n\n\n\n\n\n\n\n\n\n\n\nSales table screen shots: saleTable\nSales modal screen shots: sale Modal\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/40070608", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Push non-angular object to AngularJs controller scope I have a Angular controller that have a FormData scope, e.g: $scope.FormData. Data is collected via model connected to a simple form. Also, I have an external non-angular js code on the page. I need to push one of its variables to $scope.FormData.name. How can I do that? Already tried acces it as a global variable via $window, but no luck. Here is the example code: \nAngular code: \napp.controller('mainController', function ($scope, $http) {\n\n $scope.formData = {};\n $scope.formData.day = \"1\";\n $scope.formData.month = \"January\"; ...\n\nAnd non-angular code:\nvar data = [{data1: value1}, {data2:value2}];\n\nBinding this data to a model in a form is not a good option, because this is an object, so, I will get a string in a formData, like [Object, Object].\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/26120206", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Connecting to Cassandra on startup, and monitoring session health Two related questions \n1) Currently, the session to C* is established in a lazy fashion - aka, only on the first any table is accessed.\nInstead, we would like to establish a session as soon as the application is started (in case there is a connectivity problem, etc. ). What would be the best way to do that? Should I just get a session object in my startup code? \nconnector.provider.session\n\n2) How would I then monitor the health of the connection? I could call \nconnector.provider.session.isClosed()\n\nbut I'm not sure it will do the job. \n\nA: I wouldn't manually rely on that mechanism per say as you may want to get more metrics out of the cluster, for which purpose you have native JMX support, so through the JMX protocol you can look at metrics in more detail.\nNow obviously you have OpsCenter which natively leverages this feature, but alternatively you can use a combination of a JMX listener with something like Graphana(just a thought) or whatever supports native compatibility.\nIn terms of low level methods, yes, you are on the money:\nconnector.provider.session.isClosed()\nBut you also have heartbeats that you can log and look at and so on. There's more detail here.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/41686161", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: R: order data frame according to one column I have a data like this \n> bbT11\n range X0 X1 total BR GDis BDis WOE IV Index\n1 (1,23] 5718 194 5912 0.03281461 12.291488 8.009909 0.42822753 1.83348973 1.534535\n2 (23,26] 5249 330 5579 0.05915039 11.283319 13.625103 -0.18858848 0.44163352 1.207544\n3 (26,28] 3105 209 3314 0.06306578 6.674549 8.629232 -0.25685394 0.50206815 1.292856\n4 (28,33] 6277 416 6693 0.06215449 13.493121 17.175888 -0.24132650 0.88874916 1.272937\n5 (33,37] 4443 239 4682 0.05104656 9.550731 9.867878 -0.03266713 0.01036028 1.033207\n6 (37,41] 4277 237 4514 0.05250332 9.193895 9.785301 -0.06234172 0.03686928 1.064326\n7 (41,46] 4904 265 5169 0.05126717 10.541702 10.941371 -0.03721203 0.01487247 1.037913\n8 (46,51] 4582 230 4812 0.04779717 9.849527 9.496284 0.03652287 0.01290145 1.037198\n9 (51,57] 4039 197 4236 0.04650614 8.682287 8.133774 0.06526000 0.03579599 1.067437\n10 (57,76] 3926 105 4031 0.02604813 8.439381 4.335260 0.66612734 2.73386708 1.946684\n\nI need to add an additional column \"Bin\" that will show numbers from 1 to 10, depending on BR column being in descending order, so for example 10th row becomes first, then first row becomes second, etc.\nAny help would be appreciated\n\nA: A very straightforward way is to use one of the rank functions from \"dplyr\" (eg: dense_rank, min_rank). Here, I've actually just used rank from base R. I've deleted some columns below just for presentation purposes.\nlibrary(dplyr)\nmydf %>% mutate(bin = rank(BR))\n# range X0 X1 total BR ... Index bin\n# 1 (1,23] 5718 194 5912 0.03281461 ... 1.534535 2\n# 2 (23,26] 5249 330 5579 0.05915039 ... 1.207544 8\n# 3 (26,28] 3105 209 3314 0.06306578 ... 1.292856 10\n# 4 (28,33] 6277 416 6693 0.06215449 ... 1.272937 9\n# 5 (33,37] 4443 239 4682 0.05104656 ... 1.033207 5\n# 6 (37,41] 4277 237 4514 0.05250332 ... 1.064326 7\n# 7 (41,46] 4904 265 5169 0.05126717 ... 1.037913 6\n# 8 (46,51] 4582 230 4812 0.04779717 ... 1.037198 4\n# 9 (51,57] 4039 197 4236 0.04650614 ... 1.067437 3\n# 10 (57,76] 3926 105 4031 0.02604813 ... 1.946684 1\n\n\nIf you just want to reorder the rows, use arrange instead:\nmydf %>% arrange(BR)\n\n\nA: bbT11$Bin[order(bbT11$BR)] <- 1:nrow(bbT11)\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/27183110", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Telebot package problem with importing \"Types\" When i want to run my bot in pycharm, I receive this error:\n\\Desktop\\st\\taxi\\taxi.py\", line 5, in \n from telebot import types\nImportError: cannot import name 'types' from 'telebot' (C:\\Users\\User\\Desktop\\st\\taxi\\venv\\lib\\site-packages\\telebot\\__init__.py)\n\nHere is my code:\nimport config\nfrom telebot import TeleBot, types\n\nbot = TeleBot(config.TELEGRAM_BOT_TOKEN)\n\n@bot.message_handler(commands=['location']) #\u0417\u0430\u043f\u0440\u043e\u0441 \u043b\u043e\u043a\u0430\u0446\u0438\u0438\ndef request_location(message):\n keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)\n\n button_geo = types.KeyboardButton(text=\"\u041e\u0442\u043f\u0440\u0430\u0432\u0438\u0442\u044c \u043c\u0435\u0441\u0442\u043e\u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u0435\", request_l\nocation=True)\n keyboard.add(button_geo)\n bot.send_message(message.chat.id, \"\u041f\u043e\u0434\u0435\u043b\u0438\u0441\u044c \u043c\u0435\u0441\u0442\u043e\u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u0435\u043c\", reply_markup=k\neyboard)\n\nif __name__ == \"__main__\":\n bot.polling()\n\nHow to fix this?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/52499589", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Como Criptografar com o Algoritmo AES usando chaves de 128-192-256 em Java Preciso fazer uma criptografia com o algoritmo AES testando o tempo de execu\u00e7\u00e3o de acordo com os tamanhos das chaves (128-192-256), mas eu n\u00e3o estou conseguindo encontrar como alternar o tamanho da chave a ser gerada pelo sistema, pois o meu c\u00f3digo retorna que o tamanho da chave \u00e9 40 bytes ou 37 bytes para as tr\u00eas. \nimport java.io.*; \nimport java.security.*; \nimport java.util.Random; \nimport javax.crypto.*; \nimport javax.crypto.spec.*; \n\npublic class EncriptaDecriptaAES { \n\nKeyGenerator keygenerator = null; \nCipher cifraAES = null; \nSecretKey chaveAES = null; \nSecretKey chaveencriptacao; \nstatic String IV = \"AAAAAAAAAAAAAAAA\"; \n\npublic EncriptaDecriptaAES(int valorKey) throws NoSuchAlgorithmException, UnsupportedEncodingException, NoSuchProviderException, NoSuchPaddingException { \nkeygenerator = KeyGenerator.getInstance(\"AES\"); \nkeygenerator.init(valorKey); \nchaveAES = keygenerator.generateKey(); \nSystem.out.println(((chaveAES.toString()).getBytes(\"UTF-8\")).length); \ncifraAES = Cipher.getInstance(\"AES/CBC/PKCS5Padding\"); // Cria a cifra \nSystem.out.println(cifraAES.getBlockSize()); \n} \n\npublic void encrypt(String srcPath, String destPath) throws UnsupportedEncodingException, InvalidKeyException, InvalidAlgorithmParameterException, FileNotFoundException, IOException, IllegalBlockSizeException, BadPaddingException { \nFile rawFile = new File(srcPath); \nFile imagemEncriptada = new File(destPath); \nInputStream inStream = null; \nOutputStream outStream = null; \ncifraAES.init(Cipher.ENCRYPT_MODE, chaveAES, new IvParameterSpec(IV.getBytes(\"UTF-8\"))); //Inicializa a cifra para o processo de encripta\u00e7\u00e3o \ninStream = new FileInputStream(rawFile); //Inicializa o input e o output streams \noutStream = new FileOutputStream(imagemEncriptada); \nbyte[] buffer = new byte[256]; \nint len; \nwhile ((len = inStream.read(buffer)) > 0) { \noutStream.write(cifraAES.update(buffer, 0, len)); //Para criptografar/descriptografar v\u00e1rios blocos usa-se o m\u00e9todo update(). \noutStream.flush(); \n} \noutStream.write(cifraAES.doFinal()); //Depois de tudo feito chamamos o m\u00e9todo doFinal(). \ninStream.close(); \noutStream.close(); \n} \n\npublic void decrypt(String srcPath, String destPath) throws InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException, FileNotFoundException, IOException, IllegalBlockSizeException, BadPaddingException { \nFile encryptedFile = new File(srcPath); \nFile decryptedFile = new File(destPath); \nInputStream inStream = null; \nOutputStream outStream = null; \ncifraAES.init(Cipher.DECRYPT_MODE, chaveAES, new IvParameterSpec(IV.getBytes(\"UTF-8\"))); //Inicializa o cipher para decriptografar \ninStream = new FileInputStream(encryptedFile); //Inicializa o input e o output streams \noutStream = new FileOutputStream(decryptedFile); \nbyte[] buffer = new byte[256]; \nint len; \nwhile ((len = inStream.read(buffer)) > 0) { \noutStream.write(cifraAES.update(buffer, 0, len)); \noutStream.flush(); \n} \noutStream.write(cifraAES.doFinal()); \ninStream.close(); \noutStream.close(); \n} \n\npublic static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, NoSuchProviderException, InvalidKeyException, InvalidAlgorithmParameterException, IOException, FileNotFoundException, IllegalBlockSizeException, BadPaddingException { \nString directoryPath = \"D:\\\u00c1rea de Trabalho\\\"; //Se mudar o pc, alterar esta linha para o caminho certo \n\nlong tempInicial = 0; \nlong tempFinal = 0; \nlong dif = 0; \n\n//EncriptaDecriptaAES chave128 = new EncriptaDecriptaAES(128); //Passa como parametro o tamanho da chave de 128 bits \nEncriptaDecriptaAES chave192 = new EncriptaDecriptaAES(192); //chave de 192 bits \n//EncriptaDecriptaAES chave256 = new EncriptaDecriptaAES(256); //chave de 256 bits \n\nSystem.out.println(\"Iniciando Codifica\u00e7\u00e3o...\"); \ntempInicial = System.currentTimeMillis(); \nfor (int i = 1; i <= 10; i++) { \nString imgOriginal = \"veiculo\" + i + \".jpg\"; \nString imgEncriptada = \"ImagensCrip\\imgEncripAES_\" + i + \".jpg\"; //Nome do arquivo encriptado \nchave192.encrypt(directoryPath + imgOriginal, directoryPath + imgEncriptada); \n} \ntempFinal = System.currentTimeMillis(); \ndif = (tempFinal - tempInicial); \nSystem.out.println(String.format(\"Tempo de codifica\u00e7\u00e3o: %02d segundos\", dif/60)); \nSystem.out.println(\"Codifica\u00e7\u00e3o Finalizada...\"); \n\ntempInicial = 0; \ntempFinal = 0; \ndif = 0; \n\nSystem.out.println(\"Iniciando Decodifica\u00e7\u00e3o...\"); \ntempInicial = System.currentTimeMillis(); \nfor (int i = 1; i <= 10; i++) { \nString imgEncriptada = \"ImagensCrip\\imgEncripAES_\" + i + \".jpg\"; //Nome do arquivo encriptado \nString imgDecriptada = \"ImagensDecrip\\imgDecripAES_\" + i + \".jpg\"; //Nome do arquivo descriptado \nchave192.decrypt(directoryPath + imgEncriptada, directoryPath + imgDecriptada); \n} \ntempFinal = System.currentTimeMillis(); \ndif = (tempFinal - tempInicial); \nSystem.out.println(String.format(\"Tempo de codifica\u00e7\u00e3o: %02d segundos\", dif/60)); \nSystem.out.println(\"Decodifica\u00e7\u00e3o Finalizada...\"); \n} \n} \n\n\nA: Acredito que o problema do seu c\u00f3digo esteja apenas na sa\u00edda:\nSystem.out.println(((chaveAES.toString()).getBytes(\"UTF-8\")).length);\n\nO toString() parece n\u00e3o estar implementado, e parece retornar lixo. Eu tentei imprimir a string e o resultado foi algo como [B@6a9c98e8.\nPor\u00e9m, existe o m\u00e9todo getEncoded(), que parece retornar o que voc\u00ea deseja.\nExecutando o seu c\u00f3digo, com algumas modifica\u00e7\u00f5es, eu obtive o seguinte resultado, utilizando 128 bits:\n\nE, utilizando 256 bits, o resultado \u00e9 este:\n\nVeja que o tamanho da chave mudou de 16 para 32 bytes. Segue o c\u00f3digo alterado:\nimport java.io.*;\nimport java.security.*; \nimport javax.crypto.*; \nimport javax.crypto.spec.*;\n\npublic class EncriptaDecriptaAES {\n\n KeyGenerator keygenerator = null;\n Cipher cifraAES = null;\n SecretKey chaveAES = null; \n static String IV = \"AAAAAAAAAAAAAAAA\";\n final protected static char[] hexArray = \"0123456789ABCDEF\".toCharArray();\n\n public EncriptaDecriptaAES(int valorKey) throws NoSuchAlgorithmException,\n UnsupportedEncodingException, NoSuchProviderException, NoSuchPaddingException { \n\n keygenerator = KeyGenerator.getInstance(\"AES\");\n keygenerator.init(valorKey);\n chaveAES = keygenerator.generateKey();\n\n // Isso nao parece dar certo!\n // System.out.println(((chaveAES.toString()).getBytes(\"UTF-8\")).length);\n\n System.out.println();\n System.out.println(\"Tamanho da chave: \" + chaveAES.getEncoded().length);\n System.out.println(\"Chave: \" + bytesToHex(chaveAES.getEncoded()));\n\n // Cria a cifra\n cifraAES = Cipher.getInstance(\"AES/CBC/PKCS5Padding\");\n\n System.out.println(\"Tamanho do bloco: \" + cifraAES.getBlockSize());\n System.out.println();\n\n }\n\n public void encrypt(String srcPath, String destPath) throws UnsupportedEncodingException,\n InvalidKeyException, InvalidAlgorithmParameterException, FileNotFoundException,\n IOException, IllegalBlockSizeException, BadPaddingException {\n\n\n File rawFile = new File(srcPath); \n File imagemEncriptada = new File(destPath); \n InputStream inStream = null; \n OutputStream outStream = null; \n cifraAES.init(Cipher.ENCRYPT_MODE, chaveAES,\n //Inicializa a cifra para o processo de encriptacao\n new IvParameterSpec(IV.getBytes(\"UTF-8\")));\n\n //Inicializa o input e o output streams\n inStream = new FileInputStream(rawFile);\n outStream = new FileOutputStream(imagemEncriptada);\n\n byte[] buffer = new byte[256]; \n int len; \n\n while ((len = inStream.read(buffer)) > 0) { \n //Para criptografar/descriptografar varios blocos usa-se o metodo update().\n outStream.write(cifraAES.update(buffer, 0, len));\n outStream.flush();\n }\n\n //Depois de tudo feito chamamos o metodo doFinal().\n outStream.write(cifraAES.doFinal());\n inStream.close();\n outStream.close();\n\n } \n\n public void decrypt(String srcPath, String destPath) throws InvalidKeyException,\n InvalidAlgorithmParameterException, UnsupportedEncodingException, FileNotFoundException,\n IOException, IllegalBlockSizeException, BadPaddingException {\n\n\n File encryptedFile = new File(srcPath); \n File decryptedFile = new File(destPath); \n InputStream inStream = null; \n OutputStream outStream = null; \n\n //Inicializa o cipher para decriptografar\n cifraAES.init(Cipher.DECRYPT_MODE, chaveAES, new IvParameterSpec(IV.getBytes(\"UTF-8\")));\n\n //Inicializa o input e o output streams\n inStream = new FileInputStream(encryptedFile);\n outStream = new FileOutputStream(decryptedFile); \n\n byte[] buffer = new byte[256]; \n int len; \n\n while ((len = inStream.read(buffer)) > 0) { \n outStream.write(cifraAES.update(buffer, 0, len)); \n outStream.flush(); \n }\n\n outStream.write(cifraAES.doFinal()); \n inStream.close(); \n outStream.close(); \n\n }\n\n public static String bytesToHex(byte[] bytes) {\n char[] hexChars = new char[bytes.length * 2];\n for ( int j = 0; j < bytes.length; j++ ) {\n int v = bytes[j] & 0xFF;\n hexChars[j * 2] = hexArray[v >>> 4];\n hexChars[j * 2 + 1] = hexArray[v & 0x0F];\n }\n return new String(hexChars);\n }\n\n public static void main(String[] args) throws NoSuchAlgorithmException,\n NoSuchPaddingException, UnsupportedEncodingException, NoSuchProviderException,\n InvalidKeyException, InvalidAlgorithmParameterException, IOException,\n FileNotFoundException, IllegalBlockSizeException, BadPaddingException {\n\n //Se mudar o pc, alterar esta linha para o caminho certo\n String directoryPath = \"\";\n\n long tempInicial = 0;\n long tempFinal = 0; \n long dif = 0; \n\n //Passa como parametro o tamanho da chave de 128, 192 ou 256 bits\n EncriptaDecriptaAES chave = new EncriptaDecriptaAES(256);\n\n System.out.println(\"Iniciando Codificacao...\");\n tempInicial = System.nanoTime(); \n\n for (int i = 1; i <= 10; i++) { \n // String imgOriginal = \"imagem_\" + i + \".jpg\";\n String imgOriginal = \"imagem_1.jpg\";\n\n //Nome do arquivo encriptado\n String imgEncriptada = \"imgEncripAES_\" + i + \".jpg\"; \n chave.encrypt(directoryPath + imgOriginal, directoryPath + imgEncriptada);\n\n }\n\n tempFinal = System.nanoTime();\n dif = (tempFinal - tempInicial);\n double segundos = (double)dif / 1000000000.0;\n\n System.out.println(\"Tempo de codificacao: \" + segundos + \" segundos.\");\n System.out.println(\"Codificacao Finalizada...\"); \n\n // tempInicial = 0; \n // tempFinal = 0; \n // dif = 0; \n\n System.out.println();\n System.out.println(\"Iniciando Decodificacao...\");\n tempInicial = System.nanoTime(); \n\n for (int i = 1; i <= 10; i++) { \n String imgEncriptada = \"imgEncripAES_\" + i + \".jpg\"; //Nome do arquivo encriptado \n String imgDecriptada = \"imgDecripAES_\" + i + \".jpg\"; //Nome do arquivo descriptado \n chave.decrypt(directoryPath + imgEncriptada, directoryPath + imgDecriptada); \n }\n\n tempFinal = System.nanoTime(); \n dif = (tempFinal - tempInicial);\n segundos = (double)dif / 1000000000.0;\n\n System.out.println(\"Tempo de decodificacao: \" + segundos + \" segundos.\"); \n System.out.println(\"Decodificacao Finalizada...\");\n\n }\n}\n\nAten\u00e7\u00e3o:\n\n\n*\n\n*Eu comentei a parte que abre imagens diferentes e utilizei um c\u00f3digo que trabalha sempre em cima da mesma imagem (como teste).\n\n*Inclu\u00ed um m\u00e9todo novo para converter bytes para hexadecimal. Eu encontrei ele aqui.\n\n*Mudei de System.currentTimeMillis(); para System.nanoTime(); por recomenda\u00e7\u00e3o de diversos posts.\n\n*Eu testei o c\u00f3digo utilizando a mesma imagem dez mil vezes com as tr\u00eas chaves de tamanhos diferentes e o tempo n\u00e3o variou muito, o que \u00e9 estranho. Ent\u00e3o n\u00e3o confie totalmente no c\u00f3digo que eu postei... ;)\n\n*Se voc\u00ea puder comentar com o resultado dos seus testes, eu agradeceria!\n\n", "meta": {"language": "pt", "url": "https://pt.stackoverflow.com/questions/87111", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "5"}} {"text": "Q: QtQuick2 Video rendering quality and embedding QVideoWidget to Qml I am working on a Qml application based on the QtQuick2, and I am having problems with the Video component included in the QtMultimedia 5.0 module. The application is supposed to add video to Qml interface and most importantly is that any BLACK color (background, rectangle or object) must be REALLY BLACK so I can overlay other Qml components over the black areas.\nWhen a video is played in the C++ QvideWidget, the video quality is good, and all the black area are really black, but when I use the QtQuick2 Video component, the quality is a little bit yellowish. I was able to do it easily in the Qt 4.8.7 with QtQuick1 using QDeclarativeItem and QGraphicProxyWidget, but since Qt5 changed the QtQuick2 way, I couldn't find a way to easily embedded widget.\nI have made a custom QAbstractVideoSurface and set it as QMediaPlay->setVideoOutput, and paint it in QtQuickPaintedItem by grabbing QImage and calling update(), but still same. Even changed all qRGB below treshold of 16 to qRgb(0,0,0), but the result is bad, especially on fade-in or fade-out.\nIs there any way I could fix this? Thanks in advance\n \n\n\nEdit 1: inserted code\n import QtQuick 2.6\n import QtMultimedia 5.0\n\n Video{\n\n id: video\n width: root.width\n height: root.height\n\n property string src: \"main.mp4\"\n\n source: src\n autoLoad: true\n autoPlay: true\n fillMode: VideoOutput.PreserveAspectFit\n }\n\nC++ Code with QVideoWidget\nQMediaPlayer *player = new QMediaPlayer();\nQVideoWidget *view = new QVideoWidget();\n\nplayer->setVideoOutput(view);\nplayer->play();\n\n\nview->resize(700, 700);\nview->show();\n\nCustom QAbstractSurface\n#include \"videoframegrabber.h\"\n\nVideoFrameGrabber::VideoFrameGrabber(QObject *parent)\n : QAbstractVideoSurface(parent)\n , imageFormat(QImage::Format_Invalid)\n{\n}\n\nQList VideoFrameGrabber::supportedPixelFormats(QAbstractVideoBuffer::HandleType handleType) const\n{\n Q_UNUSED(handleType);\n return QList()\n << QVideoFrame::Format_ARGB32\n << QVideoFrame::Format_ARGB32_Premultiplied\n << QVideoFrame::Format_RGB32\n << QVideoFrame::Format_RGB24\n << QVideoFrame::Format_RGB565\n << QVideoFrame::Format_RGB555\n << QVideoFrame::Format_ARGB8565_Premultiplied\n << QVideoFrame::Format_BGRA32\n << QVideoFrame::Format_BGRA32_Premultiplied\n << QVideoFrame::Format_BGR32\n << QVideoFrame::Format_BGR24\n << QVideoFrame::Format_BGR565\n << QVideoFrame::Format_BGR555\n << QVideoFrame::Format_BGRA5658_Premultiplied\n << QVideoFrame::Format_AYUV444\n << QVideoFrame::Format_AYUV444_Premultiplied\n << QVideoFrame::Format_YUV444\n << QVideoFrame::Format_YUV420P\n << QVideoFrame::Format_YV12\n << QVideoFrame::Format_UYVY\n << QVideoFrame::Format_YUYV\n << QVideoFrame::Format_NV12\n << QVideoFrame::Format_NV21\n << QVideoFrame::Format_IMC1\n << QVideoFrame::Format_IMC2\n << QVideoFrame::Format_IMC3\n << QVideoFrame::Format_IMC4\n << QVideoFrame::Format_Y8\n << QVideoFrame::Format_Y16\n << QVideoFrame::Format_Jpeg\n << QVideoFrame::Format_CameraRaw\n << QVideoFrame::Format_AdobeDng;\n}\n\nbool VideoFrameGrabber::isFormatSupported(const QVideoSurfaceFormat &format) const\n{\n const QImage::Format imageFormat = QVideoFrame::imageFormatFromPixelFormat(format.pixelFormat());\n const QSize size = format.frameSize();\n\n return imageFormat != QImage::Format_Invalid\n && !size.isEmpty()\n && format.handleType() == QAbstractVideoBuffer::NoHandle;\n}\n\nbool VideoFrameGrabber::start(const QVideoSurfaceFormat &format)\n{\n const QImage::Format imageFormat = QVideoFrame::imageFormatFromPixelFormat(format.pixelFormat());\n const QSize size = format.frameSize();\n\n if (imageFormat != QImage::Format_Invalid && !size.isEmpty()) {\n this->imageFormat = imageFormat;\n imageSize = size;\n sourceRect = format.viewport();\n\n QAbstractVideoSurface::start(format);\n\n //widget->updateGeometry();\n //updateVideoRect();\n\n return true;\n } else {\n return false;\n }\n}\n\nvoid VideoFrameGrabber::stop()\n{\n currentFrame = QVideoFrame();\n targetRect = QRect();\n\n QAbstractVideoSurface::stop();\n\n //widget->update();\n}\n\nbool VideoFrameGrabber::present(const QVideoFrame &frame)\n{\n if (frame.isValid())\n {\n QVideoFrame cloneFrame(frame);\n cloneFrame.map(QAbstractVideoBuffer::ReadOnly);\n const QImage image(cloneFrame.bits(),\n cloneFrame.width(),\n cloneFrame.height(),\n QVideoFrame::imageFormatFromPixelFormat(cloneFrame .pixelFormat()));\n emit frameAvailable(image); // this is very important\n cloneFrame.unmap();\n }\n\n if (surfaceFormat().pixelFormat() != frame.pixelFormat()\n || surfaceFormat().frameSize() != frame.size()) {\n setError(IncorrectFormatError);\n stop();\n\n return false;\n } else {\n currentFrame = frame;\n\n //widget->repaint(targetRect);\n\n return true;\n }\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/58048837", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Logstash: Missing data after migration I have been migrating one of the indexes in self-hosted Elasticsearch to amazon-elasticsearch using Logstash. we have around 1812 documents in our self-hosted Elasticsearch but in amazon-elasticsearch, we have only about 637 documents. Half of the documents are missing after migration.\nOur logstash config file \ninput {\n elasticsearch {\n hosts => [\"https://staing-example.com:443\"]\n user => \"userName\"\n password => \"password\"\n index => \"testingindex\"\n size => 100\n scroll => \"1m\"\n }\n}\n\nfilter {\n\n}\n\noutput {\n amazon_es {\n hosts => [\"https://example.us-east-1.es.amazonaws.com:443\"]\n region => \"us-east-1\"\n aws_access_key_id => \"access_key_id\"\n aws_secret_access_key => \"access_key_id\"\n index => \"testingindex\"\n}\nstdout{\n codec => rubydebug\n }\n}\n\nWe have tried for some of the other indexes as well but it still migrating only half of the documents.\n\nA: Make sure to compare apples to apples by running GET index/_count on your index on both sides.\nYou might see more or less documents depending on where you look (Elasticsearch HEAD plugin, Kibana, Cerebro, etc) and if replicas are taken into account in the count or not.\nIn your case you had more replicas in your local environment than in your AWS Elasticsearch service, hence the different count.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/58390552", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Image of closed unit ball under a compact operator Let $X,Y$ be Banach spaces and $A\\in\\mathcal L(X,Y)$ . The task is to prove the following:\n$A$ is compact if and only if the image of the closed unit ball in $X$ is compact in $Y$.\nI have proven this when $X$ is a reflexive space.\nProof. Let $X$ be a reflexive space, $\\bar B$ the closed unit ball in $X$, and $A$ a compact operator. Let further $y_n=Ax_n$ be a sequence in $A(\\bar B)$.\nIn reflexive spaces $\\bar B$ is weakly compact, so there exists a subsequence $x_{n_j} \\to x$ weakly.\nBecause $A$ is compact, $Ax_{n_j}\\to Ax$ strongly. \nOn the other side, $A(\\bar B)$ is relatively compact, so there exists $z_k=Ax_{n_{j_k}}$ that converges strongly to $y\\in Y$.\nBut $z_k\\to Ax$ strongly. So by unicity of the limit $y=Ax$ and the image is compact.\nIt's easily proved that if the image is compact, the operator is also compact.\nBut I don't know what to do in case of nonreflexive spaces. Is there any counterexample or proof in such case?\n\nA: It is false in general that the image of the closed unit ball under a compact operator is closed (and hence compact). Here is an easy example:\nConsider $X = C[0,1]$ with the uniform norm, and the compact operator $A \\in B(X)$ defined by the formula:\n$\\displaystyle\\qquad Af(x) = \\int_0^x f(t)\\,dt$.\nCompactness of $A$ is easily proven using Arzel\u00e0\u2013Ascoli. Our operator $A$ produces an anti-derivative of any input given to it, and the image of the closed unit ball of $X$ under $A$ is the set\n$\\displaystyle\\qquad \\{f \\in C^1[0,1] \\mathrel: f(0)=0,\\ \\lVert f'\\rVert \\leq 1\\}$\nwhich certainly is not a closed subset of $X$. \n\nA: This is much easier. Use the definition of compact operator. An operator is compact if and only if the image of a bounded set is precompact. The unit ball is bounded and any other bounded set is inside some $\\lambda$ times the unit ball.\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/404516", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "5"}} {"text": "Q: My Org's IP address is not in the given IP Range The list of IP ranges to be whitelisted are (as far as I know the followings): https://help.salesforce.com/s/articleView?id=000321501&type=1 -\nhowever my call is sent out from an IP Address (check if You don't trust: 35.157.191.28 ), which is nowhere on this list, so my API call was totally ignored (the response is empty without errormsg or even http status code) because according to the integrated system's inner logs we \"matched none of the trusted IPs\".\nWhat does it mean? What should I do?\n\nA: Assuming that your instance is on Hyperforce, the following would be worth visiting (Otherwise, this answer is irrelevant).\n1. What does it mean?\nThis would most likely mean that you are a hyperforce customer. Your salesforce instance could no more be hosted in Salesforce-Managed Instances or Public Cloud Instances, but on Hyperforce Instances. To find out if you are hyperforce customer, locate your Instance ID from Setup > Company Information page, and verify in the Hyperforce instances listed here.\nAs mentioned here,\n\nIf you are a Hyperforce customer, Salesforce will no longer publish IP addresses for Hyperforce customers. In addition to the IP\nranges below, you should follow our recommendations as outlined in the\nRetain uninterrupted access to Salesforce\nservices\non Hyperforce article.\n\nThis could be the possible reason for why you are unable to locate your IP address here.\n2. What should I do?\nAs recommended by Salesforce, you should move away from hard-coded IP allowlists or hard-coded instance specific references and instead allow required domains (including the salesforce myDomain). Some useful references mentioned below:\nRetain uninterrupted access to Salesforce services on Hyperforce\n\nDon\u2019t Use Hard-Coded IP Allowlists IP allowlisting historically was used as a low-tech form of security to prevent internet traffic\nfrom being rerouted. This strategy requires vigilant maintenance when\nnew instances and servers come online. As Hyperforce rapidly scales,\nthe manual overhead of this approach will become unmanageable for\ncustomers. So, Hyperforce IPs aren\u2019t published, and allowlisting isn\u2019t\nsupported.\nUsers benefit from replacing fragile IP allowlists with modern and\nsustainable approaches to security. The next section describes common\nreasons for allowlisting and recommended alternatives.\nControl User and API Client Access to Salesforce Services If you use IP allowlists to control user or server access to the internet,\nthen Allow the Required Domains.\nSecure access to these domains is enforced through the use of HTTPS\nand SSL client certificates.\n\nYou might find some more useful information in these links: Hyperforce - General FAQ, Updating Hard-coded references & Allow the Required Domains\nWith the minimal details in your question, explaining more towards all the details related to Hyperforce is beyond the scope of this question.\nDisclaimer: I'm neither an expert on networking nor on Hyperforce. I've not gone thru all text in the aforementioned articles, but some of it will be relevant to your question (provided you are in Hyperforce)\n", "meta": {"language": "en", "url": "https://salesforce.stackexchange.com/questions/381012", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Program that checks if number can be divided to three numbers I need to make a program that checks if a number can be divided to three(or more) numbers. for example 8=2*2*2 and 153=3*3*17 and so on. And it has to work for all positive real numbers. I just can't wrap my head around it :(\n def loytyyko_kolme_tekijaa(luku):\n tekija = 2\n kaikki = 0\n while luku > tekija:\n if luku % tekija == 0:\n kaikki = kaikki + 1 \n tekija = tekija + 1 \n if kaikki >= 3:\n return True\n else:\n return False\n\n\nA: Ok now that I see that you tried. Is this what you want?\nCopied answer from here:\nPython - Integer Factorization into Primes\ndef factorize(num):\n for possible_factor in range(2, num):\n if num % possible_factor == 0:\n return [possible_factor] + factorize(num // possible_factor)\n return [num]\n\nnums = [8,153]\nfor num in nums:\n print(\"{}: {}\".format(num, factorize(num)))\n\nReturns:\n8: [2, 2, 2]\n153: [3, 3, 17]\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/46662206", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-5"}} {"text": "Q: How do I fill a rectangle or ellipse with a gradient in Processing? I am trying to get my paddles from white to gradient (linear) and the ball to have a radial gradient. Thanks for your help!You can find the code for the paddles in void drawPaddle.\nThis is my goal:\n\nThis is my code:\n//Ball\nint ballX = 500;\nint ballY = 350;\nint ballHeight = 35;\nint ballWidth = 35;\nint speedX = 4;\nint speedY = 4;\nint directionX = 1;\nint directionY = 1;\n//Paddles\nint player1X = 30;\nint player2X = 830;\nint player1Y = 350;\nint player2Y = 350;\n\n//Healthbars\nint bar1X = 100;\nint bar1Y = 20;\nint player1health = 100;\nint bar1colour = #22E515;\nint bar2X = 700;\nint bar2Y = 20;\nint player2health = 100;\nint bar2colour = #22E515;\n\n//Movements\nboolean upX = false;\nboolean downX = false;\nboolean upY = false;\nboolean downY = false;\n\nvoid setup() {\n size(900, 700);\n}\n\nvoid draw() {\n background(55, 68, 120);\n\ndrawPaddle();\n\n //EmptySpace**\n fill(55, 68, 120);\n noStroke();\n rect(player1X, player1Y, 40, 140);\n rect(player2X, player2Y, 40, 140);\n \n //Healthbars\n fill(bar1colour);\n rect(bar1X, bar1Y, player1health, 15);\n fill(bar2colour);\n rect(bar2X, bar2Y, player2health, 15);\n\n //Ball\n fill(194, 16, 0);\n ellipse(ballX, ballY, ballHeight, ballWidth);\n \n\n moveCircle();\n movePaddle();\n moveCollisions();\n}\n\nvoid drawPaddle() { \n fill(255);\n noStroke();\n rect(30, 0, 40, 1000);\n rect(830, 0, 40, 1000);\n}\n\nvoid moveCircle() { \n ballX = ballX + speedX * 1;\n ballY = ballY + speedY * 1;\n\n if (ballX > width- ballWidth +20 || ballX < ballWidth) {\n speedX *= -1;\n }\n if (ballY > height- ballHeight +20 || ballY < ballHeight) {\n speedY *= -1;\n }\n}\n\nvoid movePaddle() {\n //key movements\n if (upX == true) {\n player1Y = player1Y - 5;\n }\n if (downX == true) {\n player1Y = player1Y + 5;\n }\n if (upY == true) {\n player2Y = player2Y - 5;\n }\n if (downY == true) {\n player2Y = player2Y + 5;\n } \n\n //Wrap around\n if (player1Y > 700) {\n player1Y = 0;\n } else if (player1Y + 140 < 0) {\n player1Y = 700;\n }\n if (player2Y > 700) {\n player2Y = 0;\n } else if (player2Y + 140 < 0) {\n player2Y = 700;\n }\n}\n\nvoid moveCollisions() {\n //Collisions\n if ((ballX - ballWidth / 2 < player1X + 40) && ((ballY - ballHeight / 2 > player1Y + 140) || (ballY + ballHeight / 2 < player1Y))) {\n if (speedX < 0) {\n player1health -= 20;\n speedX = -speedX*1;\n if (player1health == 20) {\n bar1colour = #F51911;\n }\n }\n } else if ((ballX + ballWidth / 2 > player2X) && ((ballY - ballHeight / 2 > player2Y + 140) || (ballY + ballHeight/2 < player2Y))) {\n if (speedX > 0) {\n player2health -= 20;\n bar2X += 20;\n speedX = -speedX*1;\n if (player2health == 20) {\n bar2colour = #F51911;\n }\n }\n }\n}\n\nvoid keyPressed() {\n if (key == 'w' || key == 'W') {\n upX = true;\n } else if (key == 's' || key == 'S') {\n downX = true;\n } else if (keyCode == UP) {\n upY = true;\n } else if (keyCode == DOWN) {\n downY = true;\n }\n}\n\nvoid keyReleased() {\n if (key == 'w' || key == 'W') {\n upX = false;\n } else if (key == 's' || key == 'S') {\n downX = false;\n } else if (keyCode == UP) {\n upY = false;\n } else if (keyCode == DOWN) {\n downY = false;\n }\n}\n\n\nA: I wrote a library just for this kind of purpose (drawing colour gradients in Processing) called PeasyGradients \u2014 download the .jar from the Github releases and drag-and-drop it onto your sketch. It renders 1D gradients as 2D spectrums into your sketch or a given PGraphics object.\nHere's an example of drawing linear and radial spectrums using your desired gradient:\nPeasyGradients renderer;\nPGraphics rectangle, circle, circleMask;\n\nfinal Gradient pinkToYellow = new Gradient(color(227, 140, 185), color(255, 241, 166));\n\nvoid setup() {\n size(800, 800);\n\n renderer = new PeasyGradients(this);\n\n rectangle = createGraphics(100, 400);\n renderer.setRenderTarget(rectangle); // render into rectangle PGraphics\n renderer.linearGradient(pinkToYellow, PI/2); // gradient, angle\n\n circle = createGraphics(400, 400);\n renderer.setRenderTarget(circle); // render into circle PGraphics\n renderer.radialGradient(pinkToYellow, new PVector(200, 200), 0.5); // gradient, midpoint, zoom\n\n // circle is currently a square image of a radial gradient, so needs masking to be circular \n circleMask = createGraphics(400, 400);\n circleMask.beginDraw();\n circleMask.fill(255); // keep white pixels\n circleMask.circle(200, 200, 400);\n circleMask.endDraw();\n\n circle.mask(circleMask);\n}\n\nvoid draw() {\n background(255);\n\n image(rectangle, 50, 50);\n\n image(circle, 250, 250);\n}\n\n\n\nA: What you can try is make a PGraphics object for each rectangle you are drawing, fill it with gradient color using linear interpolation and then instead of using rect(x1, y1, x2, y2), in drawPaddle() use image(pgraphic, x, y).\nHere is how you can create a gradient effect using lerpColor() in processing:\n\n*\n\n*Make a start point say (x1, y1) and end point say (x2, y2) of the gradient.\n\n*Make a starting and a ending color say c1 and c2.\n\n*Now for a point P (x, y), calculate the distance between start point and P and divide it by the distance between the start point and and end point. This will be the 'amount' to lerp from start color and end color.\nfloat t = dist(x1, y1, x, y) / dist(x1, x2, y1, y2)\n\n*Put this value in lerpColor() as lerpColor(c1, c2, value). This will give you the color for point P.\n\n*Repeat the same for every point you want to calculate the gradient for.\n\nHere's an example:\nNote: here, i am taking t which is the amount to be lerped as the distance between the starting point of gradient divided by the distance between the start and end point of gradient, as it will always be a value in between 0 and 1.\nPGraphics g = createGraphics(50, 200); // set these values to the size(width, height) of paddle you want \n color startColor = color(255, 25, 25); // color of start of the gradient\n color endColor = color(25, 25, 255); // color of end of the gradient\n \n g.beginDraw(); //start drawing in this as you would draw in the screen\n g.loadPixels();//load pixels, as we are going to set the color of this, pixel-by-pixel\n \n int x1 = g.width/2;\n int y1 = 0;\n int x2 = g.width/2;\n int y2 = g.height;\n \n // (x1, y1) is the start point of gradient\n // (x2, y2) is the end point of gradient\n \n // loop through all the pixels\n for (int x=0; xterm_id;\n $category_child_id = $category_child->term_id;\n $wpdb->update( \n $wpdb->prefix.'term_taxonomy', \n array( \n 'parent' => $category_parent_id,\n\n ), \n array( 'term_id' => $category_child_id ) \n\n );\n\n", "meta": {"language": "en", "url": "https://wordpress.stackexchange.com/questions/245438", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Find the jordan form of a given matrix let $n,k\\in\\ N$ and $\\lambda \\in F$.\nFind the rank and the Jordan form of matrix $$A={ J }_{ n }{ (\\lambda ) }^{ k }$$\n\nA: $J_n(\\lambda)^k$ is an upper-triangular matrix, and its diagonal elements will all be $\\lambda^k$. Thus, its rank is $n$, and its Jordan form is $J_n(\\lambda^k)$\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/413930", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Sass build issue for sublime text 2 : no file is generated I've downloaded Ruby and installed Sass. I then installed Sass Build for Sublime Text 2 through the package manager but when I try to build my css file, nothing happens.\nIt says :\n\n[Decode error - output not utf-8]\n [Finished in 0.1s with exit code 1]\n\nDoes anyone know how to fix this ?\n\nA: By default, the output encoding in a sublime build is utf-8. This will cause an error if there are non-utf-8 characters in your sass or scss.\nYou can create a custom sass .sublime-build along the lines of the following by going to Tools > Build System > New Build System.\n{\n\n \"cmd\": [\"sass\", \"--update\", \"$file:${file_path}/${file_base_name}.css\", \"--stop-on-error\", \"--no-cache\"],\n \"selector\": \"source.sass, source.scss\",\n \"line_regex\": \"Line ([0-9]+):\",\n\n \"osx\":\n {\n \"path\": \"/usr/local/bin:$PATH\"\n },\n\n \"windows\":\n {\n \"shell\": \"true\"\n }\n\n \"encoding\": \"cp1252\"\n}\n\nNote the key (the only one that'll be surplus from the installed package) \"encoding\": \"cp1252\". Its value will have to match that of your source or be a superset thereof. There's a fairly comprehensive list of codecs in the Python docs.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/32000383", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to use PermissionRequiredMixin in FBV? I am thinking about how I can use PermissionRequiredMixin in FBV.(I have used the same in CBV and it is working as expected).\nPlease find the FBV(here need to implement permission). I don't want to use @login_required()\n\n@login_required()\nThis will check only if the user is authenticated or not.\n\ndef delete_viewgen(request,PermissionRequiredMixin,id):\n oneuser=ShiftChange.objects.get(id=id)\n permission_required = ('abc.add_shiftchange',)\n oneuser.delete()# delete\n return redirect('/gensall')\n\nI am getting ERROR : missing 1 required positional argument: 'PermissionRequiredMixin'\nCBV Case where it is working fine.\nclass ShiftChangeUpdateView(PermissionRequiredMixin,UpdateView):\n permission_required = ('abc.change_shiftchange',)\n login_url = '/login/'\n model=ShiftChange\n fields='__all__'\n\nIn CBV it is working fine and if user is not having change permission it is giving 403 Forbidden how to implement same in FBV and also how to customize 403 Forbidden message.\nThanks!\n\nA: On function based views you would use decorators, in your particular case\npermission_required decorator\n@permission_required('abc.change_shiftchange', raise_exception=True)\ndelete_viewgen(request,id)\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/65650217", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Default Firefox browser not playing some content I can't play videos like the ones on most twitter posts, for example, https://twitter.com/doglab/status/1255593258916499458?s=20. However, Chrome plays them.\nAlso is there any recommended set of installs that power users can do a day or two after getting Ubuntu 20.04 to get the most used video codecs and other tools?\nsolved with\nsudo apt update\n\nsudo apt upgrade -y\n\nsudo apt install ffmpeg\n\nand ubuntu-restricted-extra via the checkbox in \"Software and Updates\" panel -> https://postimg.cc/yWx4qS90\n\n\nA: I had the same issue and after running the following command : \nsudo apt install ffmpeg\nIt's a big install just for playing videos in firefox, but at least it works, and having ffmpeg on your system might always be useful.\n", "meta": {"language": "en", "url": "https://askubuntu.com/questions/1233182", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to extract year from a date variable and decrement it in XSL From the following XML, i have to extract the year 1989 and decrement it by 2 and display the year.\n\n\n \n Empire Burlesque\n Bob Dylan\n USA\n Columbia\n 10.90\n 10/10/1989\n \n\n\nXSL:\n\n\n\n \n \n

    My CD Collection

    \n \n \n --1989-2 value should be displayed here-----\n \n \n
    \n
    \n\n\nA: \n \n \n \n \n

    My CD Collection

    \n \nI want last 4 characters, so I did a minus 3. If its last n characters, do minus n-1 \n \n \n \n \n
    \n
    \n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/30796417", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: \u041a\u0430\u043a \u0441\u043e\u0432\u043c\u0435\u0441\u0442\u0438\u0442\u044c \u0437\u0430\u043f\u0443\u0441\u043a flask \u043f\u0440\u0438\u043b\u043e\u0436\u0435\u043d\u0438\u044f \u0441 \u0434\u0440\u0443\u0433\u0438\u043c \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u043c? \u0418\u043c\u0435\u0435\u0442\u0441\u044f \u0442\u0435\u043b\u0435\u0433\u0440\u0430\u043c \u0431\u043e\u0442 \u043d\u0430 flask, \u0432 \u043a\u043e\u0442\u043e\u0440\u043e\u043c \u0435\u0441\u0442\u044c \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u043e\u0439 \u043e\u0442\u043f\u0440\u0430\u0432\u043a\u0438 \u0443\u0432\u0435\u0434\u043e\u043c\u043b\u0435\u043d\u0438\u0439 \u0440\u0435\u0430\u043b\u0438\u0437\u043e\u0432\u0430\u043d\u043d\u0430\u044f \u0447\u0435\u0440\u0435\u0437 schedule \u0438 \u0437\u0430\u043f\u0443\u0441\u043a\u0430\u0435\u043c\u0430\u044f \u043e\u0442\u0434\u0435\u043b\u044c\u043d\u044b\u043c \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u043e\u043c. \u041f\u0440\u0438 \u0437\u0430\u043f\u0443\u0441\u043a\u0435 \u043f\u0440\u0438\u043b\u043e\u0436\u0435\u043d\u0438\u044f \u0438\u0437 gunicorn \u0441\u0442\u0430\u0440\u0442\u0443\u0435\u0442 \u043a\u043b\u0430\u0441\u0441 flask \u043f\u0440\u0438\u043b\u043e\u0436\u0435\u043d\u0438\u044f, shedule \u043d\u0435 \u0437\u0430\u043f\u0443\u0441\u043a\u0430\u0435\u0442\u0441\u044f \u0442.\u043a \u0432\u044b\u043d\u0435\u0441\u0435\u043d \u0437\u0430 \u043d\u0435\u0433\u043e. \u041f\u043e\u0434\u0441\u043a\u0430\u0436\u0438\u0442\u0435 \u043a\u0430\u043a \u043c\u043e\u0436\u043d\u043e \u043f\u0435\u0440\u0435\u043f\u0438\u0441\u0430\u0442\u044c \u0434\u0430\u043d\u043d\u044b\u0439 \u043a\u043e\u0434, \u0447\u0442\u043e\u0431\u044b shedule \u0441\u043c\u043e\u0433 \u0437\u0430\u043f\u0443\u0441\u0442\u0438\u0442\u044c\u0441\u044f?\napp = flask.Flask(__name__)\nlogger = telebot.logger\ntelebot.logger.setLevel(logging.INFO)\n\nAPI_TOKEN = config.token\nWEBHOOK_HOST = config.host\nWEBHOOK_PORT = config.port\nWEBHOOK_LISTEN = config.listen_ip\nWEBHOOK_SSL_CERT = config.ssl_cert \nWEBHOOK_SSL_PRIV = config.ssl_priv\nWEBHOOK_URL_BASE = \"https://%s:%s\" % (WEBHOOK_HOST, WEBHOOK_PORT)\nWEBHOOK_URL_PATH = \"/%s/\" % (API_TOKEN)\n\nbot = telebot.TeleBot(API_TOKEN)\n\n# \u041e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u0435 \u043c\u0435\u0442\u043e\u0434\u044b \u0431\u043e\u0442\u0430 \u0432\u044b\u043a\u043b\u0430\u0434\u044b\u0432\u0430\u0442\u044c \u0441\u044e\u0434\u0430 \u043d\u0435 \u0441\u0442\u0430\u043b, \u0434\u0430\u0431\u044b \u043d\u0435 \u0440\u0430\u0437\u0434\u0443\u0432\u0430\u0442\u044c \u0438 \u0442\u0430\u043a \u043d\u0435\u043c\u0430\u043b\u0435\u043d\u044c\u043a\u0438\u0439 \u043a\u043e\u0434\n\n@bot.message_handler(commands=['start'])\ndef start(message):\n chat_id = get_chat_id(message)\n logo = open(config.path_to_logo, 'rb')\n bot.send_photo(\n chat_id, logo, caption='\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435. \u042d\u0442\u043e - \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u043e\u043d\u043d\u044b\u0439 \u0431\u043e\u0442 \u043a\u043e\u043c\u043f\u0430\u043d\u0438\u0438 BigTelecom.')\n menu(message)\n\n@app.route(WEBHOOK_URL_PATH, methods=['POST'])\ndef webhook():\n if flask.request.headers.get('content-type') == 'application/json':\n json_string = flask.request.get_data().decode('utf-8')\n update = telebot.types.Update.de_json(json_string)\n bot.process_new_updates([update])\n return ''\n else:\n flask.abort(403)\n\ndef send_notification():\n # if datetime.datetime.now().day == 28: # \u041e\u0442\u043f\u0440\u0430\u0432\u043a\u0430 \u043d\u0430\u043f\u043e\u043c\u0438\u043d\u0430\u043d\u0438\u044f \u043e \u043f\u043e\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0438 \u0431\u0430\u043b\u0430\u043d\u0441\u0430 \u043a\u0430\u0436\u0434\u043e\u0435 28\u043e\u0435 \u0447\u0438\u0441\u043b\u043e\n user_data_query = 'SELECT tg_id, tariff_id, id FROM client WHERE tg_id != \"0\"'\n res_user_data_query_table = execute_select_query(\n user_data_query).split('__next_item__')\n for i in range(len(res_user_data_query_table)):\n row = res_user_data_query_table[i].split('__next_column__')\n if row[0] != '':\n row = {\n 'tg_id': row[0],\n 'tariff_id': row[1],\n 'id': row[2]\n }\n res_user_data_query_table[i] = row\n for item in res_user_data_query_table:\n if isinstance(item, dict):\n try:\n balance = check_balance(item)\n monthly_query = 'SELECT monthly FROM ip_tariff WHERE id = ' + \\\n '\"' + item.get('tariff_id') + '\"'\n res_monthly_query = execute_select_query(\n monthly_query).split('__next_item__')\n service_id_query = 'SELECT service_id FROM client_clientservice WHERE client_id = ' + \\\n '\"' + item.get('id') + '\"'\n res_service_id_query = execute_select_query(\n service_id_query).split('__next_item__')\n discount_services = ['11', '12', '13', '15', '16', '17', '18', '19', '20', '21', '22',\n '23', '24', '25', '31', '32', '33', '34', '37', '38', '39', '44', '45', '47', '48']\n if_discount_message = ''\n sum_services_price = 0.0\n for i in range(len(res_service_id_query)):\n if res_service_id_query[i] != '':\n service_price_query = 'SELECT price FROM clientservice WHERE id = ' + \\\n '\"' + res_service_id_query[i] + '\"'\n res_service_price_query = execute_select_query(\n service_price_query).split('__next_item__')\n if res_service_id_query[i] in discount_services:\n if_discount_message = '\u0410\u0431\u043e\u043d\u0435\u043d\u0442\u0441\u043a\u0430\u044f \u043f\u043b\u0430\u0442\u0430 \u0440\u0430\u0441\u0441\u0447\u0438\u0442\u044b\u0432\u0430\u0435\u0442\u0441\u044f \u0431\u0435\u0437 \u0443\u0447\u0435\u0442\u0430 \u0441\u043a\u0438\u0434\u043a\u0438.'\n sum_services_price += float(res_service_price_query[0])\n monthly = float(res_monthly_query[0]) + sum_services_price\n delta = monthly - balance\n note = '\u041d\u0430\u043f\u043e\u043c\u0438\u043d\u0430\u0435\u043c: 1\u043e\u0433\u043e \u0447\u0438\u0441\u043b\u0430 \u0441\u043f\u0438\u0448\u0435\u0442\u0441\u044f \u0430\u0431\u043e\u043d\u0435\u043d\u0442\u0441\u043a\u0430\u044f \u043f\u043b\u0430\u0442\u0430, \u0412\u0430\u043c \u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e \u0432\u043d\u0435\u0441\u0442\u0438 \u043d\u0430 \u0441\u0447\u0435\u0442 ' + str(delta) + \\\n ' \u0440\u0443\u0431. \u041f\u0440\u043e\u0438\u0437\u0432\u0435\u0441\u0442\u0438 \u043e\u043f\u043b\u0430\u0442\u0443 \u043c\u043e\u0436\u043d\u043e \u043d\u0430\u0436\u0430\u0432 \u043d\u0430 \u043a\u043d\u043e\u043f\u043a\u0443 \u041f\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u044c \u0431\u0430\u043b\u0430\u043d\u0441 \u0432 \u0433\u043b\u0430\u0432\u043d\u043e\u043c \u043c\u0435\u043d\u044e. ' + \\\n if_discount_message\n if delta < 0:\n note = '\u041d\u0430\u043f\u043e\u043c\u0438\u043d\u0430\u0435\u043c: 1\u043e\u0433\u043e \u0447\u0438\u0441\u043b\u0430 \u0441\u043f\u0438\u0448\u0435\u0442\u0441\u044f \u0430\u0431\u043e\u043d\u0435\u043d\u0442\u0441\u043a\u0430\u044f \u043f\u043b\u0430\u0442\u0430, \u043d\u0430 \u0432\u0430\u0448\u0435\u043c \u0441\u0447\u0435\u0442\u0435 \u0434\u043e\u0441\u0442\u0430\u0442\u043e\u0447\u043d\u043e \u0441\u0440\u0435\u0434\u0442\u0432 \u0434\u043b\u044f \u043e\u043f\u043b\u0430\u0442\u044b \u043d\u0430\u0448\u0438\u0445 \u0443\u0441\u043b\u0443\u0433, \u0441\u043f\u0430\u0441\u0438\u0431\u043e!'\n bot.send_message(item.get('tg_id'), note)\n except telebot.apihelper.ApiTelegramException:\n print('no_chat with ', item.get('tg_id'))\n\nschedule.every(10).seconds.do(send_notification)\n\nclass ScheduleMessage():\n def try_send_schedule(): # \u0411\u0435\u0441\u043a\u043e\u043d\u0435\u0447\u043d\u044b\u0439 \u0446\u0438\u043a\u043b \u0434\u043b\u044f \u0448\u0435\u0434\u0443\u043b\u043b\u0435\u0440\u0430\n while True:\n schedule.run_pending()\n time.sleep(1)\n\n def start_process(): # \u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435 \u0438 \u0437\u0430\u043f\u0443\u0441\u043a \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u0430 \u0448\u0435\u0434\u0443\u043b\u043b\u0435\u0440\u0430\n p1 = Process(target=ScheduleMessage.try_send_schedule, args=())\n p1.start()\n\n\nbot.remove_webhook()\ntime.sleep(0.15)\n\nbot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH,\n certificate=open(WEBHOOK_SSL_CERT, 'r'))\n\n\nif __name__ == '__main__':\n ScheduleMessage.start_process()\n app.run(\n host=WEBHOOK_LISTEN,\n port=WEBHOOK_PORT,\n ssl_context=(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV),\n debug=False\n )\n\n\u041a\u043e\u043c\u0430\u043d\u0434\u0430 \u0437\u0430\u043f\u0443\u0441\u043a\u0430 gunicorn:\ngunicorn --bind my_ip:88 main:app --certfile=/path_to_cert/webhook_cert.pem --keyfile=/path_to_key/webhook_pkey.pem\n\nA: \u0412\u043e\u043f\u0440\u043e\u0441 \u0440\u0435\u0448\u0438\u043b\u0441\u044f \u043f\u0440\u043e\u0441\u0442\u043e. \u0412\u044b\u043d\u0435\u0441 \u0437\u0430\u043f\u0443\u0441\u043a \u043f\u0440\u043e\u0446\u0435\u0441\u0441\u0430 schedule \u0432 \u0442\u0435\u043b\u043e \u0431\u043e\u0442\u0430 \u0438\u0437 \u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0446\u0438\u0438 \u0437\u0430\u043f\u0443\u0441\u043a\u0430.\nScheduleMessage.start_process()\nif __name__ == '__main__':\n \n app.run(\n host=WEBHOOK_LISTEN,\n port=WEBHOOK_PORT,\n ssl_context=(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV),\n debug=False\n )\n\n", "meta": {"language": "ru", "url": "https://ru.stackoverflow.com/questions/1317135", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Apache reverse proxy to nodejs server on CentOS 7 (WHM) I'm trying to setup my site on the server. I've uploaded it and it's currently running on the server but the problem comes when I try to setup a reverse proxy on the domain so that I can access the site. I had followed the WHM documentation on how to do a reverse proxy and it worked but it also redirected the subdomains. Below is the tutorial i followed for modifying an individual virtual host.\nhttps://docs.cpanel.net/ea4/apache/modify-apache-virtual-hosts-with-include-files/\nIn short, I'd like to be able to access my site, example.com, without affecting my subdomains, webmail.example.com. Below is my conf file\n ServerName example.com\n ServerAlias www.example.com\n\n ProxyRequests Off\n \n Require all granted\n \n\n ProxyPass / http://127.0.0.1:3000/\n ProxyPassReverse / http://127.0.0.1:3000/\n\nAnd below is the default setting for the same virtual host I'm trying to change located in the httpd.conf file\n\n ServerName example.com\n ServerAlias mail.example.com www.example.com\n DocumentRoot /home/gusqooqw/public_html\n ServerAdmin webmaster@mtsd.co.za\n UseCanonicalName Off\n\n ## User gusqooqw # Needed for Cpanel::ApacheConf\n \n \n \n \n UserDir enabled gusqooqw\n \n \n \n \n\n # Enable backwards compatible Server Side Include expression parser for Apache versions >= 2.4.\n # To selectively use the newer Apache 2.4 expression parser, disable SSILegacyExprParser in\n # the user's .htaccess file. For more information, please read:\n # http://httpd.apache.org/docs/2.4/mod/mod_include.html#ssilegacyexprparser\n \n \n SSILegacyExprParser On\n \n \n\n\n\n \n suPHP_UserGroup gusqooqw gusqooqw\n \n \n \n SuexecUserGroup gusqooqw gusqooqw\n \n \n \n RMode config\n RUidGid gusqooqw gusqooqw\n \n \n # For more information on MPM ITK, please read:\n # http://mpm-itk.sesse.net/\n AssignUserID gusqooqw gusqooqw\n \n \n PassengerUser gusqooqw\n PassengerGroup gusqooqw\n \n\n \n ScriptAlias /cgi-bin/ /home/gusqooqw/public_html/cgi-bin/\n \n\n\n # Global DCV Rewrite Exclude\n \n RewriteOptions Inherit\n \n\n\n\n\n\n\n Include \"/etc/apache2/conf.d/userdata/std/2_4/gusqooqw/example.com/*.conf\"\n\n\n # To customize this VirtualHost use an include file at the following location\n # Include \"/etc/apache2/conf.d/userdata/std/2_4/gusqooqw/example.com/*.conf\"\n\n\nAnd below is the default webmail virtual host found in httpd.conf\n\n ServerName mtsd.co.za\n ServerAlias mail.mtsd.co.za www.mtsd.co.za cpcalendars.mtsd.co.za webdisk.mtsd.co.za webmail.mtsd.co.za cpcontacts.mtsd.co.za cpanel.mtsd.co.za\n DocumentRoot /home/gusqooqw/public_html\n ServerAdmin webmaster@mtsd.co.za\n UseCanonicalName Off\n\n ## User gusqooqw # Needed for Cpanel::ApacheConf\n \n \n \n \n UserDir enabled gusqooqw\n \n \n \n \n\n # Enable backwards compatible Server Side Include expression parser for Apache versions >= 2.4.\n # To selectively use the newer Apache 2.4 expression parser, disable SSILegacyExprParser in\n # the user's .htaccess file. For more information, please read:\n # http://httpd.apache.org/docs/2.4/mod/mod_include.html#ssilegacyexprparser\n \n \n SSILegacyExprParser On\n \n \n\n\n \n \n SecRuleEngine Off\n \n \n IfModule mod_suphp.c>\n suPHP_UserGroup gusqooqw gusqooqw\n \n \n \n SuexecUserGroup gusqooqw gusqooqw\n \n \n \n RMode config\n RUidGid gusqooqw gusqooqw\n \n \n # For more information on MPM ITK, please read:\n # http://mpm-itk.sesse.net/\n AssignUserID gusqooqw gusqooqw\n \n \n PassengerUser gusqooqw\n PassengerGroup gusqooqw\n \n\n \n ScriptAlias /cgi-bin/ /home/gusqooqw/public_html/cgi-bin/\n \n \n SSLEngine on\n\n SSLCertificateFile /var/cpanel/ssl/apache_tls/mtsd.co.za/combined\n\n SetEnvIf User-Agent \".*MSIE.*\" nokeepalive ssl-unclean-shutdown\n \n SSLOptions +StdEnvVars\n \n \n\n\n\n\n\n Include \"/etc/apache2/conf.d/userdata/ssl/2_4/gusqooqw/mtsd.co.za/*.conf\"\n\n\n\n\n # To customize this VirtualHost use an include file at the following location\n # Include \"/etc/apache2/conf.d/userdata/ssl/2_4/gusqooqw/mtsd.co.za/*.conf\"\n\n \n RequestHeader set X-HTTPS 1\n \n\n RewriteEngine On\n RewriteCond %{HTTP_HOST} =cpanel.mtsd.co.za [OR]\n RewriteCond %{HTTP_HOST} =cpanel.mtsd.co.za:443\n RewriteCond %{HTTP:Upgrade} !websocket [nocase]\n\n RewriteRule ^/(.*) /___proxy_subdomain_cpanel/$1 [PT]\n ProxyPass \"/___proxy_subdomain_cpanel\" \"http://127.0.0.1:2082\" max=1 retry=0\n RewriteCond %{HTTP_HOST} =cpcalendars.mtsd.co.za [OR]\n RewriteCond %{HTTP_HOST} =cpcalendars.mtsd.co.za:443\n RewriteCond %{HTTP:Upgrade} !websocket [nocase]\n\n RewriteRule ^/(.*) /___proxy_subdomain_cpcalendars/$1 [PT]\n ProxyPass \"/___proxy_subdomain_cpcalendars\" \"http://127.0.0.1:2079\" max=1 retry=0\n RewriteCond %{HTTP_HOST} =cpcontacts.mtsd.co.za [OR]\n RewriteCond %{HTTP_HOST} =cpcontacts.mtsd.co.za:443\n RewriteCond %{HTTP:Upgrade} !websocket [nocase]\nRewriteRule ^/(.*) /___proxy_subdomain_cpcontacts/$1 [PT]\n ProxyPass \"/___proxy_subdomain_cpcontacts\" \"http://127.0.0.1:2079\" max=1 retry=0\n RewriteCond %{HTTP_HOST} =webdisk.mtsd.co.za [OR]\n RewriteCond %{HTTP_HOST} =webdisk.mtsd.co.za:443\n RewriteCond %{HTTP:Upgrade} !websocket [nocase]\n\n RewriteRule ^/(.*) /___proxy_subdomain_webdisk/$1 [PT]\n ProxyPass \"/___proxy_subdomain_webdisk\" \"http://127.0.0.1:2077\" max=1 retry=0\n RewriteCond %{HTTP_HOST} =webmail.mtsd.co.za [OR]\n RewriteCond %{HTTP_HOST} =webmail.mtsd.co.za:443\n RewriteCond %{HTTP:Upgrade} !websocket [nocase]\n\n RewriteRule ^/(.*) /___proxy_subdomain_webmail/$1 [PT]\n ProxyPass \"/___proxy_subdomain_webmail\" \"http://127.0.0.1:2095\" max=1 retry=0\n\n RewriteCond %{HTTP:Upgrade} websocket [nocase]\n RewriteCond %{HTTP_HOST} =cpanel.mtsd.co.za [OR]\n RewriteCond %{HTTP_HOST} =cpanel.mtsd.co.za:443\n\n RewriteRule ^/(.*) /___proxy_subdomain_ws_cpanel/$1 [PT]\n RewriteCond %{HTTP:Upgrade} websocket [nocase]\n RewriteCond %{HTTP_HOST} =webmail.mtsd.co.za [OR]\n RewriteCond %{HTTP_HOST} =webmail.mtsd.co.za:443\n\n RewriteRule ^/(.*) /___proxy_subdomain_ws_webmail/$1 [PT]\n\n\n\nA: So after having contacted the cpanel support, they could not answer why the method I used above wasnt working and they gave an alternative solution. I ended up using an interface called Application manager on Cpanel. It's the easiest way of installing a nodejs application on a cpanel server. Below is the documentation on how to use it to run yourr application\nhttps://docs.cpanel.net/knowledge-base/web-services/how-to-install-a-node.js-application/ \nHope this helps someone\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/61922650", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How i can define schema for array using jsonloader? I am using elephantbird project to load a json file to pig.\nBut i am not sure how i can define the schema at load. Did not find a description about the same.\ndata:\n{\"id\":22522,\"name\":\"Product1\",\"colors\":[\"Red\",\"Blue\"],\"sizes\":[\"S\",\"M\"]}\n{\"id\":22523,\"name\":\"Product2\",\"colors\":[\"White\",\"Blue\"],\"sizes\":[\"M\"]}\n\ncode:\nfeed = LOAD '$INPUT' USING com.twitter.elephantbird.pig.load.JsonLoader() AS products_json;\n\nextracted_products = FOREACH feed GENERATE\n products_json#'id' AS id,\n products_json#'name' AS name,\n products_json#'colors' AS colors,\n products_json#'sizes' AS sizes;\n\ndescribe extracted_products;\n\nresult:\nextracted_products: {id: chararray,name: bytearray,colors: bytearray,sizes: bytearray}\n\nhow i can give the correct schema to them (int,string,array,array) and how can i flatten array elements into rows?\nthanks in advance\n\nA: to convert json array to tuple:\nfeed = LOAD '$INPUT' USING com.twitter.elephantbird.pig.load.JsonLoader() AS products_json;\n\nextracted_products = FOREACH feed GENERATE\nproducts_json#'id' AS id:chararray,\nproducts_json#'name' AS name:chararray,\nproducts_json#'colors' AS colors:{t:(i:chararray)},\nproducts_json#'sizes' AS sizes:{t:(i:chararray)};\n\nto flatten a tuple\nflattened = foreach extracted_products generate id,flatten(colors);\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/29500998", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to make a password reset request in wordpress I'm trying to use postman to make a post request to reset the password, to the wordpress site. Here is what query is obtained as a result: https://example.com/wp-login.php?action=lostpassword&user_login=User123 \nAnd in the end I get the answer: ERROR: Enter a username or email address. How to make a request correctly and is it even possible? \n\n\nA: I got it!\nWhat OP did wrong was sending the user_login value in Postman's Params instead of form-data or x-www-form-urlencoded.\nHere is the working Postman request\n\nBut that's not all.\nI am using Flutter for developing my mobile app and http package to send the request and the normal http.post() won't work. It only works with MultipartRequest for some reason.\nHere is the full working request for Flutter's http package.\nString url = \"https://www.yourdomain.com/wp-login.php?action=lostpassword\";\n\nMap headers = {\n 'Content-Type': 'multipart/form-data; charset=UTF-8',\n 'Accept': 'application/json',\n};\n\nMap body = {\n 'user_login': userLogin\n};\n\nvar request = http.MultipartRequest('POST', Uri.parse(url))\n ..fields.addAll(body)\n ..headers.addAll(headers);\n\nvar response = await request.send();\n\n// forgot password link redirect on success\nif ([\n 200,\n 302\n].contains(response.statusCode)) {\n return 'success';\n} else {\n print(response.statusCode);\n throw Exception('Failed to send. Please try again later.');\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/49360250", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Is there a library for showing long text in one single TextView with different formatting? E.g. similar looking to what apps like Fabulous are doing.\nMy use case it that I have a longer text stored online, which should then be retrieved and displayed. So I cannot style every single one with different TextViews and would like to have something with tags or so inside.\nMaybe something like that? But doesn't seem to be usable as a library.\n\nI have looked for something in the Android must have libraries but no results.\n\nA: I think I found something really close to what I wanted with this library: SRML: \"String Resource Markup Language\"\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/55171948", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Graphics.fillArc(); is not working properly I have written this java code for drawing a filled arc whose endpoint angle increases by 1 in each iteration of loop from 0 to 360 degrees, but this is not working properly so please help.\nimport java.awt.Color;\nimport java.awt.FlowLayout;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\n\n\n\npublic class A {\n\n public static void main(String arg[]) throws Exception {\n\n JFrame f = new JFrame();\n f.setExtendedState(JFrame.MAXIMIZED_BOTH);\n f.setUndecorated(true);\n f.setVisible(true);\n f.getContentPane().setBackground(Color.BLACK);\n f.setLayout(new FlowLayout());\n Circle c;\n\n for(int i=0; i<=360; i++) {\n c = new Circle(-i);\n f.add(c);\n Thread.sleep(6);\n f.getContentPane().remove(c);\n f.getContentPane().revalidate();\n f.getContentPane().repaint();\n }\n\n }\n}\n\nclass Circle extends JPanel {\n\n int angle;\n\n public Circle(int angle) {\n this.angle=angle;\n }\n\n public void paintComponent(Graphics g) {\n\n super.paintComponent(g);\n g.setColor(Color.RED);\n g.fillArc(50, 50, 100, 100, 90, angle);\n }\n}\n\n\nA: I won't list all the errors that you have in your code. I fixed most of them.\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Graphics;\n\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.SwingUtilities;\n\npublic class Scratch {\n\n public static void main(String arg[]) throws Exception {\n\n JFrame f = new JFrame();\n f.setSize(600, 600);\n f.setVisible(true);\n f.getContentPane().setBackground(Color.BLACK);\n f.setLayout(new BorderLayout());\n\n for(int i=0; i<=360; i++) {\n final int fi = i;\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n f.getContentPane().removeAll();\n Circle c = new Circle(-fi);\n f.add(c);\n f.getContentPane().revalidate();\n f.getContentPane().repaint();\n }\n });\n try {\n Thread.sleep(100);\n } catch (InterruptedException ie) {\n }\n }\n\n }\n}\n\nclass Circle extends JPanel {\n\n int angle;\n\n public Circle(int angle) {\n this.angle=angle;\n }\n\n public void paintComponent(Graphics g) {\n\n super.paintComponent(g);\n g.setColor(Color.WHITE);\n g.fillRect(0, 0, getWidth(), getHeight());\n\n g.setColor(Color.RED);\n g.fillArc(50, 50, 100, 100, 0, angle);\n }\n}\n\nI recommend you to have one component that updates it's image rather than removing / adding different components.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/25310033", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Popup when a new message arrives I have a fully functioning messaging system on my website.\nI want to evolve this by having a box popup altering members when they have a new message.\nIt would say something like \"You have a new message, would you like to view?\".\nYou would be able to click Yes or No.\nHow would I go about doing this?\nNever tried anything like this before!\nThanks\nUPDATE. \nI am very inexperienced using the technologies required here. \nHow would I go about ensuring this works on every page?\nWhat code would I include?\nThis is something I need to improve on as it opens up so many more possibilities!\n\nA: You can have a looping AJAX call in the background that checks every few minutes. If the server returns a URL (or something distinguishable from \"no messages\") then you'll get the popup, and if they hit OK, are sent to the URL (using a basic confirm() dialog in Javascript).\nBe careful though, the users patience will wear thin if you munch their CPU power on this.\n\nA: You'd have to check regulary with the server if a new message is present for the user, using a timer in your javascript (so clientside code). Due to the nature of HTTP (it being stateless) it is not possible to push this notification from the server.\n\nA: You have 3 options:\n\n\n*\n\n*Show the message every time the user reloads the page. Easy and fast.\n\n*Show the message by sending AJAX requests to the server. Can be really bad when you have many users, so make sure the response take very little time.\n\n*Send the message from the server using WebSocket. Most up-to-date technology, but it's only supported in a few browsers, so check the compatibility issues before implementing it.\n\n\nI'd personally use #1, if I don't need instant user reaction. #2 is good for web chatting. #3 is universal, but rarely used yet.\nNormally you would have an AJAX script in the background, running with long timeout (30+ seconds), and functionality that shows the message after page reload. This combines #1 and #2.\n\nA: Firstly you should look at the following:\nhttp://stanlemon.net/projects/jgrowl.html\nyou should load jQuery + jGrowl and create a heartbeat function which polls the server every X seconds like.\nWhen the server receives a request from the JavaScript you check the database for the latest messages marked un_notified (not read)\nYou compile a list and mark them notified, and then send the list to the JavaScript again, this in turn gets passed to jGrowl and notifications are show,\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/4575944", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: racket postfix to prefix I have a series of expressions to convert from postfix to prefix and I thought that I would try to write a program to do it for me in DrRacket. I am getting stuck with some of the more complex ones such as (10 (1 2 3 +) ^).\nI have the very simple case down for (1 2 \\*) \u2192 (\\* 1 2). I have set these expressions up as a list and I know that you have to use cdr/car and recursion to do it but that is where I get stuck.\nMy inputs will be something along the lines of '(1 2 +).\nI have for simple things such as '(1 2 +):\n(define ans '())\n(define (post-pre lst)\n (set! ans (list (last lst) (first lst) (second lst))))\n\nFor the more complex stuff I have this (which fails to work correctly):\n(define ans '())\n(define (post-pre-comp lst)\n (cond [(pair? (car lst)) (post-pre-comp (car lst))]\n [(pair? (cdr lst)) (post-pre-comp (cdr lst))]\n [else (set! ans (list (last lst) (first lst) (second lst)))]))\n\nObviously I am getting tripped up because (cdr lst) will return a pair most of the time. I'm guessing my structure of the else statement is wrong and I need it to be cons instead of list, but I'm not sure how to get that to work properly in this case.\n\nA: Were you thinking of something like this?\n(define (pp sxp)\n (cond\n ((null? sxp) sxp)\n ((list? sxp) (let-values (((args op) (split-at-right sxp 1)))\n (cons (car op) (map pp args))))\n (else sxp)))\n\nthen\n> (pp '(1 2 *))\n'(* 1 2)\n> (pp '(10 (1 2 3 +) ^))\n'(^ 10 (+ 1 2 3))\n\n\nA: Try something like this:\n(define (postfix->prefix expr)\n (cond\n [(and (list? expr) (not (null? expr)))\n (define op (last expr))\n (define args (drop-right expr 1))\n (cons op (map postfix->prefix args))]\n [else expr]))\n\nThis operates on the structure recursively by using map to call itself on the arguments to each call.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/27346338", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: OpenSSL::SSL::SSLError at /auth/facebook/callback with omniauth I'm dealing with the OpenSLL error on windows, using omniauth.\nI've tried specifying the cacert.pem file. It is placed in my_app_dir\\assets\\cacert.pem (downloaded from the curl website), and\nprovider :facebook, APP_ID, SECRET, {:client_options => {:ssl => {:ca_file => File.dirname(__FILE__) << \"assets\\cacert.pem\"}}}\n\ndoes not work. I still get the OpenSSL Error. I decided that I don't need my windows machine to verify as I will be deploying to a linux server anyway, so for now I wanted to set it to not verify at all:\nSCOPE = 'email,read_stream'\n\nAPP_ID = \"2XXXXXXXXXXXXX\"\nSECRET = \"4XXXXXXXXXXXXXXXXXXXXXXX\"\n\nuse OmniAuth::Builder do\n provider :facebook, APP_ID, SECRET, {:client_options => {:ssl => {:verify => false}}}\nend\n\nI still get the error.\nAt this point, I don't really care whether or not it uses a certificate (I would prefer it do), I need to get it to work so that I can get past this roadblock.\nThe specific error says:\nSSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed\n\nWhat can I do to fix this?\n\nA: Try following the instructions given in this link:\nhttp://jimneath.org/2011/10/19/ruby-ssl-certificate-verify-failed.html\nAnd you have to make this minor change in fix_ssl.rb at the end:\nself.ca_file = Rails.root.join('lib/ca-bundle.crt').to_s\n\nI hope this helps.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/9969661", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Login working in localhost but error \"secret option required for sessions\" when deployed in Heroku My authentification works properly on localhost but gives me error 500 when deployed on Heroku.\nError: \n{\"type\":\"error\",\"error\":{\"message\":\"secret option required for sessions\"}}\n\nI have my secret session on a .env file that is ignored by .gitignore when pushing (maybe I should change that?)\nHeroku Logs:\n2019-10-23T17:22:22.682593+00:00 heroku[router]: at=info method=GET path=\"/manifest.json\" host=apppack-demo.herokuapp.com request_id=bb235945-cb82-4168-91ce-fd19d2109801 fwd=\"85.240.87.39\" dyno=web.1 connect=0ms service=2ms status=304 bytes=237 protocol=https\n2019-10-23T17:22:22.793594+00:00 heroku[router]: at=info method=GET path=\"/logo192.png\" host=apppack-demo.herokuapp.com request_id=8a1d2243-45c9-4919-b2ad-3ee8f9148d9c fwd=\"85.240.87.39\" dyno=web.1 connect=0ms service=2ms status=304 bytes=238 protocol=https\n2019-10-23T17:22:35.594349+00:00 heroku[router]: at=info method=POST path=\"/api/signup\" host=apppack-demo.herokuapp.com request_id=43907374-4de3-4658-92ce-9188f03e1624 fwd=\"85.240.87.39\" dyno=web.1 connect=0ms service=3ms status=500 bytes=300 protocol=https\n2019-10-23T17:22:35.592607+00:00 app[web.1]: POST /api/signup 500 1.206 ms - 74\n\n\nA: I recently had this issue with my app. \nI was getting the 'Error: secret option required for sessions' ONLY when deployed to Heroku.\nHere is what my code looked like originally:\napp.use(session({\n secret: process.env.SESSION_SECRET, \n resave: false, \n saveUninitialized: false\n}))\n\nWhen I deployed to Heroku it kept giving me an \"Internal server error\". Once checking the logs, it showed me 'Error: secret option required for sessions'.\nHere is how I fixed it:\napp.use(session({\n secret: 'secretidhere', \n resave: false, \n saveUninitialized: false\n}))\n\nSince my .env file wasn't viewable and that's where I had my secret code, it was giving me that error. Now, just by putting an arbitrary string 'secretidhere', I deployed to heroku again and it worked!\n** However, please note that this should not be a permanent solution. As the poster above states, you should have a config file in your root directory, or another method so this session stays secret. \nHope this helps!\n\nA: I was facing the same issue while I was deploying my code into AWS Elastic BeanStalk.\nIn .env we could have -\nsecret='my_secret'\n\nWhile in server.js:\napp.use(cookieParser())\napp.use(session({\n resave:true,\n saveUninitialized:true,\n secret:process.env.secret,\n cookie:{maxAge:3600000*24}\n}))\n\nThe solution turned out to be adding secret to the environments in there. Just add it to your enviroments for production, be it heroku or AWS.\n\nA: Have you added your secret session from your .env file to heroku config? Since your .env is in your .gitignore it will not be pushed up to heroku. Your code is looking for a string from your process.env but the heroku environment does not have it yet.\nYou have two solutions\n\n\n*\n\n*Go to your app console and click on settings. Once you are there, click on the box that says reveal config vars and add your secret there.\n\n\nor\n\n\n*In the root directory of your project you can set your config vars there using the command \n\n\nheroku config:set SECRET_SESSION=\"secretName\"\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/58528070", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "4"}} {"text": "Q: java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" I receive this error when I try to deploy my war on Wildfly 10.1.0.Final (I cannot change wildfly version)\n18:53:58,467 WARN [org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext] (ServerService Thread Pool -- 78) Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type\n18:53:58,493 INFO [org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener] (ServerService Thread Pool -- 78)\n\nError starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.\n18:53:58,536 ERROR [org.springframework.boot.SpringApplication] (ServerService Thread Pool -- 78) Application run failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type\n at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:628)\n at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)\n at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)\n at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)\n at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)\n at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)\n at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955)\n at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)\n at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)\n at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147)\n at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)\n at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)\n at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)\n at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:175)\n at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:155)\n at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:97)\n at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:174)\n at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:186)\n at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:171)\n at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)\n at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)\n at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)\n at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)\n at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)\n at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)\n at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)\n at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:234)\n at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:100)\n at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)\n at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)\n at java.util.concurrent.FutureTask.run(FutureTask.java:266)\n at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n at java.lang.Thread.run(Thread.java:748)\n at org.jboss.threads.JBossThread.run(JBossThread.java:320)\nCaused by: java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type\n at org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer.customize(UndertowWebServerFactoryCustomizer.java:81)\n at org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer.customize(UndertowWebServerFactoryCustomizer.java:59)\n at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.lambda$postProcessBeforeInitialization$0(WebServerFactoryCustomizerBeanPostProcessor.java:72)\n at org.springframework.boot.util.LambdaSafe$Callbacks.lambda$null$0(LambdaSafe.java:287)\n at org.springframework.boot.util.LambdaSafe$LambdaSafeCallback.invoke(LambdaSafe.java:159)\n at org.springframework.boot.util.LambdaSafe$Callbacks.lambda$invoke$1(LambdaSafe.java:286)\n at java.util.ArrayList.forEach(ArrayList.java:1257)\n at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1082)\n at org.springframework.boot.util.LambdaSafe$Callbacks.invoke(LambdaSafe.java:286)\n at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization(WebServerFactoryCustomizerBeanPostProcessor.java:72)\n at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization(WebServerFactoryCustomizerBeanPostProcessor.java:58)\n at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:440)\n at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796)\n at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)\n ... 34 more\n\n18:53:58,543 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 78) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host.\"/custom-crm-ticket-0.0.1-SNAPSHOT\": org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host.\"/custom-crm-ticket-0.0.1-SNAPSHOT\": java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type\n at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:85)\n at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)\n at java.util.concurrent.FutureTask.run(FutureTask.java:266)\n at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\n at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\n at java.lang.Thread.run(Thread.java:748)\n at org.jboss.threads.JBossThread.run(JBossThread.java:320)\nCaused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type\n at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:236)\n at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:100)\n at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)\n ... 6 more\nCaused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type\n at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:628)\n at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)\n at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)\n at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)\n at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)\n at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)\n at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955)\n at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)\n at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)\n at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147)\n at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)\n at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)\n at org.springframework.boot.SpringApplication.run(SpringApplication.java:308)\n at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:175)\n at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:155)\n at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:97)\n at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:174)\n at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:186)\n at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:171)\n at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)\n at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)\n at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)\n at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)\n at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)\n at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)\n at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)\n at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:234)\n ... 8 more\nCaused by: java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type\n at org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer.customize(UndertowWebServerFactoryCustomizer.java:81)\n at org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer.customize(UndertowWebServerFactoryCustomizer.java:59)\n at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.lambda$postProcessBeforeInitialization$0(WebServerFactoryCustomizerBeanPostProcessor.java:72)\n at org.springframework.boot.util.LambdaSafe$Callbacks.lambda$null$0(LambdaSafe.java:287)\n at org.springframework.boot.util.LambdaSafe$LambdaSafeCallback.invoke(LambdaSafe.java:159)\n at org.springframework.boot.util.LambdaSafe$Callbacks.lambda$invoke$1(LambdaSafe.java:286)\n at java.util.ArrayList.forEach(ArrayList.java:1257)\n at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1082)\n at org.springframework.boot.util.LambdaSafe$Callbacks.invoke(LambdaSafe.java:286)\n at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization(WebServerFactoryCustomizerBeanPostProcessor.java:72)\n at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization(WebServerFactoryCustomizerBeanPostProcessor.java:58)\n at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:440)\n at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796)\n at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)\n ... 34 more\n\n18:53:58,560 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 1) WFLYCTL0013: Operation (\"deploy\") failed - address: ([(\"deployment\" => \"custom-crm-ticket-0.0.1-SNAPSHOT.war\")]) - failure description: {\n \"WFLYCTL0080: Failed services\" => {\"jboss.undertow.deployment.default-server.default-host.\\\"/custom-crm-ticket-0.0.1-SNAPSHOT\\\"\" => \"org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host.\\\"/custom-crm-ticket-0.0.1-SNAPSHOT\\\": java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field \\\"MAX_HEADER_SIZE\\\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type\n Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field \\\"MAX_HEADER_SIZE\\\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type\n Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field \\\"MAX_HEADER_SIZE\\\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type\n Caused by: java.lang.LinkageError: loader constraint violation: when resolving field \\\"MAX_HEADER_SIZE\\\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type\"},\n \"WFLYCTL0412: Required services that are not installed:\" => [\"jboss.undertow.deployment.default-server.default-host.\\\"/custom-crm-ticket-0.0.1-SNAPSHOT\\\"\"],\n \"WFLYCTL0180: Services with missing/unavailable dependencies\" => undefined\n}\n18:53:58,665 INFO [org.jboss.as.server] (DeploymentScanner-threads - 1) WFLYSRV0010: Deployed \"custom-crm-ticket-0.0.1-SNAPSHOT.war\" (runtime-name : \"custom-crm-ticket-0.0.1-SNAPSHOT.war\")\n18:53:58,666 INFO [org.jboss.as.controller] (DeploymentScanner-threads - 1) WFLYCTL0183: Service status report\nWFLYCTL0186: Services which failed to start: service jboss.undertow.deployment.default-server.default-host.\"/custom-crm-ticket-0.0.1-SNAPSHOT\": org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host.\"/custom-crm-ticket-0.0.1-SNAPSHOT\": java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type\n\nThis is my pom\n\n\n 4.0.0\n \n org.springframework.boot\n spring-boot-starter-parent\n 2.7.2\n \n \n com.hpe.du\n custom-crm-ticket\n 0.0.1-SNAPSHOT\n war\n custom-crm-ticket\n custom ticketing\n \n 1.8\n \n \n \n org.springframework.boot\n spring-boot-starter-web\n \n \n org.springframework.boot\n spring-boot-starter-tomcat\n provided\n \n \n org.springframework.boot\n spring-boot-starter-test\n test\n \n \n org.projectlombok\n lombok\n 1.18.24\n provided\n \n \n org.json\n json\n 20220320\n \n \n javax.jms\n javax.jms-api\n 2.0.1\n \n \n javax.jms\n jms\n 1.1\n runtime\n \n \n org.wildfly\n wildfly-jms-client-bom\n 10.1.0.Final\n pom\n \n \n org.wildfly\n wildfly-naming-client\n 1.0.15.Final\n \n \n \n \n \n org.springframework.boot\n spring-boot-maven-plugin\n \n \n \n\n\nI tried also to change the pom as following\n\n org.wildfly\n wildfly-jms-client-bom\n 10.1.0.Final\n pom\n \n \n org.jboss.xnio\n xnio-api\n \n \n\n\n\n org.wildfly\n wildfly-naming-client\n 1.0.15.Final\n \n \n org.jboss.xnio\n xnio-api\n \n \n\n\nThe Error disappear, and the war deployed, but when I call the REST, I receive the error\n19:02:49,017 ERROR [stderr] (Thread-133) Exception in thread \"Thread-133\" java.lang.NoClassDefFoundError: org/xnio/Options\n19:02:49,021 ERROR [stderr] (Thread-133) at org.jboss.naming.remote.client.InitialContextFactory.(InitialContextFactory.java:92)\n19:02:49,022 ERROR [stderr] (Thread-133) at java.lang.Class.forName0(Native Method)\n19:02:49,025 ERROR [stderr] (Thread-133) at java.lang.Class.forName(Class.java:348)\n19:02:49,027 ERROR [stderr] (Thread-133) at org.jboss.as.naming.InitialContext.getDefaultInitCtx(InitialContext.java:113)\n19:02:49,032 ERROR [stderr] (Thread-133) at org.jboss.as.naming.InitialContext.init(InitialContext.java:99)\n19:02:49,034 ERROR [stderr] (Thread-133) at javax.naming.ldap.InitialLdapContext.(InitialLdapContext.java:154)\n19:02:49,046 ERROR [stderr] (Thread-133) at org.jboss.as.naming.InitialContext.(InitialContext.java:89)\n19:02:49,049 ERROR [stderr] (Thread-133) at org.jboss.as.naming.InitialContextFactory.getInitialContext(InitialContextFactory.java:43)\n19:02:49,060 ERROR [stderr] (Thread-133) at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)\n19:02:49,063 ERROR [stderr] (Thread-133) at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)\n19:02:49,064 ERROR [stderr] (Thread-133) at javax.naming.InitialContext.init(InitialContext.java:244)\n19:02:49,065 ERROR [stderr] (Thread-133) at javax.naming.InitialContext.(InitialContext.java:216)\n19:02:49,066 ERROR [stderr] (Thread-133) at com.hpe.du.customcrmticket.JMSUtils.customTTJMSCommunication.elaborateRequest(customTTJMSCommunication.java:100)\n19:02:49,066 ERROR [stderr] (Thread-133) at com.hpe.du.customcrmticket.customCrmTicketController.lambda$createTT$0(customCrmTicketController.java:36)\n19:02:49,067 ERROR [stderr] (Thread-133) at java.lang.Thread.run(Thread.java:748)\n19:02:49,072 ERROR [stderr] (Thread-133) Caused by: java.lang.ClassNotFoundException: org.xnio.Options from [Module \"deployment.custom-crm-ticket-0.0.1-SNAPSHOT.war:main\" from Service Module Loader]\n19:02:49,093 ERROR [stderr] (Thread-133) at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)\n19:02:49,094 ERROR [stderr] (Thread-133) at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)\n19:02:49,095 ERROR [stderr] (Thread-133) at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)\n19:02:49,096 ERROR [stderr] (Thread-133) at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)\n19:02:49,097 ERROR [stderr] (Thread-133) ... 15 more\n\nI don't understand why without exclusions there is this error, but with the exclusion it needs the dependecy\n\nA: I solved the problem in this way\nin pom.xml I excluded xnio-api (as in the question)\n\n org.wildfly\n wildfly-jms-client-bom\n 10.1.0.Final\n pom\n \n \n org.jboss.xnio\n xnio-api\n \n \n\n\n\n org.wildfly\n wildfly-naming-client\n 1.0.15.Final\n \n \n org.jboss.xnio\n xnio-api\n \n \n\n\nThen I created jboss-deployment-structure.xml under webapp/WEB-INF folder, with this content\n\n true\n \n \n \n \n \n\n\n\nnow the WAR is deployed with no problems\nHope this help\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/73337657", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: how to overwrite ScrollView content in ios or change focus I'm beginner in ios ....\nIn One of my activity I have created Custom scrollView and on it I have created Some custom textField ..Now when we click on textField then my custom tableView opens but this table mixup with already existing textField ....If I add this table on UIView then it does not scroll ......so how to overwrite on scroll view textField and scroll tabel with textField.....I Have Declared all table delegates and table appears properly but on scroll problem occur ....\nscrollview=[[UIScrollView alloc]initWithFrame:CGRectMake(0,60,320,540)];\n[scrollview setContentSize:CGSizeMake(800,1500)];\n\nscrollview.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);\nscrollview.autoresizesSubviews = YES;\n\nscrollview.scrollEnabled = YES;\nscrollview.delegate = self;\nscrollview.directionalLockEnabled = YES;\n\nscrollview.showsVerticalScrollIndicator = YES;\n\nscrollview.showsHorizontalScrollIndicator = YES;\n\nscrollview.autoresizesSubviews = YES;\nscrollview.backgroundColor=[UIColor whiteColor];\n[self.view addSubview:scrollview];\n\nAdviseDr=[[UITextField alloc]initWithFrame:CGRectMake(150,110,140,30)];\nAdviseDr.font = [UIFont boldSystemFontOfSize:15.0];\nAdviseDr.borderStyle = UITextBorderStyleLine;\nAdviseDr.clearButtonMode = UITextFieldViewModeWhileEditing; \nAdviseDr.delegate =self;\nAdviseDr.tag=1;\n[scrollview addSubview:AdviseDr];\n\ntable_AdviseDoctor=[[UITableView alloc]initwithframe:CGRectMake(150,200,170,200)style:UITableViewStylePlain]; \ntable_AdviseDoctor.delegate=self;\ntable_AdviseDoctor.dataSource=self;\ntable_AdviseDoctor.layer.borderWidth = 2.0;\ntable_AdviseDoctor.layer.borderColor = [UIColor grayColor].CGColor;\n[self.view addSubview:table_AdviseDoctor];\ntable_AdviseDoctor.hidden=YES;\nMedicalfacility=[[UITextField alloc]initWithFrame:CGRectMake(150,150,170,30)];\nMedicalfacility.font = [UIFont boldSystemFontOfSize:15.0];\nMedicalfacility.borderStyle = UITextBorderStyleLine;\nMedicalfacility.delegate =self;\nMedicalfacility.tag=2;\n[scrollview addSubview:Medicalfacility];\n[Medicalfacility addTarget:self action:@selector(btnpress1:)forControlEvents:UIControlEventEditingDidBegin];\n\n\nA: The Better option is that when you clicked on UITextField at that time also hide your UITextField so your UITextField is not mixup with your UITableView and when You remove/hide your UITableView at that time your hidden UITextField again unHide( give hidden = NO). Other wise there are many ways for solve your problem, i like this option so i suggest you.\nOther Option is.\nTake your UITableView in UIView, i hope that you have already know that UITableView have its own ScrollView so you not need to put in/over any scrollView.\nAnd when you click on UITextFiled that are in UIScrollView at that time you also put restriction that user can not do with UIScrollView and UITextField also \n(give userInteraction = NO). so also give (give userInteraction = YES) when your UITableView is hide.\n\nA: UserInteraction is right for but You know when we write this [self.view addsubview:Table_AdviseDoctor] then ....when we scroll already and then click on text field then my table open long below from required position then we write code UserInteraction.enable=No; then scroll not work this right but first scroll and then click on text filed then ..problem occur not right position .....\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/17424615", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: using array offsets to calculate delta in numpy I need to create delta and growth rate with a lot of data points. I'm new to numpy but I see it can do internal operations like this.\n(Pdb) data = np.array([11,22,33,44,10,3])\n(Pdb) data + data\narray([22, 44, 66, 88, 20, 6])\n\nIs it possible to add data offsets in numpy array operations? Like this delta calculation.\n(Pdb) [data[i] - data[i-2] for i in range(2,len(data))]\n[22, 22, -23, -41]\n\n(Pdb) [data[i] - data[i-1] for i in range(1,len(data))]\n[11, 11, 11, -34, -7]\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/63081854", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Is it possible to generate a signed certificate with an existing CA which has a different key pair? I create a signed certificate with an existing CA as I explained in this post: Bouncy Castle: Signed Certificate with an existing CA\nHowever, my generated certificate has the same public and private keys that the CA certificate.\nIs it possible to generate a certificate which has another key pair?\nI have tried the example code in the following post but my pdf signature is invalid: Generating X509 Certificate using Bouncy Castle Java\nI will appreciate any comment or information that can help me.\nThanks in advance.\n\nA: A public key certificate (PKC) will have the same key pair (public key) as the issuer only if the certificate is a self signed one. It's always possible for a CA to issue a certificate for another key-pair, in which case the new certificate will have the public key of the new key-pair and will be signed by the CA's private key. The subject of this new certificate can in turn be made a CA (through BasicConstraint extension and KeyUsage extension) in which case the new key-pair can be used to issue yet other certificates, thus creating a certificate path or chain. Please see the following code snippet.\npublic static X509Certificate getCertificte(X500Name subject,\n PublicKey subjectPublicKey,\n boolean isSubjectCA,\n X509Certificate caCertificate,\n PrivateKey caPrivateKey,\n String signingAlgorithm,\n Date validFrom,\n Date validTill) throws CertificateEncodingException {\n\nBigInteger sn = new BigInteger(64, random);\n\nX500Name issuerName = new X500Name(caCertificate.getSubjectDN().getName());\nSubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());\n\nX509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerName,\n sn,\n validFrom,\n validTill,\n subject,\n subjectPublicKeyInfo);\n\nJcaX509ExtensionUtils extensionUtil;\ntry {\n extensionUtil = new JcaX509ExtensionUtils();\n} catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(\"No provider found for SHA1 message-digest\");\n}\n\n// Add extensions\ntry {\n AuthorityKeyIdentifier authorityKeyIdentifier = extensionUtil.createAuthorityKeyIdentifier(caCertificate);\n certBuilder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier);\n\n SubjectKeyIdentifier subjectKeyIdentifier = extensionUtil.createSubjectKeyIdentifier(subjectPublicKey);\n certBuilder.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyIdentifier);\n\n BasicConstraints basicConstraints = new BasicConstraints(isSubjectCA);\n certBuilder.addExtension(Extension.basicConstraints, true, basicConstraints);\n} catch (CertIOException e) {\n throw new RuntimeException(\"Could not add one or more extension(s)\");\n}\n\nContentSigner contentSigner;\ntry {\n contentSigner = new JcaContentSignerBuilder(signingAlgorithm).build(caPrivateKey);\n} catch (OperatorCreationException e) {\n throw new RuntimeException(\"Could not generate certificate signer\", e);\n}\n\ntry {\n return new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner));\n } catch (CertificateException e) {\n throw new RuntimeException(\"could not generate certificate\", e);\n }\n}\n\nPlease note the arguments:\nsubjectPublicKey: public key corresponding to the new key-pair for which a new certificate will be issued. \ncaCertificate: CA certificate which corresponds to the key-pair of the current CA. \ncaPrivateKey: private key of the CA (private key corresponding to the caCertificate above). This will be used to sign the new certificate. \nisSubjectCA: a boolean indicating whether the new certificate holder (subject) will be acting as a CA.\nI have omitted keyUsage extensions for brevity, which should be used to indicate what all purposes the public key corresponding to the new cert should be used.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/51921657", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Is there a way to check if an element has a class in cypress.io? I don't want to test that it has the class like ...should('have.class', \"some-class\") I just want know if it does, and if doesn't then perform some action that gives it that class.\nBasically, I want to see if the element has Mui-checked and if it doesn't them programmatically check it.\n\nA: You can use the hasClass() jquery method for this:\ncy.get('selector').then(($ele) => {\n if ($ele.hasClass('foo')) {\n //Do something when you have the class\n } else {\n //Do something when you don't have the class\n }\n})\n\n\nA: Add the class like this. You don't need to check the condition since $el.addClass() works either way.\ncy.get('selector').then($el => $el.addClass(\"blue\"))\n\n\nA: You can retrieve the class attribute with should() and check that it contains your class, something like:\ncy.get('.selector')\n .should('have.attr', 'class')\n .and('contain', 'some-class');\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/71385871", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: BigQuery: DDL statement not executing via client API I am executing CREATE TABLE IF NOT EXIST via client API using following JobConfigurationQuery:\nqueryConfig.setUseLegacySql(false)\nqueryConfig.setFlattenResults(false)\nqueryConfig.setQuery(query)\n\nAs I am executing CREATE TABLE DDL, I cannot specify destination table, write dispositions, etc. In my Query History section of Web UI, I see job being executed successfully without any exceptions, and with no writes happening. Is DDL statement not supported via client API?\nI am using following client: \"com.google.apis\" % \"google-api-services-bigquery\" % \"v2-rev397-1.23.0\"\n\nA: From BigQuery docs which says it seems that no error is returned when table exists:\n\nThe CREATE TABLE IF NOT EXISTS DDL statement creates a table with the\n specified options only if the table name does not exist in the\n dataset. If the table name exists in the dataset, no error is\n returned, and no action is taken.\n\nAnswering your question, DDL is supported from API which is also stated in doc, to do this:\n\nCall the jobs.query method and supply the DDL statement in the request\n body's query property.\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/51551968", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Concurrency, Locking in SQL Server Database I have a requirement to Save/Update data in 15 tables. I have to ensure at the time of updation the concurrency and locking should be maintained, so that no dirty read happens. I am updating data using storeed procedure. What I can do in oredr to implement locking and concurrency?\n\nA: Other answers are assuming that you are already using a transaction. I won't omit this, since you might be missing it.\nYou should use a transaction to ensure that records in all 15 tables or none are inserted/updated. The transaction ensures you atomicity in your operation. If something fails during the stored procedure and you don't use a transaction, some of the save/update operations will be made, and some not (the ones from the query that has produced the error).\nIf you use BEGIN TRAN, and COMMIT for successful operations or ROLLBACK in case of failure, you will get all done or nothing. You should check for errors after each query execution, and call ROLLBACK TRANSACTION if there is one, or call COMMIT at the end of the stored procedure.\nThere is a good sample in the accepted answer of this Stackoverflow question on how to handle transaction inside a stored procedure. \nOnce you have the transaction, the second part is how to avoid dirty reads. You can set the isolation level of your database to READ COMMITED, this will prevent, by default, dirty reads on your data. But the user can still chose to do dirty reads by specifying WITH (NOLOCK) or READUNCOMMITED in his query. You cannot prevent that.\nBesides, there are the snapshot isolation levels (Snapshot and Read Commited Snapshot) that could prevent locking (which is not always good), avoiding dirty reads at the same time.\nThere is a lot of literature on this topic over the internet. If you are interested in snapshot isolation levels, I suggest you to read this great article from Kendra Little at Brent Ozar.\n\nA: You can't prevent that dirty read does not happen. Is the reader that does the dirty reads, not you (the writer). All you can do is ensure that your write is atomic, and that is accomplished by wrapping all writes in a single transaction. This way readers that do not issue dirty reads will see either all your updates, either none (atomic).\nIf a reader chooses to issue dirty reads there's nothing you can do about it.\nNote that changing your isolation level has no effect whatsoever on the reader's isolation level.\n\nA: All you need to do to ensure that the sql server isolation level is set appropriately. To eliminate dirty reads, it needs to be at Read Committed or higher, (Not at Read Uncommitted). Read Committed is the default setting out of the box. \nIt might be worth while, however, to review the link above and see what benefits, (and consequences) the higher settings provide.\n\nA: You can set the transaction isolation level to SERIALIZABLE. by using the following statement \nSET TRANSACTION ISOLATION LEVEL SERIALIZABLE; \n\nBefore you BEGIN TRANSACTION but Warning it can slow down other user who will be try to see on update or insert data into your tables, Your can also make use of the SNAP_SHOT Isolation Level which shows you only the last Commited/Saved data but it makes extensive use of Temp DB which can also effect the performance.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/19361525", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Highlighting when HTML and Xpath is given Given the HTML as a string, the Xpath and offsets. I need to highlight the word. \nIn the below case I need to highlight Child 1\nHTML text: \n\n \n

    Children

    Joe has three kids:
    \n \n \n\n\nXPATH as : /html/body/ul/li[1]/a[1]\nOffsets: 0,7\nRender - I am using react in my app.\nThe below is what I have done so far.\npublic render(){\n let htmlText = //The string above\n let doc = new DOMParser().parseFromString(htmlRender,'text/html');\n let ele = doc.evaluate(\"/html/body/ul/li[1]/a[1]\", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); //This gives the node itself\n let spanNode = document.createElement(\"span\");\n spanNode.className = \"highlight\";\n\n spanNode.appendChild(ele);\n // Wrapping the above node in a span class will add the highlights to that div\n //At this point I don't know how to append this span to the HTML String\n return(\n
    Display html data
    \n
    \n )\n\nI want to avoid using jquery. Want to do in Javascript(React too) if possible!\nEdit:\nSo if you notice the Render function it is using dangerouslySetHTML.\nMy problem is I am not able manipulate that string which is rendered. \n\nA: This is what I ended up doing.\npublic render(){\n let htmlText = //The string above\n let doc = new DOMParser().parseFromString(htmlRender,'text/html');\n let xpathNode = doc.evaluate(\"/html/body/ul/li[1]/a[1]\", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); \n const highlightedNode = xpathNode.singleNodeValue.innerText;\n const textValuePrev = highlightedNode.slice(0, char_start);\n const textValueAfter = highlightedNode.slice(char_end, highlightedNode.length);\n xpathNode.singleNodeValue.innerHTML = `${textValuePrev}\n \n ${highlightedNode.slice(char_start, char_end)}\n ${textValueAfter}`;\n return(\n
    Display html data
    \n
    \n )\n\n\nA: Xpath is inherently cross component, and React components shouldn't know much about each other. Xpath also basically requires all of the DOM to be created in order to query it. I would render your component first, then simply mutate the rendered output in the DOM using the Xpath selector.\nhttps://jsfiddle.net/69z2wepo/73860/\nvar HighlightXpath = React.createClass({\n componentDidMount() {\n let el = document.evaluate(this.props.xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);\n el.singleNodeValue.style.background = 'pink';\n },\n render: function() {\n return this.props.children;\n }\n});\n\nUsage:\n\n ... app ...\n\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/42869993", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "6"}} {"text": "Q: Setting up a Git repository for a .NET solution I have a solution with 15 C# projects and I'm trying to set up an efficient git repository for them. Should I create a repository on that level or for each project under the solution?\nWebServices/\n|- WebServices.sln\n|- WebService1/\n `- WebService1.csproj\n|- WebService2/\n `- WebService2.csproj\n\nThe solution has a project reference to ../framework/framework.csproj which is a seperate repository and all the other projects have a reference to. The projects under the solution are not linked in any way, but they all use the framework.\nI would like any changes to the framework would be passed to the projects.\nDo you have any guide for me how to achieve that in the best possible way?\n\nA: There is no one answer to how to set up your repository. It depend on your specific needs.\nSome questions you should ask yourself include:\n\n\n*\n\n*Are all projects going to be released and versioned separately?\n\n*Are the projects really independent of each other?\n\n*How is your development team structured? Do individual developers stick to a single project?\n\n*Is your framework project stable?\n\n*Does your build process build each project separately?\n\n\nAssuming that the answers to all of the above is \"yes\", then I would set it up like so:\n\n\n*\n\n*Continue maintaining the framework code in its own repository, and publish it to an internal server using NuGet (as suggested in ssube's comment).\n\n*Create a separate repository for each project, each with their own solution file.\n\n\nIf you can say \"yes\" to all except #5 (and possibly #1), above, then I would add one more repository that consists of submodules of each of the individual projects and a global solution file that your build server can use. If you add a new project, you have to remember to also update this repository!\nIf you have to say \"no\" to #2, then just build a single repository.\nIf you have to say \"no\" to #3, then you'll have to make a judgement call, between separation of the code and developers' need to switch between repos. You could create a separate repository including submodules, but if all your developers wind up using that repo, you are really only introducing new maintenance with little gain.\nIf your framework is not stable (#4), then you may want to include that as a submodule in any of these cases. I recommend that once it becomes stable, then you look into removing the submodule and switching to NuGet at that time.\n\nA: What i have done for such a situation was the following. Note that in my case there were 2-3 developers.\nSo i have 3 things in this:\n\n\n*\n\n*The empty project structure that i would like to replicate [OPTIONAL]\n\n*The common library projects\n\n*The actual end projects that use common library projects\n\n\n1) I just create my scaffold development directory structure and i am putting a .gitkeep file in each and everyone of them in order for git to include it. In this way when i want to setup myself in a new pc i just clone this and i have my empty development \"universe\" structure. Then i populate (git clone) with the projects i need.\n2) The common libraries project is just a normal repo.\n3) My end projects reference the common library projects. There are prons and cons about it and depends on your situation, but i what i gain is that i can change the common libraries either directly from the common library project, or from the end project which references it. In both ways i get the changes in git and commit normally and separately.\nIn your case i would have my empty structure and then do 2 separate clones. The framework project in the correct place and then the entire webservices repo.\nIts up to you if you want to have a separate repo for each web service or one for all. It depends on your person count and work flow.\nAlso do not forget a proper .gitignore Here: LINK\n\nA: If \n\n\n*\n\n*you really want to have all projects in the same solution\n\n*the common project \"Framework\" is in active development (and some modifications\nfor one project could break others...)\n\n\ni think you must have each WebService as a git project with his own copy of Framework project as submodule:\nWebServices/\n|- WebServices.sln\n|- WebService1/\n `|-.git \n |-WebService1.csproj\n |-Framework (as submodule)\n|- WebService2/\n `|-.git \n |-WebService2.csproj\\\n |-Framework (as submodule)\n\nThis way each WebService will use the Framework version that is compatible with. \n(of course you must be aware of git submodule workings... you could read for example this, specially the section \"Issues with Submodules\"!)\nImportant: with this configuration each deployed webservice must reference the Framework library with the actual version it is using!\n\nA: Depending on \"how independent\" development going to be for each of your projects you might consider two option.\n\n\n*\n\n*in case you are mostly working on entire solution - create one repo for entire solution\n\n*in case some projects are really independent , create separate repos for those projects and create solution file for each project aside project file, then use git submodules to reference those repos in the repo of the main solution, that make use of those projects.\nGit Submodules Tips\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/23414771", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "16"}} {"text": "Q: Does Akka Decider have access to the full failure scenario? New to Akka. Creating a new Scala class that extends SupervisorStrategy gives me the following template to work with:\nclass MySupervisorStrategy extends SupervisorStrategy {\n override def decider: Decider = ???\n\n override def handleChildTerminated(context: ActorContext, child: ActorRef,\n children: Iterable[ActorRef]): Unit = ???\n\n override def processFailure(context: ActorContext, restart: Boolean,\n child: ActorRef, cause: Throwable, stats: ChildRestartStats, children: Iterable[ChildRestartStats]): Unit = ???\n}\n\nI'm looking for a way to access:\n\n\n*\n\n*The Throwable/Exception that was thrown from the child actor\n\n*The child actor ActorRef that threw the exception\n\n*The message that was passed to the child actor that prompted the exception to be thrown\n\n\nI think the Decider (which is actually a PartialFunction[Throwable,Directive]) gets passed the Throwable whenever the child throws the exception, but I'm not seeing where I could get access to #2 and #3 from my list above. Any ideas?\n\nUpdate\nFrom the posted fiddle, it looks like a valid Decider is:\n{\n case ActorException(ref,t,\"stop\") =>\n println(s\"Received 'stop' from ${ref}\")\n Stop\n case ActorException(ref,t,\"restart\") =>\n println(s\"Received 'restart' from ${ref}\")\n Restart\n case ActorException(ref,t,\"resume\") =>\n println(s\"Received 'resume' from ${ref}\")\n Resume\n}\n\nAbove, I see all three:\n\n\n*\n\n*The exception that was thrown by the child\n\n*The child (ref) that threw the exception\n\n*The message that was sent to the child originally (that caused the exception to be thrown)\n\n\nIt looks like there's nothing in that Decider that needs to be defined inside that Supervisor class. I'd like to pull the Decider logic out into, say, MyDecider.scala and find a way to refactor the Supervisor so that its supervisorStrategy uses an instance of MyDecider, so maybe something similar to:\nclass Supervisor extends Actor {\n import akka.actor.OneForOneStrategy\n import akka.actor.SupervisorStrategy._\n import scala.concurrent.duration._\n\n var child: ActorRef = _\n\n override val supervisorStrategy =\n OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute, decider = myDecider)\n\n ...\n}\n\n\nA: For #2 you could access the sender \"if the strategy is declared inside the supervising actor\"\n\nIf the strategy is declared inside the supervising actor (as opposed to within a companion object) its decider has access to all internal state of the actor in a thread-safe fashion, including obtaining a reference to the currently failed child (available as the sender of the failure message).\n\nThe message is not made available so the only option is to catch your exception and throw a custom one with the message that was received. \nHere is a quick fiddle\nclass ActorSO extends Actor {\n\n def _receive: Receive = {\n case e =>\n println(e)\n throw new RuntimeException(e.toString)\n }\n\n final def receive = {\n case any => try {\n _receive(any)\n }\n catch {\n case t:Throwable => throw new ActorException(self,t,any)\n }\n\n }\n\n}\n\nUpdate\nA Decider is just a PartialFunction so you can pass it in the constructor.\nobject SupervisorActor {\n def props(decider: Decider) = Props(new SupervisorActor(decider))\n}\n\nclass SupervisorActor(decider: Decider) extends Actor {\n\n override val supervisorStrategy = OneForOneStrategy()(decider)\n\n override def receive: Receive = ???\n}\n\nclass MyDecider extends Decider {\n override def isDefinedAt(x: Throwable): Boolean = true\n\n override def apply(v1: Throwable): SupervisorStrategy.Directive = {\n case t:ActorException => Restart\n case notmatched => SupervisorStrategy.defaultDecider.apply(notmatched)\n }\n}\n\nobject Test {\n val myDecider: Decider = {\n case t:ActorException => Restart\n case notmatched => SupervisorStrategy.defaultDecider.apply(notmatched)\n }\n val myDecider2 = new MyDecider()\n val system = ActorSystem(\"stackoverflow\")\n val supervisor = system.actorOf(SupervisorActor.props(myDecider))\n val supervisor2 = system.actorOf(SupervisorActor.props(myDecider2))\n}\n\nBy doing so, you won't be able to access supervisor state like the ActorRef of the child that throw the exception via sender() (although we are including this in the ActorException)\nRegarding your original question of accessing from the supervisor the child message that cause the exception, you can see here (from akka 2.5.3) that the akka developers choose to not make it available for decision.\n final protected def handleFailure(f: Failed): Unit = {\n // \u00a1\u00a1\u00a1 currentMessage.message is the one that cause the exception !!!\n currentMessage = Envelope(f, f.child, system)\n getChildByRef(f.child) match {\n /*\n * only act upon the failure, if it comes from a currently known child;\n * the UID protects against reception of a Failed from a child which was\n * killed in preRestart and re-created in postRestart\n */\n case Some(stats) if stats.uid == f.uid \u21d2\n // \u00a1\u00a1\u00a1 currentMessage.message is not passed to the handleFailure !!!\n if (!actor.supervisorStrategy.handleFailure(this, f.child, f.cause, stats, getAllChildStats)) throw f.cause\n case Some(stats) \u21d2\n publish(Debug(self.path.toString, clazz(actor),\n \"dropping Failed(\" + f.cause + \") from old child \" + f.child + \" (uid=\" + stats.uid + \" != \" + f.uid + \")\"))\n case None \u21d2\n publish(Debug(self.path.toString, clazz(actor), \"dropping Failed(\" + f.cause + \") from unknown child \" + f.child))\n }\n }\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/50353738", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: How to install packages with conda into /usr/bin/python3 I have a package, that is only downloadable with conda. When I startup a shell and type which python3, I get /home/usr/miniconda3/bin/python. Then I do conda deactivate and my python3 is /usr/bin/python3. Is there any chance to install packages from conda, so that the python-interpreter in that location finds them?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/60789708", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Examples of continuous functions that are not homotopic to each other. Let $f,g:X \\to Y$ be continuous functions. Then, consider $F:X \\times I \\to Y$ defined as follows:$$F(x,t) = f(1-t)+gt$$\nHow does one check whether $F$ is continuous(w.r.t the product topology)?\nIs there any other way to define a homotopy between two functions?\nAs an example, take $f,g : \\mathbb{R} \\to \\mathbb{R}$ to be $f(x) = x, g(x) = sin(x)$. Then how does one PROVE that the homotopy map as defined above is continuous?\nMoreover, what are some examples of maps that are not homotopic?\n\nA: The identity map of the circle $\\rm{id}:S^1\\to S^1$ and a constant map on $S^1$ are continuous but not homotopic. This is due to a result by Heinz Hopf, from one point of view.\nIntuitively the unit circle is not contractible.\nBy the alluded to result, we can wrap the circle around itself as many times as we like, continuously, and get non-homotopic maps.\n\nThe homotopy you refer to is the straight line homotopy. There are plenty of others.\n\nA: Generally, this all comes down to a space being path connected. If the path the homotopy described is contained in the space then it will be continous. For example, if we want to see the circular sector of radii 1 and 2 is homotopic to the unit circumference, we might consider the following map:\n$$\nf(x)=\\frac{x}{||x||}\n$$\nIt normalizes every point of the sector. It is continous because $0$ is not contained in the sector, thus, it is a retraction into the unit sphere. We want to prove it is a deformation retract, so we can end our proof, concluding that the two sets have the same type of homotopy. We consider the following homotopy:\n$$\nH(x,t)=f(x)\u00b7t+x\u00b7(1-t)\n$$\nBecause of what I said earlier, one can check it is radial, making it thus continious (the sector is path connected).\n\nA: The homotopy you describe for maps to $\\mathbb{R}$ (or maybe $\\mathbb{R}^n$) is continuous because addition and multiplication on $\\mathbb{R}$ are continuous operations, along with the functions $f$ and $g$ being continuous.\nIn general, maps $f$ and $g$ are not homotopic if some $f(x)$ and $g(x)$ are in different path components (essentially using that if $f$ and $g$ were homotopic then so would be the compositions $\\{x\\} \\hookrightarrow X \\to Y$). This tells you for example that the identity of $\\mathbb{R} - 0$ is not homotopic to the map $x \\mapsto -x$.\nLooking at such compositions with maps $Z \\to X$ from other 'test' spaces $Z$ can often detect if $f$ and $g$ are not homotopic. For example looking at all maps $S^n \\to X$ composed with $f$ and $g$ is the same as looking at the maps $\\pi_n(X) \\to \\pi_n(Y)$ induced by $f$ and $g$.\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/4019258", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: how to show product SKU below product name only on product page I am using porto theme in magento 1.9. i want to display product SKU only on product page below product name. how can we add product SKU on product page.\n\nA: Edit file\napp/design/frontend/yourtheme/package/template/catalog/product/view.phtml\nif you want to add SKU then please add following code underneath of H1 tag (product name).\n

    productAttribute($_product, $_product->getSku(), 'sku') ?>

    \nTo remove the attribute from details section, comment out the line\ngetSku(); ?>\n", "meta": {"language": "en", "url": "https://magento.stackexchange.com/questions/324012", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: Map newlines in GHCi Simple question, but I can't seem to figure it out. I have a list, and I want to print out each element of it on its own line. I can do\nmap show [1..10]\n\nfor example, which will print out them all together, but with no newlines. My thought was to do map (putStrLn $ show) [1..10] but this won't work because I just get back an [IO()]. Any thoughts?\n\nA: Aren't these answers putting too much emphasis on IO? If you want to intersperse newlines the standard Prelude formula is :\n> unlines (map show [1..10])\n\"1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n10\\n\"\n\nThis is the thing you want written - newlines are characters not actions, after all. Once you have an expression for it, you can apply putStrLn or writeFile \"Numbers.txt\" directly to that. So the complete operation you want is something like this composition:\nputStrLn . unlines . map show\n\nIn ghci you'd have\n> (putStrLn . unlines . map show) [1,2,3]\n1\n2\n3\n\n\nA: Try this: mapM_ (putStrLn . show) [1..10]\n\nA: Here is my personal favourite monad command called sequence:\nsequence :: Monad m => [m a] -> m [a]\n\nTherefore you could totally try: \nsequence_ . map (putStrLn . show) $ [1..10]\n\nWhich is more wordy but it leads upto a function I find very nice (though not related to your question):\nsequence_ . intersperse (putStrLn \"\")\n\nMaybe an ugly way to do that but I thought it was cool.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/5149916", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Google Maps API Drawing Rectangle This is the meat of the code I am using and I am not getting errors, but I am not seeing the points that are in the area of the rectangle. Any help would be appreciated:\n`enter code here`/** @this {google.maps.Rectangle} */\nfunction showNewRect(event) {\n var ne = rectangle.getBounds().getNorthEast();\nvar sw = rectangle.getBounds().getSouthWest();\ngoogle.maps.event.addlistener(rectangle, \"bounds_changed\", function(){\n document.getElementById(\"map-selected\").innerHTML=rectangle.getBounds();\n var rectA = (ne*sw);\n })\n\n\n}\n\nfunction listSelected () {\nvar inside = $.map( sites, function ( s ) {\n var d;\n\n if ( ( (d = google.maps.geometry.poly.containsLocation( s.position )) <= rectA ) )\n return s.location + ' ('+(Math.round(d/100)/10)+' km)';\n $('#map-selected').html( inside.sort().join('') );\n\n});\n}\n\n\n google.maps.event.addListener(drawingManager, 'rectanglecomplete', function( rectangle ) {\n\n selectedArea = rectangle;\n listSelected();\n\n google.maps.event.addListener(rectangle, 'center_changed', listSelected);\n google.maps.event.addListener(rectangle, 'bounds_changed', listSelected);I am working with the Google maps API and I have a map I am drawing on with a rectangle. I need to have a user draw the rectangle, and on the map there will be predefined locations, that when the rectangle crosses the locations there will be details of each location put into a list. \n\nThis is an example:\nhttp://hmoodesigns.com/ksi/\nI have an example using the circle draw tool, which I can get to work fine, but the rectangle tool I have not been able to have this identify the points on the map. \nHow can I check for these points without having a predefined rectangle on the page? \nThanks, \n\nA: When the Rectangle has been drawn iterate over the locations and use the method contains() of the Rectangle's bounds to test if the LatLng's are within the bounds of the Rectangle\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/23618188", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}} {"text": "Q: PHP DomDocument appendChildNode where I have tags in the text I would like to append some text to a dom element as a child node.\nThe problem is that in the text I can have tags as , etc.\nActually, with this method:\nprivate function appendChildNode($dom_output, $cit_node, $nodeName, $nodeText)\n{\n if ($nodeText != null && $nodeText != \"\" ) {\n $node = $dom_output->createElement($nodeName);\n $node->appendChild($dom_output->createTextNode($nodeText));\n $cit_node->appendChild($node);\n return $node;\n }\n}\n\nWhen I have tags in the $nodeText, then the will be converted to <i> and so on.\nHow can I append this text by keeping the tags as they are?\nThank you.\n\nA: I managed to find the solution.\nThanks to this post: DOMDocument append already fixed html from string\nI did:\nprivate function appendChildNode($dom_output, $cit_node, $nodeName, $nodeText)\n{\n if ($nodeText != null && $nodeText != \"\" ) { \n $node = $dom_output->createElement($nodeName);\n $fragment = $dom_output->createDocumentFragment();\n $fragment->appendXML( $nodeText);\n $node->appendChild($fragment);\n $cit_node->appendChild($node);\n return $node;\n }\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/22009512", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Can I have different ESX hosts accessing the same LUN over different protocols? I currently have a cluster of two ESX 3.5U2 servers connected directly via FiberChannel to a NetApp 3020 cluster. These hosts mount four VMFS LUNs for virtual machine storage. Currently these LUNs are only made available via our FiberChannel initator in the Netapp configuration\nIf I were to add an ESXi host to the cluster for internal IT use can I:\n\n\n*\n\n*Make the same VMFS LUNs available via the iSCSI target on the Netapp\n\n*Connect this ESXi host to those LUNs via iSCSI\n\n*Do all of this while the existing two ESX hosts are connected to those LUNs via FiberChannel\n\n\nDoes anyone have experience with this type of mixed protocol environment, specifically with Netapp?\n\nA: As long as the Netapp can present a LUN to both the fibre channel and iSCSI interfaces at the same time it shouldn't be a problem. However to do this the ESXi host would need to be a member of the cluster that the other two machines are members of, otherwise the volume will become corrupt.\n\nA: First you should note that ESXi cannot be part of a Cluster, in fact it can't be managed from VirtucalCenter/vSphere without paying for the licensing. \nThat being said. Once you have it part of the cluster, You will need to make sure that your SAN is presenting the LUN with the same ID (most do but some don't). If it isn't you need to resignature your LUN. See VMWare Documentation for help\nIf you cannot get the licensing, you will need to give it it's own storage.\nEdit: Clarified what i was saying as to ESXi not being able to be managed by VC/vSphere\n", "meta": {"language": "en", "url": "https://serverfault.com/questions/32318", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to type \"line1\", \"line2\", \"line3\".... using for loop in python For example, I want to generate below output using a \"for\" loop, having the for loop automatically populate the number at the end of the word line:\nline1\nline2\nline3\nline4\nline5\nline6\nline7\n\n\nA: Here is how to do it with \"f-strings\" and the range() class object in a for loop:\nfor_loop_basic_demo.py:\n#!/usr/bin/python3\n\nEND_NUM = 7\nfor i in range(1, END_NUM + 1):\n print(f\"line{i}\")\n\nRun command:\n./for_loop_basic_demo.py\n\nOutput:\nline1\nline2\nline3\nline4\nline5\nline6\nline7\n\nGoing further: 3 ways to print\nThe 3 ways I'm aware of to print formatted strings in Python are:\n\n*\n\n*formatted string literals; AKA: \"f-strings\"\n\n*the str.format() method, or\n\n*the C printf()-like % operator\n\nHere are demo prints with all 3 of those techniques to show each one for you:\n#!/usr/bin/python3\n\nEND_NUM = 7\nfor i in range(1, END_NUM + 1):\n # 3 techniques to print:\n\n # 1. newest technique: formatted string literals; AKA: \"f-strings\"\n print(f\"line{i}\")\n\n # 2. newer technique: `str.format()` method\n print(\"line{}\".format(i))\n\n # 3. oldest, C-like \"printf\"-style `%` operator print method\n # (sometimes is still the best method, however!)\n print(\"line%i\" % i)\n\n print() # print just a newline char\n\nRun cmd and output:\neRCaGuy_hello_world/python$ ./for_loop_basic_demo.py \nline1\nline1\nline1\n\nline2\nline2\nline2\n\nline3\nline3\nline3\n\nline4\nline4\nline4\n\nline5\nline5\nline5\n\nline6\nline6\nline6\n\nline7\nline7\nline7\n\n\nReferences:\n\n*\n\n****** This is an excellent read, and I highly recommend you read and study it!: Python String Formatting Best Practices\n\n*Official Python documentation for all \"Built-in Functions\". Get used to referencing this: https://docs.python.org/3/library/functions.html\n\n*\n\n*The range() class in particular, which creates a range object which allows the above for loop iteration: https://docs.python.org/3/library/functions.html#func-range\n\nA: You can use f strings.\\\nn = 7\nfor i in range(1, n + 1):\n print(f\"line{i}\")\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/71376733", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-2"}} {"text": "Q: Getting Facebook Access Token from User Id and Facebook App Secret? I'm trying to understand how the facebook api works. The end goal is to be able to read the posts from a facebook page.\nIf someone has connected with my app on facebook can my c# application then get the posts from a public facebook page if it knows their facebook account id (and has the facebook app secret hard coded).\nIf so what are the http requests it needs to make in order to get the access token which can then be used to get the posts, and what are the requests to get a new access token before one expires?\nIf you could provide an example in c# (maybe using the acebooksdk.net library) that would be great!\nThanks.\n\nA: The way to do it was using \"The Login Flow for Web (without JavaScript SDK)\" api to get a user access token. A user access token is required to be sent with graph api queries in order to get page posts.\nThe first step is to create an app on facebook where you specify what information you want the program to be able to access via the graph api. The end user will then choose to accept these permissions later.\nThe program creates a web browser frame and navigates to https://www.facebook.com/dialog/oauth?client_id={app-id}&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token\nThe response type \"token\" means that when the (embedded) web browser is redirected to the redirect_uri the user access token will be added to the end of the url as a fragment. E.g the browser would end up on the page with url https://www.facebook.com/connect/login_success.html#access_token=ACCESS_TOKEN...\nThe redirect uri can be anything but facebook has that specific one set aside for this scenario where you are not hosting another server which you want to receive and process the response.\nBasically facebook gathers all the information required from the user and then sends them to the redirect_uri. Some information they may require is for them to login and accept permissions your app on facebook requires.\nSo the program simply keeps an eye on what url the embedded browser is on and when it matches the redirect_uri it parses the url which will contain the data as fragments and can then close the browser. \n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/18196667", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "5"}} {"text": "Q: \"Call to undefined method PHPUnit\\Framework\\TestSuite::sortId()\" Error while executing Test Case with Coverage \nCall to undefined method PHPUnit\\Framework\\TestSuite::sortId()\n\nGetting this error while trying to execute test case with coverage.\nCommand:\nphpunit -v --debug ./Test.php --coverage-clover ../clover.xml\n\nPutput: (first two lines)\nPHPUnit 9.5.4 by Sebastian Bergmann and contributors.\nRuntime: PHP 7.3.33-1+ubuntu21.10.1+deb.sury.org+1\n...\n\n\nA: It appears that you have different installations of PHPUnit mixed up.\nFor instance, you may have used Composer to install PHPUnit and have configured the autoloader generated by Composer as PHPUnit's bootstrap script but then you invoke PHPUnit using an executable other than vendor/bin/phpunit.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/70389249", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Retrieving data from PostgresQL database with millions of rows takes very long I've been working on a system where users can register as an user, create a book club and invite other people (members) to join. The user and member can all add books to the club, and also vote for books that other members have added. I recently tried to add a lot of data to check if the database is performing well, after which I found out that it takes a lot of time to actually get the data I like. I would like to get all books in a club, including their votes and the name of the members that have voted for it.\nMy database diagram (created via dbdiagram.io, check it out)\n\nIn order to freely query the database without too much hassle, I decided to use Hasura, an open source service that can create a GraphQL backend by just looking at the data structure (I am using PostgresQL). I Use the following query to get the data I want:\nquery GetBooksOfClubIncludingVotesAndMemberName {\n books(\n where: {\n club_id: {_eq: \"3\"}, \n state:{_eq: 0 }\n }, \n order_by: [\n { fallback : asc },\n { id: asc }\n ]\n ) {\n id\n isbn\n state\n votes {\n member {\n id\n name\n }\n }\n } \n}\n\nThis query of course gets converted to a SQL statement\nSELECT\n coalesce(\n json_agg(\n \"root\"\n ORDER BY\n \"root.pg.fallback\" ASC NULLS LAST,\n \"root.pg.id\" ASC NULLS LAST\n ),\n '[]'\n ) AS \"root\"\nFROM\n (\n SELECT\n row_to_json(\n (\n SELECT\n \"_8_e\"\n FROM\n (\n SELECT\n \"_0_root.base\".\"id\" AS \"id\",\n \"_0_root.base\".\"isbn\" AS \"isbn\",\n \"_7_root.ar.root.votes\".\"votes\" AS \"votes\"\n ) AS \"_8_e\"\n )\n ) AS \"root\",\n \"_0_root.base\".\"id\" AS \"root.pg.id\",\n \"_0_root.base\".\"fallback\" AS \"root.pg.fallback\"\n FROM\n (\n SELECT\n *\n FROM\n \"public\".\"books\"\n WHERE\n (\n ((\"public\".\"books\".\"club_id\") = (('3') :: bigint))\n AND ((\"public\".\"books\".\"state\") = (('0') :: smallint))\n )\n ) AS \"_0_root.base\"\n LEFT OUTER JOIN LATERAL (\n SELECT\n coalesce(json_agg(\"votes\"), '[]') AS \"votes\"\n FROM\n (\n SELECT\n row_to_json(\n (\n SELECT\n \"_5_e\"\n FROM\n (\n SELECT\n \"_4_root.ar.root.votes.or.member\".\"member\" AS \"member\"\n ) AS \"_5_e\"\n )\n ) AS \"votes\"\n FROM\n (\n SELECT\n *\n FROM\n \"public\".\"votes\"\n WHERE\n ((\"_0_root.base\".\"id\") = (\"book_id\"))\n ) AS \"_1_root.ar.root.votes.base\"\n LEFT OUTER JOIN LATERAL (\n SELECT\n row_to_json(\n (\n SELECT\n \"_3_e\"\n FROM\n (\n SELECT\n \"_2_root.ar.root.votes.or.member.base\".\"id\" AS \"id\",\n \"_2_root.ar.root.votes.or.member.base\".\"name\" AS \"name\"\n ) AS \"_3_e\"\n )\n ) AS \"member\"\n FROM\n (\n SELECT\n *\n FROM\n \"public\".\"members\"\n WHERE\n (\n (\"_1_root.ar.root.votes.base\".\"member_id\") = (\"id\")\n )\n ) AS \"_2_root.ar.root.votes.or.member.base\"\n ) AS \"_4_root.ar.root.votes.or.member\" ON ('true')\n ) AS \"_6_root.ar.root.votes\"\n ) AS \"_7_root.ar.root.votes\" ON ('true')\n ORDER BY\n \"root.pg.fallback\" ASC NULLS LAST,\n \"root.pg.id\" ASC NULLS LAST\n ) AS \"_9_root\";\n\nWhen executing this statement using EXPLAIN ANALYZE in front of it, it tells me that it took approximately 9217 milliseconds to finish, check the analyze response below\n QUERY PLAN\n-------------------------------------------------------------------------------------------------------------------------------------------------------------\n Aggregate (cost=12057321.11..12057321.15 rows=1 width=32) (actual time=9151.967..9151.967 rows=1 loops=1)\n -> Sort (cost=12057312.92..12057313.38 rows=182 width=37) (actual time=9151.856..9151.865 rows=180 loops=1)\n Sort Key: books.fallback, books.id\n Sort Method: quicksort Memory: 72kB\n -> Nested Loop Left Join (cost=66041.02..12057306.09 rows=182 width=37) (actual time=301.721..9151.490 rows=180 loops=1)\n -> Index Scan using book_club on books (cost=0.43..37888.11 rows=182 width=42) (actual time=249.506..304.469 rows=180 loops=1)\n Index Cond: (club_id = '3'::bigint)\n Filter: (state = '0'::smallint)\n -> Aggregate (cost=66040.60..66040.64 rows=1 width=32) (actual time=49.134..49.134 rows=1 loops=180)\n -> Nested Loop Left Join (cost=0.72..66040.46 rows=3 width=32) (actual time=0.037..49.124 rows=3 loops=180)\n -> Index Only Scan using member_book on votes (cost=0.43..66021.32 rows=3 width=8) (actual time=0.024..49.104 rows=3 loops=180)\n Index Cond: (book_id = books.id)\n Heap Fetches: 540\n -> Index Scan using members_pkey on members (cost=0.29..6.38 rows=1 width=36) (actual time=0.005..0.005 rows=1 loops=540)\n Index Cond: (id = votes.member_id)\n SubPlan 2\n -> Result (cost=0.00..0.04 rows=1 width=32) (actual time=0.000..0.000 rows=1 loops=540)\n SubPlan 3\n -> Result (cost=0.00..0.04 rows=1 width=32) (actual time=0.000..0.000 rows=1 loops=540)\n SubPlan 1\n -> Result (cost=0.00..0.04 rows=1 width=32) (actual time=0.001..0.002 rows=1 loops=180)\n Planning Time: 0.788 ms\n JIT:\n Functions: 32\n Options: Inlining true, Optimization true, Expressions true, Deforming true\n Timing: Generation 4.614 ms, Inlining 52.818 ms, Optimization 113.442 ms, Emission 81.939 ms, Total 252.813 ms\n Execution Time: 9217.899 ms\n(27 rows)\n\nWith table sizes of:\n relname | rowcount\n--------------+----------\n books | 1153800\n members | 19230\n votes | 3461400\n clubs | 6410\n users | 3\n\nThis takes way too long. In my previous design, I did not have any indexes, which caused it to be even slower. I have added indexes, but I'm still not quite happy about the fact that I'll have to wait that long. Is there anything that I can improve concerning the data structure or anything?\nEDIT\nSame select statement, but now using EXPLAIN (ANALYZE, BUFFERS) as suggested:\n QUERY PLAN\n-------------------------------------------------------------------------------------------------------------------------------------------------------------\n Aggregate (cost=12057321.11..12057321.15 rows=1 width=32) (actual time=8896.202..8896.202 rows=1 loops=1)\n Buffers: shared hit=2392279 read=9470\n -> Sort (cost=12057312.92..12057313.38 rows=182 width=37) (actual time=8896.097..8896.106 rows=180 loops=1)\n Sort Key: books.fallback, books.id\n Sort Method: quicksort Memory: 72kB\n Buffers: shared hit=2392279 read=9470\n -> Nested Loop Left Join (cost=66041.02..12057306.09 rows=182 width=37) (actual time=222.978..8895.801 rows=180 loops=1)\n Buffers: shared hit=2392279 read=9470\n -> Index Scan using book_club on books (cost=0.43..37888.11 rows=182 width=42) (actual time=174.471..214.000 rows=180 loops=1)\n Index Cond: (club_id = '3'::bigint)\n Filter: (state = '0'::smallint)\n Buffers: shared hit=113 read=9470\n -> Aggregate (cost=66040.60..66040.64 rows=1 width=32) (actual time=48.211..48.211 rows=1 loops=180)\n Buffers: shared hit=2392166\n -> Nested Loop Left Join (cost=0.72..66040.46 rows=3 width=32) (actual time=0.028..48.202 rows=3 loops=180)\n Buffers: shared hit=2392166\n -> Index Only Scan using member_book on votes (cost=0.43..66021.32 rows=3 width=8) (actual time=0.018..48.187 rows=3 loops=180)\n Index Cond: (book_id = books.id)\n Heap Fetches: 540\n Buffers: shared hit=2390546\n -> Index Scan using members_pkey on members (cost=0.29..6.38 rows=1 width=36) (actual time=0.004..0.004 rows=1 loops=540)\n Index Cond: (id = votes.member_id)\n Buffers: shared hit=1620\n SubPlan 2\n -> Result (cost=0.00..0.04 rows=1 width=32) (actual time=0.000..0.000 rows=1 loops=540)\n SubPlan 3\n -> Result (cost=0.00..0.04 rows=1 width=32) (actual time=0.000..0.000 rows=1 loops=540)\n SubPlan 1\n -> Result (cost=0.00..0.04 rows=1 width=32) (actual time=0.008..0.008 rows=1 loops=180)\n Planning Time: 0.400 ms\n JIT:\n Functions: 32\n Options: Inlining true, Optimization true, Expressions true, Deforming true\n Timing: Generation 2.060 ms, Inlining 9.923 ms, Optimization 94.927 ms, Emission 68.793 ms, Total 175.702 ms\n Execution Time: 8898.360 ms\n(35 rows)\n\nEDIT 2:\nUsing select * from pg_prepared_xacts; and select * from pg_stat_activity; as suggested in an answer. The first statement does not show any rows, and for the second one I did not notice any old xact_start times, and this was done after previously (yesterday) running VACUUM FULL votes. Running VACUUM FULL votes unfortunately does not fix the problem.\nOutput of statements:\nbooky=# select * from pg_prepared_xacts;\n transaction | gid | prepared | owner | database\n-------------+-----+----------+-------+----------\n(0 rows)\n\nbooky=# select * from pg_stat_activity;\n datid | datname | pid | usesysid | usename | application_name | client_addr | client_hostname | client_port | backend_start | xact_start | query_start | state_change | wait_event_type | wait_event | state | backend_xid | backend_xmin | query | backend_type\n--------+---------+-----+----------+----------+------------------+-------------+-----------------+-------------+-------------------------------+-------------------------------+-------------------------------+-------------------------------+-----------------+---------------------+--------+-------------+--------------+---------------------------------+------------------------------\n | | 31 | | | | | | | 2020-04-05 08:41:47.959657+00 | | | | Activity | AutoVacuumMain | | | | | autovacuum launcher\n | | 33 | 10 | postgres | | | | | 2020-04-05 08:41:47.959964+00 | | | | Activity | LogicalLauncherMain | | | | | logical replication launcher\n 169575 | booky | 48 | 10 | postgres | psql | | | -1 | 2020-04-05 10:05:20.847798+00 | 2020-04-05 10:07:47.534381+00 | 2020-04-05 10:07:47.534381+00 | 2020-04-05 10:07:47.534382+00 | | | active | | 15265333 | select * from pg_stat_activity; | client backend\n | | 29 | | | | | | | 2020-04-05 08:41:47.959346+00 | | | | Activity | BgWriterHibernate | | | | | background writer\n | | 28 | | | | | | | 2020-04-05 08:41:47.959688+00 | | | | Activity | CheckpointerMain | | | | | checkpointer\n | | 30 | | | | | | | 2020-04-05 08:41:47.959501+00 | | | | Activity | WalWriterMain | | | | | walwriter\n(6 rows)\n\n\nA: -> Index Only Scan using member_book on votes (cost=0.43..66021.32 rows=3 width=8) (actual time=0.024..49.104 rows=3 loops=180)\n Index Cond: (book_id = books.id)\n Heap Fetches: 540\n\n49.104 * 180 = 8839, which is substantially all of your time. Most likely most of this time is going to IO to read random pages from the table (if you turn on track_io_timings and then do EXPLAIN (ANALYZE, BUFFERS) we would have a definitive answer to that).\nIf you vacuum \"votes\", and so get rid of the heap fetches, it would almost surely solve the problem. \n -> Index Only Scan using member_book on votes (cost=0.43..66021.32 rows=3 width=8) (actual time=0.018..48.187 rows=3 loops=180)\n Index Cond: (book_id = books.id)\n Heap Fetches: 540\n Buffers: shared hit=2390546\n\nIf this was done after the VACUUM was done, then you probably have some kind of long-running transaction being held open, which is preventing VACUUM from doing its job effectively. Also, hitting 2,390,546 buffers to get 540 row seems incredibly outlandish. Again, that could be due to some long-open transaction causing massive bloat in your index and/or table.\nDoes select * from pg_prepared_xacts; show any rows? Does select * from pg_stat_activity show any old times for xact_start? If neither of those, then can you do a VACUUM FULL votes and see if that fixes the problem?\n\nA: Thanks to @Lennart, I've added an INDEX which seems to have fixed the issue. It went from around 8900 milliseconds all the way to 35 milliseconds, which is awesome\nIndex to be created:\nCREATE INDEX IX1_VOTES ON VOTES (book_id, member_id)\n\n", "meta": {"language": "en", "url": "https://dba.stackexchange.com/questions/264321", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: python csv delimiter doesn't work properly I try to write a python code to extract DVDL values from the input. Here is the truncated input.\n A V E R A G E S O V E R 50000 S T E P S\n\n\n NSTEP = 50000 TIME(PS) = 300.000 TEMP(K) = 300.05 PRESS = -70.0\n Etot = -89575.9555 EKtot = 23331.1725 EPtot = -112907.1281\n BOND = 759.8213 ANGLE = 2120.6039 DIHED = 4231.4019\n 1-4 NB = 940.8403 1-4 EEL = 12588.1950 VDWAALS = 13690.9435\n EELEC = -147238.9339 EHBOND = 0.0000 RESTRAINT = 0.0000\n DV/DL = 13.0462 \n EKCMT = 10212.3016 VIRIAL = 10891.5181 VOLUME = 416404.8626\n Density = 0.9411\n Ewald error estimate: 0.6036E-04\n\n\n\n R M S F L U C T U A T I O N S\n\n\n NSTEP = 50000 TIME(PS) = 300.000 TEMP(K) = 1.49 PRESS = 129.9\nEtot = 727.7890 EKtot = 115.7534 EPtot = 718.8344\nBOND = 23.1328 ANGLE = 36.1180 DIHED = 19.9971\n1-4 NB = 12.7636 1-4 EEL = 37.3848 VDWAALS = 145.7213\nEELEC = 739.4128 EHBOND = 0.0000 RESTRAINT = 0.0000\nDV/DL = 3.7510\nEKCMT = 76.6138 VIRIAL = 1195.5824 VOLUME = 43181.7604\n Density = 0.0891\n Ewald error estimate: 0.4462E-04\n\nHere is the script. Basically we have a lot of DVDL in the input (not in the above truncated input) and we only want the last two. So we read all of them into a list and only get the last two. Finally, we write the last two DVDL in the list into a csv file. The desire output is \n13.0462, 3.7510\nHowever, the following script (python 2.7) will bring the output like this. Could any guru enlighten? Thanks.\n13.0462\"\"3.7510\"\"\nHere is the script:\nimport os\nimport csv\n\nDVDL=[]\nfilename=\"input.out\"\nfile=open(filename,'r')\n\nwith open(\"out.csv\",'wb') as outfile: # define output name\n line=file.readlines()\n for a in line:\n if ' DV/DL =' in a:\n DVDL.append(line[line.index(a)].split(' ')[1]) # Extract DVDL number\n\n print DVDL[-2:] # We only need the last two DVDL\n yeeha=\"\".join(str(a) for a in DVDL[-2:])\n print yeeha\n writer = csv.writer(outfile, delimiter=',',lineterminator='\\n')#Output the list into a csv file called \"outfile\"\n writer.writerows(yeeha)\n\n\nA: As the commenter who proposed an approach has not had the chance to outline some code for this, here's how I'd suggest doing it (edited to allow optionally signed floating point numbers with optional exponents, as suggested by an answer to Python regular expression that matches floating point numbers):\nimport re,sys\n\npat = re.compile(\"DV/DL += +([+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?)\")\nvalues = []\nfor line in open(\"input.out\",\"r\"):\n m = pat.search(line)\n if m:\n values.append(m.group(1))\noutfile = open(\"out.csv\",\"w\")\noutfile.write(\",\".join(values[-2:]))\n\nHaving run this script:\n$ cat out.csv\n13.0462,3.7510\n\nI haven't used the csv module in this case because it isn't really necessary for a simple output file like this. However, adding the following lines to the script will use csv to write the same data into out1.csv:\nimport csv\n\nwriter = csv.writer(open(\"out1.csv\",\"w\"))\nwriter.writerow(values[-2:])\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/26196007", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Perl (opendir): Receiving \"Can't use an undefined value as a symbol reference at line 46.\" I am trying to use opendir to open a directory. When ever this happens I get the error: \"Can't use an undefined value as a symbol reference at line.\" From searching other questions this usually originates from trying to use a variable that is out of scope. From all that I can tell my variable that I am using for my directory location is in scope and my handler for opendir is defined in the function like all examples. Please help me figure out what is going wrong. Line 46 where it is claiming the error is at is double starred.\nuse File::Find;\nuse File::Copy;\nuse File::Path;\n\nmy @imagelocations = ('/some/location1','/some/location2');\nmy $destination = '/some/location';\n\nforeach $a (@imagelocations)\n{\n find (\\&Move_Images, $a);\n}\n\nsub Move_Images\n{\n my $file = $_;\n if (-e $file && $File::Find::dir eq $a && $file ne \".\")\n {\n if (-M $file < 1)\n {\n my @folder = split(/_/, $file);\n my ($var1,$var2,$var3) = @folder[0,1,4];\n if (lc $var1 ne \"manual\" && lc $var1 ne \"test\")\n {\n if (-d ($File::Find::dir.'/'.$file))\n {\n $var3 = substr ($var3,1,-2);\n my $open = $File::Find::dir.\"/$file\";\n **opendir (my $dh, $open) or die \"Can't open directory $!\";**\n my @files = readdir($dh);\n ...\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/40621369", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to fix unexpected token in ESLint? I install ESLint globally using the command npm install -g eslint on my Mac. It was successful installing, but when I run eslint -v this is the issue I encounter:\n$ npm install -g eslint\npath/to/bin/eslint -> path/to/lib/node_modules/eslint/bin/eslint.js\n+ eslint@7.3.1\nadded 107 packages from 63 contributors in 4.823s\n\n$ eslint -v\npath/to/lib/node_modules/eslint/bin/eslint.js:93\n } catch {\n ^\n\nSyntaxError: Unexpected token {\n at createScript (vm.js:80:10)\n at Object.runInThisContext (vm.js:139:10)\n at Module._compile (module.js:617:28)\n at Object.Module._extensions..js (module.js:664:10)\n at Module.load (module.js:566:32)\n at tryModuleLoad (module.js:506:12)\n at Function.Module._load (module.js:498:3)\n at Function.Module.runMain (module.js:694:10)\n at startup (bootstrap_node.js:204:16)\n at bootstrap_node.js:625:3\n\nI would like to know what are the missing steps that cause this issue? I'm using Node.js v8.16.2 and NPM v6.4.1.\n\nA: The error happens because } catch { is a relatively recent (ES2019) language feature called \"optional catch binding\"; prior to its introduction, binding the caught error (e.g. } catch (err) {) was required syntactically. Per node.green, you need at least Node 10 to have that language feature.\nSo why does this happen in ESLint? Per e.g. the release blog, version 7 has dropped support for Node 8; they're no longer testing against that version and more modern language features will be assumed to be supported.\nTo fix it, either:\n\n*\n\n*Upgrade Node (Node 8 is out of LTS, which is why ESLint dropped support); or\n\n*npm install eslint@6 (with -g if you want to install globally) to use the older version of ESLint with Node 8 support.\n\n\nA: In case it's helpful for anyone, I had a slightly different twist on the other answer. In my case, the error was happening during the Travis CI build process and causing it to fail. The solution in my case was to update my .travis.yml file to node_js: \"16\"\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/62636329", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "14"}} {"text": "Q: IE11 emulates IE7 even though it's set to EDGE My website has the following settings:\n\nBut IE11 renders the page in IE7 mode:\n\nThis is on a machine with a fresh IE11 install, and it's the first time I'm visiting the website with the browser.\nAny idea what could be wrong?\n\nA: Does moving the X-UA-Compatible tag to be immediately underneath the tag make a difference?\nSee answer by neoswf:\nX-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode\nCheers,\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/23579763", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to create read-only user in pgAdmin 4? Creating a read-only user in pgAdmin 4 is a little tricky.\nHere is a guide on how I did it.\nFirst of all a few words about the process.\nThe whole process is based on editing a schema (very simple and safe) for your DB, so this creates limitations for using the method for all the DBs you have unless you edit schemas for each DB (again, it is easy).\nFirst, we have to open a main dialogue, select the target DB you need the read-only user for -> Schemas -> right mouse click on \"public\" schema -> Properties.\n\nIn the opened window go to \"Default privileges\" and click the \"+\" in the right corner.\n\n*\n\n*In the \"Grantee\" column enter: \"pg_read_all_data\",\n\n*in \"Privileges\" column click on the field and you will see options. Enable only \"Select\".\n\n\nOn the rest tabs (Sequences, Functions, Types) you can do the same (Select or Usage).\nHit \"Save\".\nIn the left sidebar scroll down and find \"Login/Group Roles\". Click right button -> Create -> Login/Group Role.\nOR if you have an existed user role you want to make read-only, click the right button on it and select \"Properties\".\nIn the opened window enter the name of the user, on the \"Definition\" tab enter a password, on the \"Previliges\" tab select \"Can login\" and \"Inherit rights from the parent roles?\"\nIn the \"Membership\" tab hit \"+\" in the \"Member of\" table and type \"pg_read_all_data\" into the \"User/Role\" column.\n\nIn the \"Parameters\" tab hit \"+\".\nSelect \"role\" in the \"Name\" column's dropdown,\ntype \"pg_read_all_data\" in the \"Value\" column.\nIn the \"Database\" column select the desired DB (where you have edited the schema in the previous steps).\nNote, you can add more rows with the same settings for different databases (of course, if those DBs have edited schemas as shown above).\n\nClick \"Save\".\nNow you can log into your PhpPgAdmin (or psql or wherever you need) under this user and do only selects. A real read-only user role.\n\nI hope it will help someone.\n\nA: I don't have enough reputation to comment on your very helpful post, but wanted to add that the public schema by default gives full access to the PUBLIC role (implicit role that all users belong to).\nSo you would first need to revoke this access.\nThis can be done in pgAdmin in the Security tab of the schema properties dialog, or with the SQL command\nREVOKE CREATE ON SCHEMA public FROM PUBLIC;\n\nSee also:\n\n*\n\n*Issue creating read-only user in PostgreSQL that results in user with greater permission with public schema\n\n*PostgreSQL - Who or what is the \"PUBLIC\" role?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/72791383", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "7"}} {"text": "Q: Grouping rows with Groupby and converting date & time of rows of start date-time and end date- time columns I have a dataset looking like this:\n\n\n\nBlast Hole East Coordinate North Coordinate Collar Theoritical Depth Tag Detector ID Date and Time Detection_Location Detection Date & Time\r\n64 16745.42 107390.32 2634.45 15.95 385656531 23-08-2018 2:39:34 PM CV23 2018-09-08 14:18:17\r\n61 16773.48 107382.6 2634.68 16.18 385760755 23-08-2018 2:38:32 PM CV23 2018-09-08 14:24:19\r\n63 16755.07 107387.68 2634.58 16.08 385262370 23-08-2018 2:39:30 PM CV23 2018-09-08 14:12:42\r\n105 16764.83 107347.67 2634.74 16.24 385742468 23-08-2018 2:41:29 PM CV22 2018-09-06 20:02:46\r\n100 16752.74 107360.32 2634.33 15.83 385112050 23-08-2018 2:41:08 PM CV22 2018-09-06 20:15:42\r\n99 16743.1 107362.96 2634.36 15.86 385087366 23-08-2018 2:41:05 PM CV22 2018-09-06 20:49:21\r\n35 16747.75 107417.68 2635.9 17.4 385453358 23-08-2018 2:36:09 PM CV22 2018-09-23 05:47:44\r\n5 16757.27 107452.4 2636 17.5 385662254 23-08-2018 2:35:03 PM CV22 2018-09-23 05:01:12\r\n19 16770.89 107420.83 2634.81 16.31 385826979 23-08-2018 2:35:50 PM CV22 2018-09-23 05:52:54\n\n\nI intended to group all the rows having 3 detections at one place ( in column Detection_location) in one hour.\nI used the following code for grouping the rows falling in one hour per 3 detection:\ndf2 = df1.groupby([pd.Grouper(key = 'Detection Date & Time', freq = 'H'), \n df1.Detection_Location]).size().reset_index(name = 'Tags')\n\nThis code gave me a result like this:\n\nI would rather like to have result in which each rows have start time when the first detection was there in that hour and when the last detection was seen and thus i would like to have a result like this:\n\n\n\nThis is the required output:\r\n\r\nDetection Date & Time - Start Detection Date & Time - End Detection_Location Tags\r\n2018-09-06 20:02:46 2018-09-06 20:49:21 CV22 3\r\n2018-09-08 14:12:42 2018-09-08 14:24:19 CV23 3\r\n2018-09-23 05:01:12 2018-09-23 05:47:44 CV22 3\n\n\nCan anyone suggest what else should i add in my group-by function to get this result.\nThanks\n\nA: Check if this works for you. Inside the aggregate function, you can pass all the values that you want to capture.\ndf2 = (df.groupby([pd.Grouper(key = 'Detection Date & Time', freq = 'H'),df.Detection_Location],sort=False)['Detection Date & Time']\n .agg(['first','last','size'])).reset_index().rename(columns={\"first\": \"Detection Date & Time - Start\", \"last\": \"Detection Date & Time - End\", \"size\": \"Tags\"})\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/57549303", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Linking to iOS simulator binaries on OSX I was curious what would happen if I linked to an iOS simulator framework in a Mac app. So I copied UIKit to it's own folder (so the Framework search path wouldn't include all the iOS simulator framework, as like CoreFoundation is both on Mac and iOS but has different headers), and dragged it into the link section in Xcode. The error Xcode gave me was: \n\nbuilding for MacOSX, but linking against dylib built for iOS Simulator\n file '/Users/jonathan/Desktop/macuikit/UIKit.framework/UIKit' for\n architecture x86_64\n\nBoth architectures are x86_64, so how can it tell the framework is specifically for the iOS simulator, I removed all references to iOS in things like Info.plist, even tried deleted everything but the UIKit binary, but the same error came up. Is there something in the binary it self that tells the linker which platform it can run on, rather than just the architecture? I looked at the Mach-O header but there is only fields for CPU type and subtype, and neither has a value for the simulator as expected.\n\nA: After a little bit of digging, it turns out that the platform on which the library can run on is indeed specified in the binary. In fact, you can edit the binary in your favorite Hex editor and make the linker skip this check entirely.\nThis information is not specified in the Mach-O header (as you have already realized). Instead, it is specified as a load command type. You can see the available types by digging through the LLVM sources. Specifically, the enum values LC_VERSION_MIN_MACOSX and LC_VERSION_MIN_IPHONEOS look interesting.\nNow, find the offset for this in our binary. Open the same in MachOView (or any other editor/viewer or your choice) and note the offset:\n\nOnce the offset is noted, jump to the same in a Hex editor and update it. I modified LC_VERSION_MIN_IPHONEOS (25) to LC_VERSION_MIN_MACOSX (24)\nSave the updates and try linking again. The error should go away. Of course, you will hit other issues when you try to actually run your example. Have fun with LLDB then :)\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/28946926", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: Find all the combinations that return a particular value from a function This is a variation on finding all the combinations that add to a target, with two constraints:\n\n\n*\n\n*We have a limited set of numbers to work with.\n\n*The numbers must result in the target number when fed into a separate function.\n\n\nIn this case, the limited set of numbers include 25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400, etc.\nAnd the function is to add the values together and then multiply by a number based on how many numbers we had:\n\n\n*\n\n*If 1 number, multiply by 1.\n\n*If 2 numbers, multiply by 1.5\n\n*If 3-6 numbers, multiply by 2\n\n*If 7-10 numbers, multiply by 2.5\n\n*If >10 numbers, multiply by 3\n\n\nExamples:\n[50, 50, 50] => 300\n[100, 100] => 300\nTarget numbers include 300, 600, 900, 1500, 3000, 3600, 4400, 5600, 6400, 7600, 9600, etc.\nMy intuition is that this can't be done recursively, because each step doesn't know the multiplier that will eventually be applied.\n\nA: Here's a recursive example in JavaScript that seems to answer the requirements:\n\n\nfunction getNextM(m, n){\r\n if (n == 1)\r\n return 1.5;\r\n if (n == 2)\r\n return 2;\r\n if (n == 6)\r\n return 2.5;\r\n if (n == 10)\r\n return 3;\r\n\r\n return m;\r\n}\r\n\r\nfunction g(A, t, i, sum, m, comb){\r\n if (sum * m == t)\r\n return [comb];\r\n \r\n if (sum * m > t || i == A.length)\r\n return [];\r\n \r\n let n = comb.length;\r\n \r\n let result = g(A, t, i + 1, sum, m, comb);\r\n \r\n const max = Math.ceil((t - sum) / A[i]);\r\n\r\n let _comb = comb;\r\n \r\n for (let j=1; j<=max; j++){\r\n _comb = _comb.slice().concat(A[i]);\r\n sum = sum + A[i];\r\n m = getNextM(m, n);\r\n n = n + 1;\r\n result = result.concat(g(\r\n A, t, i + 1, sum, m, _comb)); \r\n }\r\n \r\n return result;\r\n}\r\n\r\nfunction f(A, t){\r\n return g(A, t, 0, 0, 1, []);\r\n}\r\n\r\n\r\nvar A = [25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400];\r\n\r\nvar t = 300;\r\n\r\nconsole.log(JSON.stringify(f(A, t)));\r\n\r\n \n\n\n\nA: I wrote a small script in Python3 that may solve this problem.\nmultiply_factor = [0,1,1.5,2,2,2,2,2.5,2.5,2.5,2.5,3]\ndef get_multiply_factor(x):\n if x< len(multiply_factor):\n return multiply_factor[x]\n else:\n return multiply_factor[-1]\n\n\nnumbers = [25, 50, 100, 200, 450, 700, 1100, 1800, 2300, 2900, 3900, 5000, 5900, 7200, 8400]\ncount_of_numbers = len(numbers)\n\n\n# dp[Count_of_Numbers]\ndp = [[] for j in range(count_of_numbers+1)]\n\n#Stores multiplying_factor * sum of numbers for each unique Count, See further\nsum_found =[set() for j in range(count_of_numbers+1)]\n\n# Stores Results in Unordered_Map for answering Queries\nmaster_record={}\n\n#Initializing Memoization Array\nfor num in numbers:\n dp[1].append(([num],num*get_multiply_factor(1)))\n\nfor count in range(2,count_of_numbers+1): # Count of Numbers\n for num in numbers:\n for previous_val in dp[count-1]:\n old_factor = get_multiply_factor(count-1) #Old Factor for Count Of Numbers = count-1\n new_factor = get_multiply_factor(count) #New Factor for Count Of Numbers = count\n\n # Multiplying Factor does not change\n if old_factor==new_factor:\n # Scale Current Number and add\n new_sum = num*new_factor+previous_val[1]\n else:\n #Otherwise, We rescale the entire sum\n new_sum = (num+previous_val[1]//old_factor)*new_factor\n\n # Check if NEW SUM has already been found for this Count of Numbers\n if new_sum not in sum_found[count]:\n # Add to current Count Array\n dp[count].append(([num]+previous_val[0],new_sum))\n # Mark New Sum as Found for Count Of Numbers = count\n sum_found[count].add(new_sum)\n if new_sum not in master_record:\n # Store Seected Numbers in Master Record for Answering Queries\n master_record[new_sum] = dp[count][-1][0]\n\n\n\n# for i in dp:\n# print(i)\nprint(master_record[1300])\nprint(master_record[300])\nprint(master_record[2300])\nprint(master_record[7950])\nprint(master_record[350700.0])\n\nOutput :- \n[100, 100, 450]\n[100, 100]\n[25, 25, 1100]\n[25, 50, 3900]\n[1800, 5900, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400, 8400]\n[Finished in 0.3s]\n\nMy Algo in a nutshell.\nIterate over Count[2, Limit], I've considered limit = Number of Elements\n Iterate over List of Numbers\n Iterate over Sums found for previous count.\n Calculate New Sum,\n If it does not exist for current count, update.\n\nI am assuming that the number of queries will be large so that memorization pays off. The upper limit for count may break my code as the possibilities may grow exponentially.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/61434281", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Multiple widget changes based on one button event in Kivy I'm trying to build this application which contains multiple buttons. I can bind each button event to a callback but I am not able to change the state (namely the label) of any other button except for the one that fired the event. Does anyone know how to do this?\n\nA: All you need is a reference to the other button, then you can do other_button.text = 'whatever'.\nThe way to do this depends on how you've constructed the program. For instance, if you constructed in the program in kv language, you can give your buttons ids with id: some_id and refer to them in the callback with stuff like on_press: some_id.do_something().\nIn pure python, you could keep references to the button in the parent class when you create them (e.g. self.button = Button()) so that the callback can reference self.button to change it. Obviously that's a trivial example, but the general idea lets you accomplish anything you want.\n\nA: Probably not the official way, but try out the following code. It will change the text property of the buttons...\nEzs.kv file:\n #:kivy 1.8.0\n\n:\n BoxLayout:\n orientation: 'vertical'\n padding: 0\n spacing: 6\n\n #choose\n Button:\n id: btn_1\n text: 'text before'\n on_press: btn_2.text = 'Whatever'\n on_release: self.text = 'Who-Hoo' \n #choose\n Button:\n id: btn_2\n text: 'Press this'\n on_release: self.text = 'HEEYY'\n on_press: btn_1.text = 'text after'\n\n.py file:\nclass Ezs(BoxLayout):\n\n\nclass EzsApp(App):\n\n def build(self):\n return Ezs\n\nif __name__ == '__main__':\n EzsApp().run()\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/20650593", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: C++ CLI error C3767: candidate function(s) not accessible I'm new to C++ CLI coming from unmanaged C++ world.\nI'm getting this error:\ncandidate function(s) not accessible \n\nwhen I pass a std::string as part of the method argument.\nHere's the exact code:\nLib Project (compiled as .dll project)\n//Lib.h\n#pragma once\n\npublic ref class Lib\n{\npublic:\n Lib(void);\n\npublic:\n void Extract( std::string& data_ );\n};\n\n//Lib.cpp\n#include \"Lib.h\"\n\nLib::Lib(void)\n{\n}\n\nvoid Lib::Extract( std::string& data_ )\n{\n data_.empty();\n}\n\nLibTest Project (compiled as application.exe)\n// LibTest.h\n#pragma once\n\nref class LibTest\n{\npublic:\n LibTest(void);\n};\n\n// LibTest.cpp\n#include \"LibTest.h\"\n\nLibTest::LibTest(void)\n{\n Lib^ lib = gcnew Lib;\n lib->Extract( std::string(\"test\") );\n}\n\nint main()\n{\n return 0;\n}\n\nCompiler Error:\n1>------ Build started: Project: LibTest, Configuration: Debug Win32 ------\n1>Compiling...\n1>LibTest.cpp\n1>.\\LibTest.cpp(7) : error C3767: 'Lib::Extract': candidate function(s) not accessible\n\n\nA: if you simply must access the internal methods another work around would be making the projects as Friend Assemblies like that:\n//Lib Project \n#pragma once\n\n//define LibTest as friend assembly which will allow access to internal members\nusing namespace System;\nusing namespace System::Runtime::CompilerServices;\n[assembly:InternalsVisibleTo(\"LibTest\")];\n\npublic ref class Lib\n{\n public:\n Lib(void);\n\n public:\n void Extract( std::string& data_ );\n};\n\n//LibTest Project \n#pragma once\n\n#using as_friend\n\nref class LibTest\n{\n public:\n LibTest(void);\n};\n\n\nA: The problem is that std::string will compile as a internal (non public) type. This is actually a change in VS 2005+:\nhttp://msdn.microsoft.com/en-us/library/ms177253(VS.80).aspx: \nNative types are private by default outside the assembly\nNative types now will not be visible outside the assembly by default. For more information on type visibility outside the assembly, see Type Visibility. This change was primarily driven by the needs of developers using other, case-insensitive languages, when referencing metadata authored in Visual C++.\nYou can confirm this using Ildasm or reflector, you will see that your extract method is compiled as:\npublic unsafe void Extract(basic_string,std::allocator >* modopt(IsImplicitlyDereferenced) data_)\n\nwith basic_string being compiled as:\n[StructLayout(LayoutKind.Sequential, Size=0x20), NativeCppClass, MiscellaneousBits(0x40), DebugInfoInPDB, UnsafeValueType]\ninternal struct basic_string,std::allocator >\n\nNote the internal. \nUnfortunately you are then unable to call a such a method from a different assembly. \nThere is a workaround available in some cases: You can force the native type to be compiled as public using the make_public pragma. \ne.g. if you have a method Extract2 such as:\nvoid Extract2( std::exception& data_ );\n\nyou can force std::exception to be compiled as public by including this pragma statement beforehand:\n#pragma make_public(std::exception)\n\nthis method is now callable across assemblies. \nUnfortunately make_public does not work for templated types (std::string just being a typedef for basic_string<>)\nI don't think there is anything you can do to make it work. I recommend using the managed type System::String^ instead in all your public API. This also ensures that your library is easily callable from other CLR languages such as c#\n\nA: In addition to the solutions described above, one can subclass the templated type to obtain a non-templated type, and include its definition in both projects, thus overcoming some of the problems mentioned above.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/947213", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "16"}} {"text": "Q: using sass with compass - 404 css not found I'm using the followig config for compass with grunt:\n compass: {\n options: {\n sassDir: '<%= yeoman.app %>/styles',\n cssDir: '.tmp/styles',\n imagesDir: '<%= yeoman.app %>/images',\n javascriptsDir: '<%= yeoman.app %>/scripts',\n fontsDir: '<%= yeoman.app %>/styles/fonts',\n importPath: 'app/components',\n relativeAssets: false\n },\n dist: {},\n server: {\n options: {\n debugInfo: true\n }\n }\n},\n\nand I see that the sass is getting compiled since it shows in the .tmp/styles folder\nbut for some reason when I call the css files from the <%= yeoman.app %>/styles filder it's not found\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/19614469", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Javascript - change r attribute of circle wrapped in #shadow-root My html tree looks as follows:\n\n \n \n \"\n />\n\n\nAfer compilation the href dissolves to data:image/svg+xml;base64,PCEtLSA8P3htbCB2ZXJzaW9uPSIxLjAiIGVuY29kaW5nPSJ1dGYtOCI/Pgo8c3ZnIHZlcnNpb249IjEuMCIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxMDAwIDUwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CjxjaXJjbGUgaWQ9InNlbWktY2lyY2xlIiBjeD0iNTAwIiBjeT0iNTAwIiByPSI1MDAiLz4KPC9zdmc+IC0tPgoKCjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTAwMCIgaGVpZ2h0PSI1MDAiIHZpZXdCb3g9IjAgMCAxMDAwIDUwMCI+CiAgPGRlZnM+CiAgICA8c3R5bGU+CiAgICAgIC5jbHMtMSB7CiAgICAgICAgZmlsbDogIzAwMDsKICAgICAgfQogICAgPC9zdHlsZT4KICA8L2RlZnM+CiAgPGNpcmNsZSBpZD0ic2VtaS1jaXJjbGUiIGNsYXNzPSJjbHMtMSIgY3g9IjUwMCIgY3k9IjUwMCIgcj0iNTAiLz4KPC9zdmc+Cgo=#semi-circle\nIf anyone wants to test it, please replace the value in the href above with this link.\nI am trying to change the radius of the circle through \ndocument.getElementById('use-tag').setAttribute('r', '25') \n\nbut instead it only gives use an attribute of r=25. Is there any way I can change the radius of the circle? I have tried to fetch it using\n getElementById\n\nbut it just gives me null (I'm assuming because it's wrapped in a shadow root). \nedit: The gist of the problem here I believe is that I am trying to change the attributes of a closed shadow root which is impossible to achieve. So can someone please tell me why am I get a closed root instead of an open one? And how can I get an open one?\nedit: Here is a demo of this situation: https://codesandbox.io/embed/smoosh-sun-nnevd?fontsize=14&hidenavigation=1&theme=dark\n\nA: Since you have direct access to circle with id semi-circle, you can update it as the below snippet.\nThe snippet is running under a setTimeout to show the difference.\n\n\nsetTimeout(function() {\r\n var circle = document.getElementById('semi-circle');\r\n circle.setAttribute('r', 60)\r\n}, 3000)\n\r\n \r\n\n\n\nYou can also do it in another way, check the snippet\n\n\nsetTimeout(function() {\r\n var circle = document.getElementById('floating-button-svg');\r\n circle.firstElementChild.setAttribute('r', 60)\r\n}, 1500)\n\r\n \r\n\n\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/60392155", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to replace this componentWillReceiveProps? I have a login and register component with forms that were created a while ago before these methods were deprecated, I've been looking around but cannot seem to find a solution, how would I go about refactoring this to using getDerivedStateFromProps?\n componentWillReceiveProps(nextProps) {\n if (nextProps.auth.isAuthenticated) {\n this.props.history.push(\"/dashboard\")\n }\n\n if (nextProps.errors) {\n this.setState({\n errors: nextProps.errors\n });\n }\n\n\nA: Since you're using componentWillReceiveProps to keep a local state in sync with props you have two alternatives:\nDeclare your initial state based on props and use componentDidUpdate to ensure props synchronicity\nclass Component extends React.Component{\n state = { foo : this.props.foo }\n\n componentDidUpdate(prevProps){\n if(this.props.foo !== prevProps.foo)\n this.setState({ foo : prevProps.foo })\n }\n}\n\nThis is actually triggering an extra render everytime, if you have some local state that is always equal to some prop you can use the prop directly instead.\nUse getDerivedStateFromProps to update the state based on a prop change, but keep in mind that you probably don't need to use it\nclass Component extends React.Component{\n static getDerivedStateFromProps(props){\n return { foo : props.foo }\n }\n}\n\n\nA: The answer to the question you asked is probably not going to be satisfactory. :-) The answer is that if you really need to derive state from props (you probably don't, just use props.errors directly in render), you do it with the newer getDerivedStateFromProps static method that accepts props and state and (potentially) returns a state update to apply:\nstatic getDerivedStateFromProps(props, state) {\n return props.errors ? {errors: props.errors} : null;\n}\n\nor with destructuring and without the unused state parameter:\nstatic getDerivedStateFromProps(({errors})) {\n return errors ? {errors} : null;\n}\n\nBut, you're saying \"But that doesn't do the authentication thing...?\" That's right, it doesn't, because that componentWillReceiveProps shouldn't have, either, it violates the rule props are read-only. So that part shouldn't be there. Instead, if that entry in props.history is supposed to be there, it should be put there by the parent component.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/59143054", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Finding value of the limit: $ \\lim_{t \\to 0} \\frac{\\varphi(1+t) - \\varphi(t)}{t}$ Let $$\\varphi(x) = e^{-x} + \\frac{x}{1!} \\cdot e^{-2x} + \\frac{3x^{2}}{2!}\\cdot e^{-3x} + \\frac{4^{2} \\cdot x^{3}}{3!} \\cdot e^{-4x} + \\cdots$$\nThen what is the value of: $$ \\displaystyle\\lim_{t \\to 0} \\frac{\\varphi(1+t) - \\varphi(t)}{t}$$\nI am not getting any idea as to how to proceed for this problem. I tried summing up the expression but no avail. I also tried differentiating $\\varphi(x)$ since the limit quantity which we require seems to involve derivative but again i couldn't find any pattern. Any ideas on how to solve this problem.\n\nA: The function $\\varphi(x)$ can be written as\n$$\r\n\\begin{eqnarray}\r\n\\varphi(x)\r\n &=& \\frac{1}{x} \\sum_{n=1}^{\\infty} \\frac{n^{n-1}}{n!}\\left(xe^{-x}\\right)^{n} \\\\\r\n &=& -\\frac{1}{x} \\sum_{n=1}^{\\infty} \\frac{(-n)^{n-1}}{n!}\\left(-xe^{-x}\\right)^{n} \\\\\r\n &=& -\\frac{1}{x} W_0\\left(-xe^{-x}\\right),\r\n\\end{eqnarray}\r\n$$\nwhere $W_0$ is the Lambert W-function's main branch. For sufficiently small $y$, the definition of the W-function ensures that $W_0(ye^y)=y$, so for small $t$,\n$$\r\n\\begin{eqnarray}\r\n\\varphi(t)\r\n &=& -\\frac{1}{t}W_0\\left(-te^{-t}\\right) \\\\\r\n &=& -\\frac{1}{t}(-t) \\\\\r\n &=& 1.\r\n\\end{eqnarray}\r\n$$\nIn fact this equality holds for all $0 \\le t < 1$. For values slightly larger than $1$, we use\n$$\r\n-(1+t)e^{-(1+t)} = \\frac{-(1+t)}{1+t+\\frac{1}{2}t^2+O(t^3)} = -1 + \\frac{1}{2}t^2+O(t^3) = -(1-t)e^{-(1-t)},\r\n$$\nso\n$$\r\n\\begin{eqnarray}\r\n\\varphi(1+t) &=& -\\frac{1}{1+t}W_0(-(1+t)e^{-(1+t)}) \\\\ &\\approx& -\\frac{1}{1+t}W_0(-(1-t)e^{-(1-t)}) \\\\ &=& \\frac{1-t}{1+t} \\\\ &=& 1 - 2t + O(t^2).\r\n\\end{eqnarray}\r\n$$\nThe desired limit, then, is\n$$\r\n\\lim_{t\\rightarrow 0}\\frac{\\varphi(1+t) - \\varphi(t)}{t} = \\lim_{t\\rightarrow 0}\\frac{(1-2t) - 1}{t} = -2.\r\n$$\n\nA: Hmm, using Pari/GP, I just tried to find the coefficients of $ \\varphi (t) $\npolcoeffs(exp(-x)*sumalt(k=0,exp(-k*x)*x^k/k!*(k+1)^(k-1)*1.0))\n\n(where the polcoeffs-function just retrieves the whole vector of coefficients up to the defined series-precision and I used x instead of t )\nThe result of this is an (arbitrary near) approximation to the formal powerseries $ \\varphi(t) = 1.0 $ So it may be useful to analyze the approximation of that powerseries to the constant in order to evaluate your limit-formula. \n\n[update] If one expands the powerseries for $e^{- k x}$ and collect coefficients at like powers of x then indeed all coefficients at a certain power of x sum to zero, thus vanish (at least heuristically up to $x^{64}$, I did not do final analysis) . Then all derivatives are also zero and even the L'Hospital-rule is of no use here. However, I don't know whether there could be some special reason that this expansion into powerseries might not be feasible/allowed because the result is an infinite sum of formal powerseries. [end update] \n\n[update 2]\n$ \\varphi(x)=e^{-x}+xe^{-2x}\\frac1{1!} \r\n+x^2e^{-3x}\\frac3{2!} \r\n+x^3e^{-4x}\\frac{4^2}{3!} + \\ldots\r\n $ \n$\\begin{array} {rrrr}\r\n\\varphi(x)= ( & 1 & -x & + \\frac{x^2}{2!}&+ \\frac{x^3}{3!} & + \\ldots )\\\\\r\n+ \\frac{x}{1!}(& 1 & -2x & + \\frac{2^2x^2}{2!}&+ \\frac{2^3x^3}{3!} & + \\ldots ) \\\\\r\n+ \\frac{3x^2}{2!}(& 1 & -3x & + \\frac{3^2x^2}{2!}&+ \\frac{3^3x^3}{3!} & + \\ldots ) \\\\\r\n+ \\ldots \\\\\r\n\\end{array} $ \nCollecting equal powers of x means to add coefficients along the antidiagonal so\n$\\begin{array} {rrrr}\r\n\\varphi(x)= 1 \\\\\r\n- x (&\\frac{1}{1!}& - \\frac{1}{1!} ) \\\\\r\n+ x^2 (&\\frac{1}{2!}& - \\frac{2}{1!}& + \\frac{3^1}{2!}) \\\\\r\n- x^3 (&\\frac{1}{3!}& - \\frac{2^2}{2!}& + \\frac{3^2}{2!}& - \\frac{4^2}{3!}) \\\\\r\n+ \\ldots \\\\\r\n\\end{array} $ \nAll the parentheses seem to form binomially weighted sums of like powers with alternating signs which are known to evaluate to zero, so the coefficients at each power of x should be zero and if this is so, the taylorseries is then $\\varphi(x)=1 $\n[end update 2]\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/19967", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: For the torus to rotate 180 degrees around the East-West symmetry axis, what happens? (Suppose to ignore the deformed friction and torus when rotating)\n\n", "meta": {"language": "en", "url": "https://physics.stackexchange.com/questions/472462", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Axios import breaks rest of javascript file I'm using encore and yarn to set up my javascript and css in a symfony project. I want to use axios so I use:\nyarn add axios\n\nthen I add this code to app.js\nimport '../css/app.scss';\nimport axios from \"axios\";\n\nconsole.log('test');\n\naxios({\n url: 'https://dog.ceo/api/breeds/list/all',\n method: 'get',\n data: {\n foo: 'bar'\n }\n});\n\nThen yarn watch picks up the modifications and compiles it to this:\n(window[\"webpackJsonp\"] = window[\"webpackJsonp\"] || []).push([[\"app\"],{\n\n/***/ \"./assets/css/app.scss\":\n/*!*****************************!*\\\n !*** ./assets/css/app.scss ***!\n \\*****************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n// extracted by mini-css-extract-plugin\n\n/***/ }),\n\n/***/ \"./assets/js/app.js\":\n/*!**************************!*\\\n !*** ./assets/js/app.js ***!\n \\**************************/\n/*! no exports provided */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _css_app_scss__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../css/app.scss */ \"./assets/css/app.scss\");\n/* harmony import */ var _css_app_scss__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_app_scss__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_1__);\n\n\nconsole.log('test');\naxios__WEBPACK_IMPORTED_MODULE_1___default()({\n url: 'https://dog.ceo/api/breeds/list/all',\n method: 'get',\n data: {\n foo: 'bar'\n }\n});\n\n/***/ })\n\n},[[\"./assets/js/app.js\",\"runtime\",\"vendors~app~normalization\"]]]);\n\nWhen I remove the import of Axios the console.log('test') runs but when I add the import it won't. So the import breaks the other code. \nCould someone explain how I import axios without trouble?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/59863878", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Css counter for list I am trying to use the counter increment in css on my ordered list but its not working\nThis is what I want to display:\n1. Acknowledgements\n 1.1 blah, blah ....\n 1.2 blah, blah ....\n 1.3 blah, blah ....\n\n2. Risk Statement\n 2.1 blah, blah ....\n 2.2 blah, blah ....\n 2.3 blah, blah ....\n\n3. License\n 3.1 blah, blah ....\n 3.2 blah, blah ....\n 3.3 blah, blah ....\n\nBut this s what is happening... http://jsfiddle.net/XQKcy/\n\nA: Demo Fiddle\nYou were very close:\nbody {\n counter-reset: listCounter;\n}\nol {\n counter-increment: listCounter;\n counter-reset: itemCounter;\n list-style:none;\n}\nli{\n counter-increment: itemCounter;\n}\nli:before {\n content: counter(listCounter) \".\" counter(itemCounter);\n left:10px;\n position:absolute;\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/23267039", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Global var vs Shared Instance swift What is the difference between global variable and shared instance in Swift? what are their respective field of use? Could anyone clarify their concept based upon Swift.\n\nA: A global variable is a variable that is declared at the top level in a file. So if we had a class called Bar, you could store a reference to an instance of Bar in a global variable like this:\nvar bar = Bar()\n\nYou would then be able to access the instance from anywhere, like this:\nbar\nbar.foo()\n\nA shared instance, or singleton, looks like this:\nclass Bar {\n static var shared = Bar()\n private init() {}\n func foo() {}\n}\n\nThen you can access the shared instance, still from anywhere in the module, like this:\nBar.shared\nBar.shared.foo()\n\nHowever, one of the most important differences between the two (apart from the fact that global variables are just generally discouraged) is that the singleton pattern restricts you from creating other instances of Bar. In the first example, you could just create more global variables:\nvar bar2 = Bar()\nvar bar3 = Bar()\n\nHowever, using a singleton (shared instance), the initialiser is private, so trying to do this...\nvar baaar = Bar()\n\n...results in this:\n\n'Bar' initializer is inaccessible due to 'private' protection level\n\nThat's a good thing, because the point of a singleton is that there is a single shared instance. Now the only way you can access an instance of Bar is through Bar.shared. It's important to remember to add the private init() in the class, and not add any other initialisers, though, or that won't any longer be enforced.\nIf you want more information about this, there's a great article by KrakenDev here.\n\nA: Singleton (sharing instance)\nEnsure that only one instance of a singleton object is created & It's provide a globally accessible through shared instance of an object that could be shared even across an app.\nThe dispatch_once function, which executes a block once and only once for the lifetime of an app.\nGlobal variable\nApple documentation says Global variables are variables that are defined outside of any function, method, closure, or type context.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/44939952", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "8"}} {"text": "Q: How to set layout with XML in View for BaseAdapter getView() method The following Java code (from https://www.intertech.com/Blog/android-adapters-adapterviews/) is from getView(), a method implementation from a Android Adapter class, and it builds a View in Java to populate items on a List. I get how it works, but the same page says it can be built using an XML file, which makes sense to me, but I'm unable to find any examples. I understand how to use XML resource files to set Activity layout using setContentView(). But how would I invoke an XML resource file to build the View in the getView() method?\n@Override\npublic View getView(int position, View convertView, ViewGroup parent) {\n if (convertView == null) {\n Context context = parent.getContext();\n LinearLayout view = new LinearLayout(context);\n view.setOrientation(LinearLayout.HORIZONTAL);\n view.addView(new CheckBox(context));\n TextView nameTextView = new TextView(context);\n nameTextView.setText(courses.get(position).getName());\n nameTextView.setPadding(0, 0, 10, 0);\n view.addView(nameTextView);\n TextView parTextView = new TextView(context);\n parTextView.setText(Integer.toString(courses.get(position).getPar()));\n view.addView(parTextView);\n return view;\n }\n return convertView;\n}\n\n\nA: like this \nitem_test.xml\n\n\n\n \n\n\nadapter \n@Override\npublic View getView(int position, View convertView, ViewGroup parent) {\n Holder holder; // use holder\n if (convertView == null) {\n convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_test, parent, false);\n holder = new Holder(convertView);\n convertView.setTag(holder);\n } else {\n holder = (Holder) convertView.getTag();\n }\n holder.name.setText(\"name\");\n return convertView;\n}\n\npublic class Holder {\n private TextView name;\n\n public Holder(View view) {\n name = view.findViewById(R.id.name);\n }\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/55692877", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}} {"text": "Q: project using moleculer-sentry example I have been trying to use the moleculer-sentry mixing in a moleculer project. But it is not working.\nDoes someone have an example project using this mixing?\nAlso i have been searching answers in internet, but nothing.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/71413946", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How Javascript asyc and await working in this particular code? I have implemented an async function which creates an XHR object inside a Promise, requests a data from the server and fulfills the Promise with the response received from the server\nasync function playWordsAudio(id, type, check=false){\n \n let file_namePromise = new Promise(function (onSuccess, onFailure){\n var xhttp = new XMLHttpRequest();\n xhttp.onload = function(){\n if(this.readyState == 4 && this.status == 200){\n if(this.responseText !== \"No Data\"){\n file_name = this.responseText;\n if(check == false){\n audio = new Audio('assets/uploads/wav/' + file_name);\n audio.play();\n }else{\n onSuccess(file_name);\n }\n }else{\n if(check){\n onSuccess('Not Found');\n }\n }\n }\n };\n\n xhttp.open(\"GET\", \"scripts/get_word_audio.php?id=\" + id + \"&type=\" + type, true);\n xhttp.send(); \n });\n\n let resultant = await file_namePromise;\n\n if(check){\n return resultant;\n }\n}\n\nLater I have defined another function which calls the async function shown above\nfunction modify_object(id, type, obj){\n result = playWordsAudio(id, type, true);\n result.then(function(value){\n if(value == \"Not Found\"){\n obj.classList.remove('fa-play');\n }\n }); \n}\n\nLater in the implementation I also call the modify_object function and pass it an object for modification as described in the function.\nmodify_object(id, type, plays[i]);\n\nIn the async function I have created a Promise, on success I pass it the file_name received from the XHR response or else I pass it 'Not Found'.\nHere I am confused on how the await part works inside the asyc function.\nIt returns the resultant to the caller of the async function which is\nresult = playWordsAudio(id, type, true);\n\nIf so, what does the onSuccess method in the Promise do\nlet file_namePromise = new Promise(function (onSuccess, onFailure){\n/*\n Some Codes\n*/\n\nonSuccess(file_name);\n\n/*\n Some more code\n*/\n\nonSuccess('Not Found);\n\n/*\n Rest of the Code\n*/\n}\n\nAs I have checked by commenting out the return statement after the await statement\nif(check){\n// return resultant;\n}\n\nThe Promise is not fulfilled.\nHow does each part of the implementation work as described above?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/67992979", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Convert ts object to data.frame and keep row- and colnames I want to convert a ts (i.e. timeseries) R object to a data.frame. The names of rows and columns of the ts object should be retained.\nConsider the AirPassengers data set:\ndata(AirPassengers)\n\nI could convert this ts object to a data.frame as follows:\nAirPassengers <- data.frame(matrix(as.numeric(AirPassengers), ncol = 12, byrow = TRUE))\ncolnames(AirPassengers) <- c(\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\")\nrownames(AirPassengers) <- 1949:1960\n\nHowever, this seems to be way too complicated. Surprisingly, a google search didn't show a simpler solution.\nQuestion: Is there a simple solution how to convert ts objects to a data.frame without losing colnames and rownames?\n\nA: The underlying issue is that the output of print for a time series object is quite heavily processed by .preformat.ts. If you want to convert it to a data frame that is visually similar to the print results this should do:\ndf <- data.frame(.preformat.ts(datasets::AirPassengers), stringsAsFactors = FALSE)\n\nNote that this will produce characters (as that is how .preformat.ts works), so be careful with the use (not sure what is the purpose of the conversion?). \n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/54053314", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Where does setup.py install console scripts to? When I set up my package using setup.py to have a console script entry point, pip install -e . creates a cli exe in the C:\\Users\\...\\anaconda3\\envs\\envname\\Scripts\\foo.exe.\nHowever on a separate computer the python executable is the one from the Windows Store:\nC:\\Users\\...\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_qbz5n6khra8p0\\python.exe\nThis doesn't set the PATH environment variable correctly to make .exes in the Scripts folder callable from the command line, so I need the full path to the .exe to call it.\nAnyway I want to find the location of foo.exe on this second computer (which I don't have access to), is there a command I can instruct the second computer to run which will tell me where a console script will be located for that given sys.executable? I.e. for my computer, I expect it to print C:\\Users\\...\\anaconda3\\envs\\envname\\Scripts.\n\nFWIW, this is my setup.cfg:\n[options]\npy_modules = xml2csv\npython_requires = >=3.10\n\n[options.entry_points]\nconsole_scripts =\n xml2csv=xml2csv:main\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/72643833", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Using the button tag, can I customize the button? I want to use a custom button image that I drew up for my application, but doing so I need to use different images for the button being focused and another for it being pressed. \nI came across the selector tags but for some reason it doesn't like it. Eclipse complains about a 'broken rendering library'. The error I get is this:\nBroken rendering library; unsupported DPI. Try using the SDK manager to get updated.\n\nAnd I have, I've updated every API past 10. If it matters, my target API is 15 and my compile API is 17. \nIf I can't get this working, can I simply use the Button tag and maybe change it in the Java src code or something?\n\nA: use a custom layout like this \n\n\n \n\n \n\n \n\n\nAlso note that the the selector should be defined in this particular way else they will give problem .i.e. \n1)state_pressed\n2)state_focused ( work only if you scroll to that button using the hardware key)\n3)drawable i.e. normal\n\nIf you changed the ordering of the selector then it won't work. One easy way to remember it is visualizing a qwerty phone - first i saw the button (normal), then moved to that particular button using arrow keys (state_focused), then i pressed that button (state_pressed). Now write them backwards.\n\nA: Instead of button,create ImageView and do necessary things on click of the image.\n \n \n\nAlso inorder to give different images on click and focus,create selector.xml in drawable folder and set background of imageview as selector file.\nselector.xml\n \n \n\n \n \n \n \n\n\n \n\nHope this will help you!\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/16826011", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "8"}} {"text": "Q: How to show button when adding fragment? Bottom button(234) is not showing after adding fragment. I don't want to resize my fragment size.\n\n\nHome_Fragment.xml This is the main Fragment page. It also have profile Fragment. From Profile Fragment we are calling next fragment that is hiding bottom button (TV_Chat button name)\n\n\n \n \n\n \n\n \n \n \n\n \n\n\n\n\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/50348828", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: ASP.NET/GridView: Using only a subset of the data fields in the table I have a list of objects called Activity and I want to display the date, type and notes for each and every one of these activities. This is the code I'm using.\n\n \n \n \n \n \n \n\n\nHowever, all of the attributes of each object is displayed in the header. How can I force it to display only the columns that I want to use?\n\nA: gvTable.AutoGenerateColumns = false \nor\n\n\nshould do the trick.\n\nA: Set the attribute on your gridview:\nAutoGenerateColumns=\"false\"\n\n\nA: You need to set the AutoGenerateColumns property on the grid to false.\n\nA: Have you tried AutoGenerateColumns=\"false\" in the gridview?\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/1922927", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: iOS Build Error: missing file Icon102.png I have a Xamarin Forms App running on Android and iOS. Everything works fine on a Simulator and on lokal devices.\nWhen I push the Buid to AppCenter, the Android Version gets build without a problem, but the iOS Build alsways fails with the following error:\n(_CoreCompileImageAssets target) -> /Users/runner/runners/2.165.1/work/1/s/O365Info/O365Info.iOS/Assets.xcassets/AppIcon.appiconset/Icon1024.png : error : File not found: /Users/runner/runners/2.165.1/work/1/s/O365Info/O365Info.iOS/Assets.xcassets/AppIcon.appiconset/Icon1024.png [/Users/runner/runners/2.165.1/work/1/s/O365Info/O365Info.iOS/O365Info.iOS.csproj]\n24 Warning(s)\n1 Error(s)\n\nTime Elapsed 00:01:01.73\n[error]Xamarin.iOS task failed with error Error: /Library/Frameworks/Mono.framework/Versions/6_6_1/bin/msbuild failed with return code: 1. For guidance on setting up the build definition, see https://go.microsoft.com/fwlink/?LinkId=760847.\n[section]Finishing: Build Xamarin.iOS solution.\nIn the first builds I didn't even had a Iconset called AppIcon.appiconset (my Iconset was named appiconset1) and the whole project didn't include a file named \"Icon1024.png\".\nI then renamed my Iconset to appioconset and included a file named \"Icon1024.png\", but I'm still getting the same error.\nNo ideas, where this error might come from. Any suggestions?\n\nA: Copied From ColeX at:\nhttps://forums.xamarin.com/discussion/179775/build-error-with-missing-file-icon1024-png\n\n\n*\n\n*Edit csproj file to remove the bogus entries (just delete them)\n\n*Ensure that a 1024*21024 png icon (file does not have Alpha or transparent) add into Assets.xcassets \n\n*Ensure the 1024 file information included in csproj file \n\n\nRefer\nWhere to find 'Missing Marketing Icon'\nhttps://forums.xamarin.com/discussion/129252/problems-with-missing-appicons-files\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/60660242", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}} {"text": "Q: What really happens internally when an update happens on a record with indexed column in sql server I know that when a table has indexed column(s), sql server duplicates the data of these columns so that it can be accessed fast without looking through every record. And if the index is covered with other columns then all these included columns are also stored along with the indexed columns. \nSo, I am assuming when an update happens on any of the indexed columns or included columns then it is obvious that the update should happen in both the actual record location and the index location. This point looks interesting to me because if a table is expected to have more updates than searches, then wouldn't it be overhead to have the index? I wanted to confirm on this and also would like to know the internals on what actually happens behind the screen when a update happens.\n\nA: Yes, you have it correct. There is a trade-off when adding indexes. They have the potential to make selects faster, but they will make updates/inserts/deletes slower.\n\nA: When you design an index, consider the following database guidelines:\n\n\n*\n\n*Large numbers of indexes on a table affect the performance of INSERT, UPDATE, DELETE, and MERGE statements because all indexes must be adjusted appropriately as data in the table changes. For example, if a column is used in several indexes and you execute an UPDATE statement that modifies that column's data, each index that contains that column must be updated as well as the column in the underlying base table (heap or clustered index).\n\n*Avoid over-indexing heavily updated tables and keep indexes narrow, that is, with as few columns as possible.\n\n*Use many indexes to improve query performance on tables with low update requirements, but large volumes of data. Large numbers of indexes can help the performance of queries that do not modify data, such as SELECT statements, because the query optimizer has more indexes to choose from to determine the fastest access method.\n\n*Indexing small tables may not be optimal because it can take the query optimizer longer to traverse the index searching for data than to perform a simple table scan. Therefore, indexes on small tables might never be used, but must still be maintained as data in the table changes.\n\n\nFor more information have a look at the below link:-\nhttp://technet.microsoft.com/en-us/library/jj835095(v=sql.110).aspx\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/23999689", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: How do I clear an array in the state of my Redux store? I am building a small e-commerce shop and I am trying to clear my cart after a successful checkout. The cart contains cartItems which are stored in the Redux store. I am getting the console log in my function in the StripeCheckoutForm component and the action creator.\nI am not seeing the console log for the reducer so I suspect something is wrong with my action creator. I am not sure about best practices concerning action creators. I was wondering when, why, and how to use dispatch in the action creator. The docs for Redux aren't exactly clear for me.\nHere is my StripeCheckout:\nimport React, {Component} from 'react';\nimport { CardElement, injectStripe } from 'react-stripe-elements';\nimport { connect } from 'react-redux';\nimport { Link } from 'react-router-dom';\nimport { clearCart } from '../actions/clearCartAction';\nimport getTotal from '../helpers/getTotalHelper';\nimport { Container, Col, Form, FormGroup, Input } from 'reactstrap';\nimport './StripeCheckoutForm.css';\n\nconst cardElement = {\n base: {\n color: '#32325d',\n width: '50%',\n lineHeight: '30px',\n fontFamily: '\"Helvetica Neue\", Helvetica, sans-serif',\n fontSmoothing: 'antialiased',\n fontSize: '18px',\n '::placeholder': {\n color: '#aab7c4'\n }\n },\n invalid: {\n color: '#fa755a',\n iconColor: '#fa755a'\n }\n};\n\nconst FIREBASE_FUNCTION = 'https://us-central1-velo-velo.cloudfunctions.net/charge/';\n\n// Function used by all three methods to send the charge data to your Firebase function\nasync function charge(token, amount, currency) {\n const res = await fetch(FIREBASE_FUNCTION, {\n method: 'POST',\n body: JSON.stringify({\n token,\n charge: {\n amount,\n currency,\n },\n }),\n });\n const data = await res.json();\n data.body = JSON.parse(data.body);\n return data;\n}\n\nclass CheckoutForm extends Component {\n constructor(props) {\n super(props);\n this.submit = this.submit.bind(this);\n }\n\n state = {\n complete: false\n }\n\n clearCartHandler = () => {\n console.log('clearCartHandler');\n this.props.onClearCart()\n }\n\n // User clicked submit\n async submit(ev) {\n console.log(\"clicked!\")\n const {token} = await this.props.stripe.createToken({name: \"Name\"});\n const total = getTotal(this.props.cartItems);\n const amount = total; // TODO: replace with form data\n const currency = 'USD';\n const response = await charge(token, amount, currency);\n\n if (response.statusCode === 200) {\n this.setState({complete: true});\n console.log('200!!',response);\n this.clearCartHandler();\n\n } else {\n alert(\"wrong credit information\")\n console.error(\"error: \", response);\n }\n }\n\n render() {\n\n if (this.state.complete) {\n return (\n
    \n

    Purchase Complete

    \n \n \n \n
    \n );\n }\n\n return ( \n
    \n \n

    Let's Checkout

    \n
    \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    \n \n
    \n
    \n \n
    \n
    \n );\n }\n}\n\nconst mapStateToProps = state => {\n return {\n cartItems: state.shoppingCart.cartItems\n }\n}\n\nconst mapDispatchToProps = state => {\n return {\n onClearCart: () => (clearCart())\n }\n}\n\nexport default connect(mapStateToProps, mapDispatchToProps)(injectStripe(CheckoutForm)); \n\nHere is my action creator:\nimport { CLEAR_CART } from './types';\n\n// export const clearCart = (dispatch) => { \n// console.log('clear_action')\n// dispatch({\n// type: CLEAR_CART,\n// }) \n// } \n\nexport function clearCart() {\n console.log('clear_action')\n return { \n type: CLEAR_CART\n }\n}\n\nand finally my reducer:\nimport {ADD_TO_CART} from '../actions/types';\nimport {REMOVE_FROM_CART} from '../actions/types';\nimport {CLEAR_CART} from '../actions/types';\n\nconst initialState = {\n cartItems: [],\n}\n\nexport default function(state = initialState, action) {\n switch(action.type) {\n case ADD_TO_CART:\n console.log('ADD_reducer');\n return {\n ...state,\n cartItems: [...state.cartItems, action.payload],\n }\n case REMOVE_FROM_CART:\n console.log('REMOVE_REDUCER', action.payload, state.cartItems);\n return {\n ...state,\n cartItems: state.cartItems.filter(item => item.id !== action.payload.id)\n }\n case CLEAR_CART:\n console.log('CLEAR_REDUCER');\n return {\n ...state,\n cartItems: []\n }\n default:\n return state;\n }\n}\n\n\nA: Action has to be dispatched like below. Let me know if it works\nconst mapDispatchToProps = (dispatch) => {\n return {\n onClearCart: () => (dispatch(clearCart()))\n }\n};\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/53989718", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "2"}} {"text": "Q: Como mudar a cor do texto fora de uma fun\u00e7\u00e3o Tkinter? Estou tentando mudar a cor de um texto fora de uma fun\u00e7\u00e3o com Tkinter. J\u00e1 tentei colocar o Label dentro da fun\u00e7\u00e3o mas fica sobrescrevendo um texto sobre o outro.\nSegue o c\u00f3digo.\nfrom tkinter import *\nfrom tkinter import ttk\nimport tkinter as tk\n\nvar_35='black'\nfg1='black'\n\nmaster = Tk()\nmaster.geometry('850x700')\nmaster.title('Vias Size')\n\n\nw = Canvas(master, width=600, height=400, bg='white')\nw.grid(row=20,column=0, columnspan=10)\n\n\n\ndef Solve():\n global fg1\n wth = int(cth.get())\n fg1='black'\n ring = \"Ring size = %d \u00b5m\" % (wth)\n if wth>120:\n fg1 = 'orange'\n print (fg1)\n var12.set(ring)\n elif wth>80:\n fg1= 'red'\n print (fg1)\n var12.set(ring)\n else:\n print (fg1)\n var12.set(ring)\n\n\nvar_1=StringVar()\nLabel_10 = Label(master, textvariable = var_1,font=('Arial',15),padx=5).grid(row=1,column=0, columnspan=5)\n\nvar12=StringVar()\nprint(fg1)\nLabel_12 = tk.Label(master, textvariable=var12, font=('Arial',12),padx=5, fg=fg1, bg='white').place(x=80, y=440)\n\n\nButton(master, text='Solve',font=('Arial',14), command=Solve).grid(row=10,column=7, columnspan=1)\n\ncth = ttk.Combobox(master, values=('25','35', '50','100', '150', '200'),font=('Arial',12) ,width=8)\ncth.current(0)\ncth.grid(row=6,column=3, columnspan=1)\n\nmainloop()\n\n\n\nA: Ol\u00e1, tudo bem?\nBom primeiro temos que resolver um problema no c\u00f3digo acima...\nVoc\u00ea atribuiu a vari\u00e1vel Label_12 a instancia de um Label j\u00e1 com o place, isso impossibilita voc\u00ea a trabalhar com as propriedades do Label, ent\u00e3o primeiro voc\u00ea instancia o Label e depois realiza o place\n Label_12 = tk.Label(master, textvariable=var12, font=('Arial',12),padx=5, fg=fg1, bg='white')\n Label_12.place(x=80, y=440)\n\nAgora dentro da fun\u00e7\u00e3o aplique o seguinte comando:\n **Label_12['foreground'] = fg1**\n\nAssim voc\u00ea altera a cor de acordo com o par\u00e2metro da fun\u00e7\u00e3o....\no seu c\u00f3digo ficaria assim:\n#########################################################\n\n#########################################################\nUma outra dica, evite usar vari\u00e1vel global, isso pode te causar alguns problemas para voc\u00ea, aplique a vari\u00e1vel como par\u00e2metro da fun\u00e7\u00e3o, ficaria melhor\nEspero ter ajudado.\n", "meta": {"language": "pt", "url": "https://pt.stackoverflow.com/questions/516343", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}} {"text": "Q: Zoomable fullscreen image in portrait and landscape mode I am a beginner at programming. I have an app where you can tap into any of the images that are on display to show that image in full-screen mode and can pinch to zoom. The issue I am having is that if you rotate the phone then the image is only half visible.\nI'm using a scroll view to achieve the zoom functionality as that seems to be the consensus of the best way to do it.\nIt works perfectly in portrait mode, or if I enter the fullscreen image while the app is already in landscape orientation, but If I go into the landscape while in the fullscreen image that's where it goes wrong. Here is the code:\nclass PictureDetailViewController: UIViewController, UIScrollViewDelegate {\n\n@IBOutlet weak var scrollView: UIScrollView!\nvar routeData = IndividualRoute(numberOfRoute: UserDefaults.standard.integer(forKey: \"currentRoute\"))\n\nvar detailPicture = UserDefaults.standard.bool(forKey: \"segueFromDetailvc\")\n\nvar detailImage = UIImageView()\n\noverride func viewDidLoad() {\n super.viewDidLoad()\n\n routeData.routesValues()\n scrollView.delegate = self\n selectImage()\n scrollView.frame = UIScreen.main.bounds\n scrollView.addSubview(detailImage)\n scrollViewContents()\n setupConstraints()\n let scrollViewFrame = scrollView.frame\n let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width\n let scaleHieght = scrollViewFrame.size.height / scrollView.contentSize.height\n let minScale = min(scaleHieght, scaleWidth)\n scrollView.minimumZoomScale = minScale\n scrollView.maximumZoomScale = 1\n scrollView.zoomScale = minScale\n let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreen))\n tap.numberOfTapsRequired = 2\n view.addGestureRecognizer(tap)\n\n}\n\n//****************************************\n\n//Image Setup\n\nfunc setupConstraints() {\n\n scrollView.translatesAutoresizingMaskIntoConstraints = false\n\n NSLayoutConstraint.activate([\n scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),\n scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),\n scrollView.topAnchor.constraint(equalTo: view.topAnchor),\n scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),\n scrollView.centerXAnchor.constraint(equalTo: view.centerXAnchor),\n scrollView.centerYAnchor.constraint(equalTo: view.centerYAnchor)])\n\n scrollView.contentSize = (detailImage.image?.size)!\n\n\n}\n\nfunc selectImage() {\n if !detailPicture {\n let foo = \"\\(routeData.achievements[UserDefaults.standard.integer(forKey: \"currentAchievement\")])\"\n detailImage.image = UIImage(named: \"\\(foo.folding(options: .diacriticInsensitive, locale: nil)) 0\")\n } else {\n let foo = \"\\(routeData.achievements[0])\"\n detailImage.image = UIImage(named: \"\\(foo.folding(options: .diacriticInsensitive, locale: nil)) 0\")\n print(\"\\(foo.folding(options: .diacriticInsensitive, locale: nil)) 0\")\n }\n\n guard let width = detailImage.image?.size.width else {\n return\n }\n guard let height = detailImage.image?.size.height else {\n return\n }\n\n let frame: CGRect = CGRect(x: 0, y: 0, width: width, height: height)\n detailImage.frame = frame\n detailImage.isUserInteractionEnabled = true\n\n}\n\n//**************************************\n\n//Scrollview setup\n\n\n@objc func dismissFullscreen(){\n scrollView.setZoomScale(1, animated: true)\n}\n\nfunc scrollViewContents() {\n\n let boundSize = UIScreen.main.bounds.size\n var contentFrame = detailImage.frame\n\n if contentFrame.size.width < boundSize.width {\n contentFrame.origin.x = (boundSize.width - contentFrame.size.width) / 2\n } else {\n contentFrame.origin.x = 0\n }\n if contentFrame.size.height < boundSize.height {\n contentFrame.origin.y = (boundSize.height - contentFrame.size.height) / 2\n } else {\n contentFrame.origin.y = 0\n }\n\n detailImage.frame = contentFrame\n\n}\n\nfunc scrollViewDidZoom(_ scrollView: UIScrollView) {\n scrollViewContents()\n}\n\nfunc viewForZooming(in scrollView: UIScrollView) -> UIView? {\n\n return detailImage\n}\n\nSorry for posting so much code but its pretty much all relevant (I think).\nHere are screenshots of the problem:\n\n\n\nA: Okay, I've managed to fix it! Had a little jump around with delight.\nI set up a new function called setupScale() that is called in viewdidload when the view is presented. I also added the viewwillLayoutSubview() override and called the setupScale() function inside it.\nIf looks like this:\nprivate func setupScale() {\n\n scrollView.frame = UIScreen.main.bounds\n scrollView.contentSize = (detailImage.image?.size)!\n scrollViewContents()\n let scrollViewFrame = scrollView.frame\n let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width\n let scaleHieght = scrollViewFrame.size.height / scrollView.contentSize.height\n let minScale = min(scaleHieght, scaleWidth)\n scrollView.minimumZoomScale = minScale\n scrollView.maximumZoomScale = 1\n scrollView.zoomScale = minScale\n}\noverride func viewWillLayoutSubviews() {\n setupScale()\n}\n\nResults look perfect on my iPad and iPhone 7 in landscape and portrait.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/47354076", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: EXEC master.sys.sp_MSforeachdb error when looping through databases I am getting the following the error when executing the statement:\nEXEC master.sys.sp_MSforeachdb \n 'INSERT INTO AuditDatabase.dbo.[DataDictionary] \n exec sp_get_extendedproperty use [?] \"?\"'\n\nMsg 102, Level 15, State 1, Line 23\nIncorrect syntax near 'master'.\nMsg 102, Level 15, State 1, Line 23\nIncorrect syntax near 'tempdb'.\nMsg 102, Level 15, State 1, Line 23\nIncorrect syntax near 'model'.\nMsg 102, Level 15, State 1, Line 23\nIncorrect syntax near 'msdb'.\nMsg 102, Level 15, State 1, Line 23\nIncorrect syntax near 'AdventureWorks2014'.\nMsg 102, Level 15, State 1, Line 23\nIncorrect syntax near 'TestDatabase'.\nMsg 102, Level 15, State 1, Line 23\nIncorrect syntax near 'AuditDatabase'.\n\nIf I run it without the use syntax like this:\nEXEC master.sys.sp_MSforeachdb \n 'INSERT INTO AuditDatabase.dbo.[DataDictionary] \n exec sp_get_extendedproperty \"?\"'\n\nIt only loops through the AdventureWorks2014 and msdb databases. It does not loop through any other database.\nsp_get_extendedproperty is on master db.\n\nA: The use statement is in the wrong place. Try something like this:\nI\n exec sp_MSforeachdb 'use ? rest of statement here '\nI just executed this and it worked fine:\nexec sp_MSforeachdb 'use ? select * from sys.objects;'\n\nIf your proc is name sp_xxx and is in master it should be available in all databases.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/29436928", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}} {"text": "Q: Find prev element source I know this code below doesn't work, but is it possible with a call to get the \"src\" from the prev, with a little tweak to the jquery below?\nHTML:\n
  • \n \n \n \n \n \n
  • \n\nJquery: \n$(\".chooseTheme\").click(function () { \n var src = $(\".chooseTheme\").find(\"img\");\n alert(src.text());\n});\n\n\nA: $(\".chooseTheme\").click(function () { \n var src = $(this).closest('li').find(\"img\").attr('src');\n alert(src);\n});\n\n\nA: $(\".chooseTheme\").click(function () { \n var src = $(\"li\").find(\"img\").attr('src');\n alert(src);\n\n});\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/16529591", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: What should be passed as input parameter when using train-test-split function twice in python 3.6 Basically i wanted to split my dataset into training,testing and validation set. I therefore have used train_test_split function twice. I have a dataset of around 10-Million rows. \nOn the first split i have split training and testing dataset into 70-Million training and 30-Million testing. Now to get validation set i am bit confused whether to use splitted testing data or training data as an input parameter of train-test-split in order to get validation set. Give some advise. TIA\nX = features \ny = target \n\n# dividing X, y into train and test and validation data 70% training dataset with 15% testing and 15% validation set \n\nfrom sklearn.model_selection import train_test_split \n\n#features and label splitted into 70-30 \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) \n\n#furthermore test data is splitted into test and validation set 15-15\nx_test, x_val, y_test, y_val = train_test_split(X_test, y_test, test_size=0.5)\n\n\nA: Don't make a testing set too small. A 20% testing dataset is fine. It would be better, if you splitted you training dataset into training and validation (80%/20% is a fair split). Considering this, you shall change your code in this way:\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) \n\n\nx_test, x_val, y_test, y_val = train_test_split(X_train, y_train, test_size=0.25)\n\n\nThis is a common practice to split a dataset like this.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/56099495", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Initialize a multidimensional array of JButtons declared in a different class using get method I have to create a battleship game where there is a multidimensional array of JButtons to denote the player grid. I am supposed to initialize the JButtons in the main UI class but they need to be declared in a separate class holding the player grid. I have tried this to add the buttons: \nfor(int i = 0; i <= 10; i++){\n for(int j = 0; j <= 10; j++){\n playerOnePanel.add(playerOne.getBoard()); \n }\n } \n\nBut this returns a null pointer exception. The class I'm trying to reference is:\npublic class Player {\n private Color shipColor;\n private String userName;\n private boolean isFirst;\n private JButton[][] buttonBoard = new JButton[rows][cols];\n private final static int rows = 10;\n private final static int cols = 10;\n\n public Player(String name){\n initComponents();\n }\n\n private void initComponents(){\n for(int i = 0; i <= rows; i++){\n for(int j = 0; j <= cols; j++){\n buttonBoard[i][j] = new JButton();\n }\n }\n }\n\n public JButton[][] getBoard(){\n return buttonBoard;\n } \n}\n\nAnd the code I want to use the object in is:\npublic class BattleshipUI extends JFrame {\n private JMenuBar menuBar; \n private JMenu gameMenu;\n private JMenu optionMenu;\n private JMenuItem playerPlayer;\n private JMenuItem playerComputer;\n private JMenuItem computerComputer; \n private JMenuItem exit; \n private JMenuItem game;\n private JMenuItem player;\n private JButton deploy;\n private JPanel shipLayoutPanel;\n private JPanel playerOnePanel;\n private JComboBox shipCb;\n private JComboBox directionCb;\n // Data arrays for various components on the UI\n private String[] rowLetters = {\" \",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\"};\n private String[] columnNumbers = {\" \",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\"};\n private String[] ships = {\"Carrier\",\"Battleship\",\"Submarine\",\"Destroyer\", \"Patrol Boat\"};\n private String[] direction = {\"Horizontal\",\"Vertical\"};\n private static final int PLAYER_ONE = 0;\n private static final int PLAYER_TWO = 1;\n private Player playerOne;\n private Player playerTwo;\n private Player[] players = new Player[2];\n private Color[] color = {Color.cyan, Color.green, Color.yellow, Color.magenta, Color.pink, Color.red, Color.white};\n\n public BattleshipUI(){\n initComponents();\n initObjects();\n }\n\n public BattleshipUI getThisParent(){\n return this;\n }\n\n private void initObjects(){\n playerOne = new Player(\"Player One\");\n playerTwo = new Player(\"Player Two\");\n players[1] = playerOne;\n players[2] = playerTwo;\n }\n\n private void initComponents(){\n this.setTitle(\"Battleship\");\n this.setDefaultCloseOperation(EXIT_ON_CLOSE);\n this.setPreferredSize(new Dimension(500,500));\n this.setMinimumSize(new Dimension(500,500));\n\n menuBar = new JMenuBar();\n gameMenu = new JMenu(\"Game\");\n optionMenu = new JMenu(\"Option\");\n menuBar.add(gameMenu);\n menuBar.add(optionMenu);\n\n playerPlayer = new JMenuItem(\"Player vs. Player\");\n playerComputer = new JMenuItem(\"Player vs. Computer\");\n computerComputer = new JMenuItem(\"Computer vs. Computer\");\n exit = new JMenuItem(\"Exit\");\n gameMenu.add(playerPlayer);\n gameMenu.add(playerComputer);\n gameMenu.add(computerComputer);\n gameMenu.add(exit);\n playerPlayer.setEnabled(false);\n computerComputer.setEnabled(false);\n\n game = new JMenuItem(\"Game Options\");\n player = new JMenuItem(\"Player Options\");\n optionMenu.add(game);\n optionMenu.add(player);\n\n shipLayoutPanel = new JPanel();\n shipLayoutPanel.setBorder(BorderFactory.createTitledBorder(\"Select Ship and Direction\"));\n\n shipCb = new JComboBox(ships);\n directionCb = new JComboBox(direction);\n deploy = new JButton(\"DEPLOY\");\n deploy.setEnabled(false);\n\n shipLayoutPanel.add(shipCb);\n shipLayoutPanel.add(directionCb);\n shipLayoutPanel.add(deploy); \n\n playerOnePanel = new JPanel(new GridLayout(11,11));\n playerOnePanel.setMinimumSize(new Dimension(400,400));\n playerOnePanel.setPreferredSize(new Dimension(400,400));\n playerOnePanel.setBorder(BorderFactory.createTitledBorder(\"Player One\"));\n\n for(int i = 0; i <= 10; i++){\n for(int j = 0; j <= 10; j++){\n playerOnePanel.add(playerOne.getBoard()); \n }\n } \n\n this.setJMenuBar(menuBar);\n this.add(shipLayoutPanel, BorderLayout.NORTH);\n this.add(playerOnePanel, BorderLayout.WEST);\n this.setVisible(true);\n }\n}\n\nIs there a way to do this? I need to use the methods and variables listed. \n\nA: You seem to initialize the players (and their boards respectively) after trying to add their board to a panel, which is impossible since you did not create the players yet. \n public BattleshipUI(){\n initComponents(); //Here you try to add the board of a player\n initObjects(); //Here you initialize the players (ergo nullpointer)\n }\n\n private void initComponents(){\n for(int i = 0; i <= 10; i++){\n for(int j = 0; j <= 10; j++){\n //playerOne is not instantiated yet\n playerOnePanel.add(**playerOne**.getBoard()); \n }\n } \n }\n\n private void initObjects(){\n **playerOne** = new Player(\"Player One\");\n playerTwo = new Player(\"Player Two\");\n players[1] = playerOne;\n players[2] = playerTwo;\n}\n\n\nA: Another thing I see is: You are trying to add a multi-dimensional JButton-Array at once to the JPanel. I think this will not work (please correct me if i am wrong). You have to do this Button by Button:\nJButton[][] board = playerOne.getBoard();\nfor(int i=0;i\n ');\">\n\n\n\n\nIs it possible to include PHP code within a section of JavaScript? Because I need to get the ID of the selected \u2018href\u2019 that I clicked. I am trying to include the PHP code in the above JavaScript function but it doesn\u2019t work.\n\nA: PHP runs on the server, generates the content/HTML and serves it to the client possibly along with JavaScript, Stylesheets etc. There is no concept of running some JS and then some PHP and so on.\nYou can however use PHP to generate the required JS along with your content.\nThe way you've written it won't work.\n\nFor sending the value of clicked_tag to your server, you can do something like (using jQuery for demoing the logic)\nfunction show_region(chosen_region_id) {\n ...\n $.post('yourserver.com/getclickedtag.php', \n {clicked_tag: chosen_region_id}, \n function(data) { ... });\n ...\n}\n\n\nA: In your script the variable chosen_region_id is already in the function so you don't really need to declare it again with PHP.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/13784380", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: unique form field validation in extjs4 Is there a cleaner way to define unique form field in extjs. Below is a sample code that is checking on client UID on client creation/edition. This code is working but has some bugs - for example on client creation if you enter a value that is already present in DB validator returns true until you unfocus the field.\nExt.define('AM.view.client.UniqueField', {\n extend: 'Ext.form.field.Text',\n alias : 'widget.uniquefield',\n\n vtype: 'UniqueUid',\n\n initComponent: function() {\n\n Ext.apply(Ext.form.field.VTypes, {\n\n UniqueUidMask : /[0-9]/i,\n UniqueUid : function(val,field) {\n if (val.length < 9) {\n Ext.apply(Ext.form.field.VTypes, {\n UniqueUidText: 'Company ID is too small'\n });\n return false;\n } else {\n var paste=/^[0-9_]+$/;\n if (!paste.test(val)) {\n Ext.apply(Ext.form.field.VTypes, {\n UniqueUidText: 'Ivalid characters'\n });\n return false;\n } else {\n\n var mask = new Ext.LoadMask(field.up('form'),{msg:'Please wait checking....'}); \n mask.show();\n var test= 0;\n var store = Ext.create('AM.store.Clients');\n store.load({params:{'uid':val, 'id': Ext.getCmp('client_id').getValue()}});\n store.on('load', function(test) {\n mask.hide();\n if(parseInt(store.getTotalCount())==0){\n this.uniqueStore(true);\n }else{\n Ext.apply(Ext.form.field.VTypes, {\n UniqueUidText: 'Company ID is already present'\n });\n this.uniqueStore(false);\n }\n },this)\n\n return true; \n }\n }}\n },this); \n\n\n this.callParent(arguments);\n\n },\n\n uniqueStore: function(is_error){\n\n Ext.apply(Ext.form.field.VTypes, {\n UniqueUidMask : /[0-9]/i,\n UniqueUid : function(val,field) {\n if (val.length < 9) {\n Ext.apply(Ext.form.field.VTypes, {\n UniqueUidText: 'Company ID is too small'\n });\n return false;\n } else {\n var paste=/^[0-9_]+$/;\n if (!paste.test(val)) {\n Ext.apply(Ext.form.field.VTypes, {\n UniqueUidText: 'Ivalid characters'\n });\n return false;\n } else {\n\n var mask = new Ext.LoadMask(field.up('form'),{msg:'Please wait checking....'}); \n mask.show();\n\n var store = Ext.create('AM.store.Clients');\n store.load({params:{'uid':val, 'id': Ext.getCmp('client_id').getValue()}});\n store.on('load', function(test) {\n mask.hide();\n if(parseInt(store.getTotalCount())==0){\n this.uniqueStore(true);\n }else{\n this.uniqueStore(false);\n }\n },this)\n\n return is_error; \n }\n }}\n },this); \n\n }\n\n});\n\n\nA: How about using server side validation?\nI answered to similar issue here: extjs4 rails 3 model validation for uniqueness\nObviously you can change it to use \"ajax\" instead of \"rest\" proxy.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/6321468", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Is it possible to set the initial topic assignments for scikit-learn LDA? Instead of setting the topic_word_prior as a parameter, I would like to initialize the topics according to a pre-defined distribution over words. How would I set this initial topic distribution in sklearn's implementation? If it's not possible, is there a better implementation to consider?\n\nA: If you have a predefined distribution of words in a pre-trained model you can just pass a bow_corpus through that distribution as a function. Gensims LDA and LDAMallet can both be trained once then you can pass a new data set through for allocation without changing the topics. \nSteps:\n\n\n*\n\n*Import your data\n\n*Clean your data: nix punctuation, numbers, lemmatize, remove stop-words, and stem\n\n*Create a dictionary\ndictionary = gensim.corpora.Dictionary(processed_docs[:])\ndictionary.filter_extremes(no_below=15, no_above=0.5, keep_n=100000)\n\n\n*Define a bow corpus\nbow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs]\n\n\n*Train your model - skip if it's already trained\nldamallet = gensim.models.wrappers.LdaMallet(mallet_path, \n corpus=bow_corpus, num_topics=15, id2word=dictionary)\n\n\n*Import your new data and follow steps 1-4\n\n*Pass your new data through your model like this:\n ldamallet[bow_corpus_new[:len(bow_corpus_new)]]\n\n\n*Your new data is allocated now and you can put it in a CSV\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/55753444", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Why I should add '&' before the parameter which is an unordered_map? unordered_map::iterator findElement(unordered_map &intString, int index){\n return intString.find(index);\n}\n\nIf I don't add the & before the intString, the code will crash.\n\nA: The & in the type for the function-parameter intString means that the function gets a reference to the passed argument, instead of a copy of it.\nThus, the iterator which is returned from .find() and which it returns in turn will point into the passed argument, instead of being a dangling iterator pointing somewhere into a no longer existing copy.\nAnd accessing destroyed objects, especially if the memory was re-purposed, can have all kinds of surprising results, which is why it is called Undefined Behavior (UB).\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/49397062", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Call Python google cloud endpoint api from android At this point I have created a python app-engine endpoint api called paper (as also noted in the app.yaml) file. I have placed all the jars, including the \u2026-java-1.13.2-beta-sources.jar file, in the libs directory of my android project. How do I call one of my web services (aka endpoint methods)? As in I don't know the name of the package that would lead me to the api, which in the python backend is simply class PageApi(remote.Service):. Imagine the paper api has a method called countPages(self):. How would I call the service? I have already tried importing import com.appspot.api.services.[etc] but eclipse does not see the importing path.\nEDIT:\nI reload the api. I check that everything looks okay on api explorer. Then I found two packages that seem to be my packages -- except they contain no classes at all.\nimport com.google.api.services.page.*;\nimport com.google.api.services.page.model.*;\n\nIf they are indeed the packages, why would the classes be missing?\n\nA: First. Once you have your projects setup correctly then the same wizard that generated your client library will copy it to your Android project and extra the source files. then you will find the packages you need in the endpoint-libs folders in your project explorer. Take a look at this post for tips on getting that working.\nThen you invoke an endpoint using Android code like this:\nfinal HttpTransport transport = AndroidHttp.newCompatibleTransport();\nJsonFactory jsonFactory = new JacksonFactory();\n\nendpointname.Builder builder = new endpointname.Builder( transport, jsonFactory, null ); \nbuilder.setApplicationName( appName );\n\nendpointname service = builder.build();\n\ntry {\n response = service.methodName( parameters ).execute();\n} catch (IOException e) {\n Log.e(...);\n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/15622779", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "4"}} {"text": "Q: Skype doesn't work Ubuntu 18.04 I have installed skype with the following command:\nsudo snap install skype --classic\nthe problem is when I want to open it, it doesn't work and automatically sign off. Even this happen writting skype on the terminal.\n\nA: Try to remove your snap installation using this command\nsudo snap remove skype\n\nthen download the .deb file from Official Skype website.\nThen install it using dpkg for ex:\ndpkg -i /path-to-/deb-file.deb\n\nNote: check this answer for more information about snap.\n", "meta": {"language": "en", "url": "https://askubuntu.com/questions/1117503", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Upload de arquivos (imagens) em ASP.net n\u00e3o envia a imagem Eu n\u00e3o consigo enviar imagens (banners) na minha aplica\u00e7\u00e3o asp.net\nMeu controller :\n [HttpPost]\n [ValidateAntiForgeryToken]\n [ValidateInput(false)]\n public ActionResult Save([Bind(Include = \"BannerId,DatHorLan,Tit,Atv\")] Banner banner)\n {\n try\n {\n banner.DatHorLan = DateTime.Now;\n banner.UsuarioId = 1;\n if (ModelState.IsValid)\n {\n // Se foi enviado um arquivo com mais do que 0 bytes:\n if (banner.File != null && banner.File.ContentLength > 0)\n {\n // Extraindo nome do arquivo\n var fileName = Path.GetFileName(banner.File.FileName);\n\n var path = Path.Combine(Server.MapPath(\"/Uploads/Img/Banners\"), fileName);\n banner.File.SaveAs(path);\n\n banner.Img = fileName;\n ModelState.Remove(\"Img\");\n }\n if (banner.BannerId == 0)\n {\n banner.DatHorLan = DateTime.Now;\n db.Banners.Add(banner);\n }\n else\n {\n db.Entry(banner).State = EntityState.Modified;\n }\n db.SaveChanges();\n ViewBag.Message = \"Registro gravado com sucesso.\";\n }\n }\n catch (DataException)\n {\n ViewBag.Message = \"Ocorreu um erro ao gravar o registro.\";\n }\n return View(\"Form\", banner);\n }\n\nMeu Model :\n[Table(\"Banners\")]\npublic class Banner\n{\n [Key]\n [Column(\"BannerId\")]\n [Display(Name = \"Banner\")]\n public int BannerId { get; set; }\n\n [Required]\n [Column(\"Tit\")]\n [Display(Name = \"T\u00edtulo\")]\n public string Tit { get; set; }\n\n [Required]\n [Column(\"Atv\")]\n [Display(Name = \"At\u00edvo\")]\n public int Atv { get; set; }\n\n [Column(\"Img\")]\n [Display(Name = \"Imagem\")]\n public string Img { get; set; }\n\n [Display(Name = \"Imagem\")]\n [NotMapped]\n public HttpPostedFileBase File { get; set; }\n\n [Column(\"DatHorLan\")]\n [Display(Name = \"Data/Hora\")]\n [DisplayFormat(DataFormatString = \"{0:dd/MM/yyyy hh:mm:ss}\", ApplyFormatInEditMode = true)]\n public DateTime DatHorLan { get; set; }\n\n [Column(\"UsuarioId\")]\n [Display(Name = \"Usu\u00e1rio\")]\n public int UsuarioId { get; set; }\n [Display(Name = \"Usu\u00e1rio\")]\n public virtual Usuario Usuario { get; set; }\n\n}\n\nO meu HTML (View)\n@model FiscoCorretora.Areas.Admin.Models.Banner\n\n@{\n ViewBag.Title = \"P\u00e1ginas\";\n Layout = \"~/Areas/Admin/Views/Shared/_Layout.cshtml\";\n}\n\n
    \n
    \n @if (Model.BannerId == 0)\n {\n

    Banner - Novo

    \n }\n else\n {\n

    Banner - Alterando

    \n }\n
    \n @using (Html.BeginForm(\"save\",\"banners\", FormMethod.Post, new { enctype = \"multipart/form-data\" }))\n {\n @Html.AntiForgeryToken()\n\n @Html.ValidationSummary(true, \"\", new { @class = \"text-danger\" })\n\n @Html.HiddenFor(model => model.BannerId)\n @Html.HiddenFor(model => model.DatHorLan)\n\n
    \n
    \n
    \n @Html.LabelFor(model => model.Tit, htmlAttributes: new { @class = \"control-label col-md-2\" })\n
    \n @Html.EditorFor(model => model.Tit, new { htmlAttributes = new { @class = \"form-control input-sm\" } })\n @Html.ValidationMessageFor(model => model.Tit, \"\", new { @class = \"text-danger\" })\n
    \n
    \n
    \n @Html.LabelFor(model => model.Atv, htmlAttributes: new { @class = \"control-label col-md-2\" })\n
    \n @Html.DropDownList(\"Atv\", new List\n {\n new SelectListItem{ Text=\"N\u00e3o\", Value = \"0\" },\n new SelectListItem{ Text=\"Sim\", Value = \"1\" }\n }, new { @class = \"form-control\" })\n\n @Html.ValidationMessageFor(model => model.Atv, \"\", new { @class = \"text-danger\" })\n
    \n
    \n
    \n @Html.LabelFor(model => model.File, htmlAttributes: new { @class = \"control-label col-md-2\" })\n
    \n @Html.TextBoxFor(model => model.File, new { type = \"file\", @class = \"form-control\" }) \n @Html.ValidationMessageFor(model => model.File)\n
    \n
    \n \n
    \n
    \n
    \n \n  Voltar\n \n \n
    \n }\n
    \n\n@section Scripts{\n \n}\n\nGrava o registro no banco e tudo mais, porem nao envia a imagem \nNo controle :\nif (banner.File != null && banner.File.ContentLength > 0)\n\nSempre ta nulo !\n\nA: Este form encontra-se dentro de outro form? \nSe sim remova new { enctype = \"multipart/form-data\" } e adicione ao form pai.\n", "meta": {"language": "pt", "url": "https://pt.stackoverflow.com/questions/242378", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Multipeer Connectivity Session in iOS7 I've looked into Apple's documentation but is still uncleared about one thing, the session.\n\n\n*\n\n*When - (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void (^)(BOOL, MCSession *))invitationHandler is called, we need to pass in a session to the invitationHandler. What will happen to this session?\nWhen A invites B to join a session that A created, does B provide a new session to A as well? What is inside B's session? Is it just A alone or does it include all the peers that are currently in A's session? Should B keep track of the session that's been used to accept A's invitation?\nInside this article, http://nshipster.com/multipeer-connectivity/, the tutorial creates a new session on the fly and uses it to accept the invitation, wouldn't you lose the session once the function is ended; thus losing information to connected peers?\n\n*Assuming that B, C and D are all invited by A, and now B wants to send something to C. Is it required that B needs to send the information to A first or can B send the information directly to C?\n\n*According to the Apple's documentation, a single session can only hold no more than 8 peers. Is it possible to make an array of sessions so that you can invite more than 8 people to join your device? If that is the case, does client also need to respond with an array so that it can carry more than 8 peers in its list?\n\n*Assuming A and B are now connected, and A now invites C to join. How does B know that C is now in the session?\nThank you for reading such a long post.\n\nA: There's not much in the way of documentation on Multipeer Connectivity, so these answers are based on my own experiments:\n\n\n*\n\n*There are lots of questions inside this one question, but in a nutshell A's session(s) manage invitations that A has sent or accepted. So if B invites and A accepts, the session that A passes when accepting will then be used in the MCSessionDelegate session: peer: didChangeState: callback to say whether the connection happened. At this point the connectedPeers property of A's session will contain B (if the connection succeeded). The session that B used to send the invitation will also get the same callback once A accepts, and will contain A in connectedPeers. Neither A nor B will have any information on the other's session that managed this connection between them. And yes, if you want to send any data to the newly connected peer, you need to keep a reference to the session that handled the connection. I've yet to see any real advantage in creating a new session for each invitation.\n\n*Based on the above, B has no information on who A is connected to. So if A is connected to B,C and D, the only peer B knows about is the peer that it connected to - A. What Multipeer Connectivity offers here is the ability for B to discover C or D via A. So if the A-B connection was made over WiFi, and A-C over Bluetooth, but B does not have Bluetooth enabled, and C is on a different WiFi network to B, B and C can still discover each other through A. The process of inviting and accepting is still up to B and C to handle though.\n\n*I answered a question about session management here that may be helpful Best option for streaming data between iPhones \n\n*B doesn't know anything about A connecting to C. All B can do is discover C for itself and add C to it's own session.\n\nA: *\n\n*From quickly looking over Chris's answer it seems accurate from what I've been working on at my job.\n\n*I'm currently working on a game using multipeer connectivity and have found that:\n(Assuming everyone is on wifi) if A connects to B and A connects to C, then B will be connected to C and be able to send messages to C.\nthe Multipeer Framework is a P2P framework and automatically connects everyone together.\neven if (as in my current project) you set it up as a Server-client model, all peers will still be connected and you can send messages between B and C without going through A. Depending on what you are doing with your app.\n\n*Go with Chris's answer\n\n*Addressed in #2\nI recommend looking at the example project in the Apple Docs and carefully watch what happens in the debug area when you connect.\nAlso, as a side note:\nScenario:(A is only on wifi),(B is on wifi and bluetooth),(C is on bluetooth only)\n\nif A connects to B via wifi, and B connects to C via bluetooth, A will still be connected to C but you won't be able to send a message from A directly to C because they are on different networks.\n\nA: @SirCharlesWatson:\n\n(Assuming everyone is on wifi) if A connects to B and A connects to C, then B will be connected to C and be able to send messages to C.\nthe Multipeer Framework is a P2P framework and automatically connects everyone together.\n\nMy question is: when B automatically connected to C, will B & C receive a state change notification on the existed session?\n\n*\n\n*A: session:peer:B didChangeState(MCSessionStateConnected)\n\n*B: session:peer:A didChangeState(MCSessionStateConnected)\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/22752700", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "3"}} {"text": "Q: javascript to allow me to collapse accordion that is extended I have a side navigation bar that consists of multiple accordions that when expanded shows more navigation buttons. I have a bit of JavaScript that will only allow one of those accordions to be expanded at a time. However if I click on one accordion to expand it, when I click the same accordion it remain open. \nI would like to get it so that I can expand and collapse the accordion without having to expand another accordion. \nJavaScript:\nvar acc = document.getElementsByClassName(\"nav-link-bottom-main\");\nvar i;\nvar last;\nfor (i = 0; i < acc.length; i++) {\n acc[i].onclick = function() {\n if (last) {\n last.nextElementSibling.classList.toggle(\"show\");\n }\n this.nextElementSibling.classList.toggle(\"show\");\n last = this;\n }\n}\n\nhtml:\n
    \n \n \n\n \n \n\n\nA: It looks like whenever if (last) condition is true and it's the same element as this, you're toggling show class twice on same element, so probably this is why it remains open (actually it closes and opens again at the same time).\nSo try to check if you're not toggling same element like this:\nif (last && last != this) {\n last.nextElementSibling.classList.toggle(\"show\");\n}\nthis.nextElementSibling.classList.toggle(\"show\");\n\nAnd I hope it helps.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/57287743", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: how can i plot series first bar's close price of super trend (long/short)? how can i plot series first bar's close price of super trend (long/short) ?\n//@version=5\nindicator(\"Supertrend\", overlay=true, timeframe=\"\", timeframe_gaps=true)\natrPeriod = input(10, \"ATR Length\")\nfactor = input.float(3.0, \"Factor\", step = 0.01)\n\n[supertrend, direction] = ta.supertrend(factor, atrPeriod)\n\nbodyMiddle = plot((open + close) / 2, display=display.none)\nupTrend = plot(direction < 0 ? supertrend : na, \"Up Trend\", color = color.green, style=plot.style_linebr)\ndownTrend = plot(direction < 0? na : supertrend, \"Down Trend\", color = color.red, style=plot.style_linebr)\n\nfill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)\nfill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)\n\n\nA: var float first_close = 0.\nif barstate.isfirst\n first_close := supertrend\n\n\nA: You will have to save the close price whenever the direction changes into a variable and then you can plot that variable. Example below\n//@version=5 \nindicator(\"Supertrend\", overlay=true, timeframe=\"\", timeframe_gaps=true)\natrPeriod = input(10, \"ATR Length\")\nfactor = input.float(3.0, \"Factor\", step = 0.01)\n\n[supertrend, direction] = ta.supertrend(factor, atrPeriod)\n\nbodyMiddle = plot((open + close) / 2, display=display.none)\nupTrend = plot(direction < 0 ? supertrend : na, \"Up Trend\", color = color.green, style=plot.style_linebr)\ndownTrend = plot(direction < 0? na : supertrend, \"Down Trend\", color = color.red, style=plot.style_linebr)\n\nfill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)\nfill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)\nvar firstbarsclose=close\nif direction<0 and direction[1]>0\n firstbarsclose:=close\nif direction>0 and direction[1]<0\n firstbarsclose:=close\nplot(firstbarsclose,style=plot.style_stepline)\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/73097293", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: I tried several times but still animation is not working, please help me to fix it CSS parts\n\nBlockquote\n\nI was just making a box and apply animation over it, these are respective lines of code\n\n\nBody\nHere it is a box over which I want to apply animation\n\n
    \n BOX\n
    \n\n\n\nA: You are using ms instead of s. Your animation is working, but it finishes so fast that you just can't see it. Therefore, you should give it a longer duration.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/67900854", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}} {"text": "Q: Directional hypothesis testing in linear regression models using SPSS I have an alternative hypothesis which states H1: \"The intelligence quotient (IQ) has a positive effect on school grades\", i.e. $H_{1}: \\beta_{1} < 0$. I am using a linear regression to check whether the slope ($\\beta_{1}$) is statistically significant.\nAs far as I know, SPSS is using a different alternate hypothesis where it checks for inequality, i.e. $H_{1}: \\beta_{1} \\neq 0$\nHow can I now use the result of SPSS and with t-Test and its corresponding p-value of $0.03$, to validate my hypothesis. I am using a significance value of $\\alpha = 0.05$\n", "meta": {"language": "en", "url": "https://stats.stackexchange.com/questions/578918", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Export data from database to sql file with PHP I need to export data (only the data, not the tables nor database) from the database to a SQL file and save it. How to write a PHP function that does that? I want to call this function in specific circumstances when running specific queries (updating a blog post, for example).\nSomething like:\n/*\n* Get the data from the database (already specified) and export it to a SQL file\n*\n* @param string $dir Where to store the SQL file. Must be a full path.\n* @return void\n*/\nfunction export_database_data(string $dir) {\n // some code that gets the data and store it in $data\n // don't know what to do here\n\n // create/update the file\n file_put_contents(\"$dir/data_backup.sql\", $data);\n}\n\nWhy this? \n(You don't need to read the following to help me solve the problem. I'm including this because I'm sure if don't include this, someone will ask it).\nI want to do that because I want to have a backup of the data (only the data; the tables do not matter because I already know how to handle them for backup). \nI'm doing this because I will use the PHP function exec to run git commands and commit the change in the SQL file. The end goal is to keep track of the data in the database, which won't be updated often. I need the data in a SQL file and I aim to use git because it is easy to access and to collaborate with others (I could not think a better solution, and creating my own tracking system would require a lot of work and time).\n\nA: You can run a mysqldump command using PHP exec function to only export data. Ex:\nexec('mysqldump -u [user] -p[pass] --no-create-info mydb > mydb.sql');\n\nMore info:\n\n\n*\n\n*mysqldump data only\n\n*Using a .php file to generate a MySQL dump\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/57632218", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: If $x^* (x)=0$ for all $x^* \\in X^*$, then $x=0$? If $X$ is any arbitrary vector space, and $X^*$ is its dual, is it true that if $x^* (x)=0$ for all $x^* \\in X^*$, then $x=0$?\n\nA: we can use Hahn-Banach theorem to prove it , we take x such that x $\\neq$ 0 , we define a functional on $span(x)$ such that $f(x)=1$ for example ...\nthen there is an extention of $f$ in $X$ . \n\nA: I am going to put my own answer here, expounding on Abderrahim Abdou's. We will use the second form of Hahn-Banach theorem (which can be found on Wikipedia). Suppose for contradiction that $x \\neq 0$, then $\\text{span}\\{x\\}$ is nontrivial, and $f(\\alpha x)=\\alpha$ for every $\\alpha \\in \\mathbb{K}$ is a linear functional on $\\text{span}\\{x\\}$. Consider the seminorm $g$ on $X$ where $g(y)=|f(y)|$ for $y \\in \\text{span}\\{x\\}$ and $0$ otherwise. Since $|f| \\leq g $ in $\\text{span} \\{x\\}$, then by Hahn-Banach theorem, $f$ extends to a linear function in whole of $X$, therefore, $f \\in X^*$, but $f(x)=1 \\neq 0$ which is a contradiction.\n", "meta": {"language": "en", "url": "https://math.stackexchange.com/questions/2438781", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Error while unzipping JSON file (Firefox) in my Node.js application I have a route where I am fetching a big chunk of JSON data from database (Postgres) and sending it in compressed format in a response. I am using Zlib module to gzip this data. I am setting Content-Type: application/gzip and Content-Encoding: gzip before sending a response. Now all this set up works well with Chrome and Safari browsers (unzipping data successfully) but for some reason this is not working in Firefox. Request header contains Accept-Encoding: gzip, deflate. \nIn browser(Firefox) console I see following errors\nAttempt to set a forbidden header was denied: Accept-Encoding and\nSyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data\nCan anybody please guide me what this issue is and how can I solve it? Thanks!\n\nA: Ok, I will answer my question with what worked for me.\nOn server side, I changed the way I was compressing the data. I am using deflate method of Zlib module instead of gzip. Also changed the response header with these values. \nContent-Encoding: deflate and Content-Type: application/deflate\nI am still not sure why gzip does not work (or at least did not work for me) but because of time constraint I am going with deflate for now.\nAlso gzip and deflate uses same compression algorithm and deflate is faster in encoding and decoding. I hope this helps and please correct me if I'm wrong at any place. Thanks!\n\nA: In modern browsers, according to https://developer.mozilla.org/en-US/docs/Web/API/Headers,\n\nFor security reasons, some headers can only be controlled by the user agent. These headers include the forbidden header names and forbidden response header names.\n\nForbidden header names include \"Accept-Encoding\".\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/46108399", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: What is the Thingsboard IoT platform's default system administrator account? What is the Thingsboard IoT platform's (https://thingsboard.io) default system administrator account after a fresh (Raspberry Pi) installation?\nThe existing documentation only refers to default \"tenant\" account, which is ok on my setup.\nThanks in advance.\n\nA: Default system administrator account:\n\n*\n\n*login - sysadmin@thingsboard.org\n\n*password - sysadmin\n\nDefault demo tenant administrator account:\n\n*\n\n*login - tenant@thingsboard.org.\n\n*password - tenant.\n\nDemo tenant customers:\nCustomer A user: customerA@thingsboard.org.\nCustomer B user: customerB@thingsboard.org.\nCustomer C user: customerC@thingsboard.org.\nall users have \u201ccustomer\u201d password.\nTake a look at demo-account documentation page for more information.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/41832556", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "8"}} {"text": "Q: How to Directly Upload file to other server So I have a project in which i want to upload video to dailymotion using api \nSo i want to Upload video directly to dailymotion server without uploading it to my local server\nMy Action\n [HttpPost]\n public async Task Add(Video Videos)\n {\n var fileToUpload = @\"E:\\Courses\\[FreeCourseLab.com] Udemy - C# Intermediate Classes, Interfaces and OOP\\5. Polymorphism Third Pillar of OOP\\3. Sealed Classes and Members.mp4\";\n return RedirectToAction(\"AddVideo\", \"Admin\");\n }\n\nmy View\n@using (Html.BeginForm(\"Add\", \"Admin\", FormMethod.Post, new { @class = \"px-lg-4\", role = \"form\" }))\n{\n @Html.AntiForgeryToken()\n @Html.ValidationSummary(\"\", new { @class = \"text-danger\" })\n\n
    \n
    \n @Html.TextBoxFor(m => m.Videos.File, new {@type=\"file\" })\n
    \n \n}\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/57901771", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: Choosing resistance in series with a photoresistor for best light-measurement resolution \n\n\nsimulate this circuit \u2013 Schematic created using CircuitLab\nI have a photoresistor, R1, and as a voltage divider a fixed resistance, R2. There is a voltage of 5V over these two, and the voltage is measured over the photoresistor. \nIn my experiment I have a yellow LED on one side, a substance which I add blue color into, and the photoresistor on the other side. How do I decide what R2 to choose so that I can detect small changes in light (when increasing the opacity of the substance)? \n\nA: Voltage dividers have the best sensitivity when R1 is equal to R2. The voltage given by the divider is:\n$$ V_x = V_1\\frac{R_1}{R_1+R_2} $$\nThe sensitivity is given by the first derivative:\n$$ d\\frac{V_x}{dR_1} = V_1\\frac{R_2}{(R_1+R_2)^2} $$\nAssuming you will make your measurements at about 10 lux, your sensor resistance will be \\$R_1=29k\\Omega\\$. Not surprisingly, the maximum of sensitivity function occurs when \\$R_2=29k\\Omega\\$ as well.\n\nA: This is a voltage divider circuit, sometimes incorrectly called a bridge. The one fixed known resistor in series with the unknown resistance produces a voltage that is a function of the unknown resistance all the way from zero to infinity. In theory, any resistance can be measured.\nHowever, the sensitivity is greatest when the output voltage is in the middle of its range. This is when the unknown resistance is close to the fixed resistance. Therefore, use a fixed resistor (R2) that matches the photoresistor value in the middle of your typical experiment. You can find this by disconnecting the photoresistor from the circuit and measuring it with a ohmmeter. Or, you can pick different fixed resistors for R2 until you get about 2.5 V out for your typical setup.\nIs the photoresistor really only 100 \u03a9 when used in your experiment? That's rather low. 2.5 V across this 100 \u03a9 draws 25 mA and causes 63 mW dissipation in the photoresistor. That shouldn't be a problem by itself, but will cause some self-heating, which probably changes the resistance a bit. This means the resistance will change quickly due to light, then more slowly due to different dissipation at the different light level.\nPhotoresistors come in many different resistance ranges. I would look for something more like 1 k\u03a9 at the intended light level.\n", "meta": {"language": "en", "url": "https://electronics.stackexchange.com/questions/225659", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "-1"}} {"text": "Q: C fork - how to wait for all children before starting workload? I am trying to get fork() to create multiple processes all of which do the same work. I need all of them to get created first, and then at the same time start doing work. That is, I want all of the processes to wait for all of the other ones to get created, and once they are all ready, start doing the work at the same exact time.\nIs this possible? Thanks.\n\nA: The simplest approach would be simply using signals, do note however that there is no way to actually guarantee that the processes will indeed run in parallel.\nThat's for the OS to decide.\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/19210566", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: Update existing SharePoint list from Excel file in library What I'm trying to do is to update the SharePoint list if there is an item in the Excel file that is not in SharePoint, for example\nI have in the SharePoint list one item:\n\n\n\n\nPR Number\nDesc\nTitle\nPriority\nLink\n\n\n\n\n0005689\nlorem\nexample\n(This is a dropdown)\nhttp://example.com\n\n\n\n\nAnd in the Excel I have three items:\n\n\n\n\nNumber\nDesc\nTitle\nLink\n\n\n\n\n0005689\nlorem\nexample\nhttp://example.com\n\n\n0003491\nlorem\nexample\nhttp://example.com\n\n\n0001497\nlorem\nexample\nhttp://example.com\n\n\n\n\nSo basically I want to compare if each of the Number values in the Excel file exists in the SharePoint list, and if not, then add it to SharePoint so the final list will be like:\n\n\n\n\nPR Number\nDesc\nTitle\nPriority\nLink\n\n\n\n\n0005689\nlorem\nexample\n(This is a dropdown)\nhttp://example.com\n\n\n0003491\nlorem\nexample\n(This is a dropdown)\nhttp://example.com\n\n\n0001497\nlorem\nexample\n(This is a dropdown)\nhttp://example.com\n\n\n\n\nSo far I have tried with PowerAutomate (MS Flow) but it is quite confusing how to use it, I have just being able to set the recurrence to each day, and to get the items and the worksheet, but I don't find a way to handle the data and make the comparisson nor the addition to the list.\nI did my research in the forum but the threads are more than 7 years old.\n\nA: See the screenshots for a sample Power Automate below.\n\nDetail 1\n\nDetail 2\n\n", "meta": {"language": "en", "url": "https://sharepoint.stackexchange.com/questions/292319", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: OpenGL orientation. (Identity rotation looking in negative z) I'm implementing a renderer that handles every translation- / view- / model- / projection-matrix (I don't use glRotate / glTranslate etc.).\nI have placed several blue objects along the positive z-axis and some red objects on the positive x-axis (So I should be able to see the red objects to my left and the blue ones straight ahead using identity rotation on my camera). It is right-hand-orientation, right?\nThe problem is that I have to turn 180 deg around the y-axis to see my objects. It appears as the identity rotation is looking in -z. \nI'm constructing my View matrix by taking the inverse of the cameras matrix [Rot Tr] and then I put it in a array column-wise and pass it to my shader.\nFor the objects (World matrix) I just pass the matrix [Rot Tr] column-wise to the shader. Should I negate the translation? \nThe projection matrix is for now constructed in the vertex shader as I am working my way through. As you can se below I'm doing \nposition = proj*view*model*gl_Vertex;\n\nAt the moment I use gl_Vertex (I use glutSolidCube after loading identity matrix as my scene objects).\nuniform mat4 view;\nuniform mat4 model;\n\nvarying vec4 pos;\n\nvoid main()\n{ \n\npos = gl_Vertex;\n\n\nfloat aspect = 1.0;\nfloat fovy = 1.5;\nfloat f = 1.0 / tan(fovy * 0.5);\nfloat near = 1.0;\nfloat far = 100.0;\nfloat tt = 1.0 / (near - far);\n\nmat4 proj = mat4(f/aspect, 0.0, 0.0, 0.0,\n 0.0, f, 0.0, 0.0,\n 0.0, 0.0, (near+far)*tt, -1.0,\n 0.0, 0.0, 2.0*near*far*tt, 0.0);\n\ngl_Position = proj * view * model * pos;\n}\n\nIn my fragment shader I set the color = pos so that I can see the color of the axis and the colors appears correct. I think the objects are correctly placed in the scene but with Identity matrix as rotation I'm still looking the opposite way.\nWhat could I have missed? Am I passing the correct matrices in a correct manner?\n\nA: A right-handed coordinate system always looks down the -Z axis. If +X goes right, and +Y goes up (which is how all of OpenGL works), and the view is aligned to the Z axis, then +Z must go towards the viewer. If the view was looking down the +Z axis, then the space would be left-handed.\n\nA: \nThe problem is that I have to turn 180 deg around the y-axis to see my objects. It appears as the identity rotation is looking in -z.\n\nYes it is. The coordinate systems provided yb OpenGL in form for glOrtho and glFrustum are right handed (take your right hand, let the thumb towards the right, the index finger up, then the index finger will point toward you). If you modeled your matrix calculations along those, then you'll get a right handed system as well.\n\nA: Alright completely rewrote this last night and I hope you find it useful if you haven't already came up with your own solutions or someone else who comes along with a similar question.\nBy default your forward vector looks down the -Z, right vector looks down the +X, and up vector looks down the +Y.\nWhen you decide to construct your world it really doesn't matter where you look if you have a 128x128 X,Z world and you are positioned in the middle at 64x64 how would any player know they are rotated 0 degrees or 180 degrees. They simply would not.\nNow you mentioned you dislike the glRotatef and glTranslatef. I as well will not use methods that handle the vector and matrix math. Firstly I use a way where I keep track of the Forward, Up, and Right Vectors. So imagine yourself spinning around in a circle this is you rotating your forward vector. So when a player wants to let's say Run Straight ahead. you will move them along the X,Z of your Forward vector, but let's say they also want to strafe to the right. Well you will still move them along the forward vector, but imagine 90 degrees taken off the forward vector. So if we are facing 45 degrees we are pointing to the -Z and -X quadrant. So strafing will move us in the -Z and +X quadrant. To do this you simple do negate the sin value. Examples of both below, but this can be done differently the below is rough example to better explain the above.\nPosition.X -= Forward.X; //Run Forward.\nPosition.Z -= Forward.Z;\n\nPosition.X += Forward.Z; //Run Backwards.\nPosition.Z += Forward.Z \n\nPosition.X += Forward.X; //Strafe Right.\nPosition.Z -= Forward.Z;\n\nPosition.X -= Forward.X; //Strafe Left.\nPosition.Z += Forward.Z;\n\nBelow is how I initialize my view matrix. These are to only be performed one time do not put this in any looping code.\nglMatrixMode(GL_MODELVIEW);\n\nview_matrix[4] = 0.0f; //UNUSED.\n\nview_matrix[3] = 0.0F; //UNUSED. \nview_matrix[7] = 0.0F; //UNUSED. \nview_matrix[11] = 0.0F; //UNUSED. \nview_matrix[15] = 1.0F; //UNUSED.\n\nupdate_view();\nglLoadMatrix(view_matrix);\n\nThen this is the update_view() method. This is to only to be called during a change in the view matrix.\npublic void update_view()\n{\n view_matrix[0] = Forward[0];\n view_matrix[1] = Up[1] * Forward[1];\n view_matrix[2] = Up[0] * -Forward[1];\n\n view_matrix[5] = Up[0];\n view_matrix[6] = Up[1];\n\n view_matrix[8] = Forward[1];\n view_matrix[9] = Up[1] * -Forward[0];\n view_matrix[10] = Up[0] * Forward[0];\n}\n\nThe Position vectors are matricies [12], [13], and [14] and are negated. You can choose to store these or just use matrix[12], [13], [14] as the vector for position.\nview_matrix[12] = -Position.x;\nview_matrix[13] = -Position.y;\nview_matrix[14] = -Position.z;\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/9448885", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "1"}} {"text": "Q: uploading an array to server in swift using Alamofire This is how I'm saving the data successfully to model class when user login\nvar isLogin: IsLogin!\nvar loginDetail: LoginDetail!\nvar myDetail: MyDetail!\n\nlet decoder = JSONDecoder()\ndo{\n isLogin = try decoder.decode(IsLogin.self, from: response.data!)\n loginDetail = isLogin.success\n myDetail = loginDetail.user\n}catch{\n print(error)\n}\n\nhere is my model class where I'm saving response from the request\nstruct IsLogin: Decodable {\n var success: LoginDetail\n}\nstruct LoginDetail: Decodable {\n var user: MyDetail\n}\n\nstruct MyDetail: Decodable {\n var id: Int\n var emergency_contacts: [EmergencyContacts]?\n}\nstruct EmergencyContacts: Decodable {\n var user_id : Int\n var number : String\n}\n\nI want to post EmergencyContacts in another request how do I do that? This is how im trying but in response array of EmergencyContacts is always empty\nmultipartFormData.append(\"\\(myDetail.emergency_contacts!)\".data(using: .utf8,allowLossyConversion: false)!,\n`enter code here`withName: \"emergency_contacts\")\n\nI have print all the values from model class and they are fine but guide me about how to send an array in a post request.Please suggest my some method using multipartformdara because I have been using this to send other parameters as well.below is the postman screenshot where If I send parameters like this then I can get the emergencycontacts in response 13 is the id of emergency contact\n\n", "meta": {"language": "en", "url": "https://stackoverflow.com/questions/63713852", "timestamp": "2023-03-29", "source": "stackexchange", "question_score": "0"}} {"text": "Q: How to use a template template argument from a member templated type alias of a struct I'm trying to use a template template argument coming from a member type alias of a struct, but I can't find the right syntax:\nstruct A\n{\n template \n using type = int;\n};\n\ntemplate