texts
sequence | tags
sequence |
---|---|
[
"How to display old articles?",
"I wanted to set created date of the articles, so I set the date of the articles to 2012-2-1 but after the setting the date of the articles it's not displaying in the front-end anymore now.\n\nAfter doing a deep dive into this I saw the article in the back-end it isn't being published. It's saying published, but has expired.\n\nSo, can I not publish the old-dated articles?\n\nPlease, help me on this topic. Thank you."
] | [
"joomla",
"joomla2.5"
] |
[
"use of if/else statement with pexpect",
"I am trying to write a script in which I would like to access the switch with tacacs credentials with the help of interactive pexpect module. However I would like to use if/else statement and accordingly send different command.\n\nFor example:\n\n1) Expecting 'password:' and sending login password.\n\nabc:PythonScripts$ ssh username@ip_address\npassword:\n\n\n2) Expecting \"Are you sure you want to continue connecting (yes/no)?\" and sending command 'yes'.\n\nabc:PythonScripts$ ssh username@ip_address\nAre you sure you want to continue connecting (yes/no)?"
] | [
"pexpect"
] |
[
"AttributeError: 'dict_set' object has no attribute 'hash' Python",
"Exercise on dictionary with hashing\nI have to to implement the following dictionary methods and the check code:\n\n\nInsert(key, value): insert the key with its value. If the key was already present, change its value;\nDelete(key): remove the key;\nLookup(key): return True if the key is present, False otherwise;\nValue(key): return the value associated with the key. It returns None, if the key is not present.\nThe suggest is to store pairs (key, value) within the lists.\n\n\nThis is my implementation:\n\n\n\nclass dict_set:\n def __init__(self, size):\n\n self.T = []\n for _ in range(size):\n self.T.append([]) \n self.prime = 993319\n self.a = random.randint(2, self.prime-1)\n self.b = random.randint(2, self.prime-1)\n self.n_keys = 0\n\n def insert(self, key, value):\n h=self.hash(key)\n if self.lookup(key):\n for k,v in enumerate(self.T[h]):\n if k==key:\n v = value\n else:\n self.T[h].append([key,value])\n self.n_keys+=1\n\n def lookup(self, key):\n h = self.hash(key)\n for mykey in (self.T[h]):\n if mykey == key:\n return True \n return False \n\n def delete(self, key):\n h=self.hash(key)\n if self.lookup(key):\n for i, e in enumerate(self.T[h]):\n if e==key:\n self.T[h][i],self.T[h][-1]=self.T[h][-1],self.T[h][i]\n del(self.T[h][len(self.T[h])-1])\n self.n_keys-=1\n return \n def value(self,key):\n h=self.hash(key)\n if self.lookup(key):\n for i, e in enumerate(self.T[h]):\n if e==key:\n return self.T[h][i][e]\n else:\n return None \n\n\nFIRST PART OH CHECK AND ERROR\n\n\n\nd=dict_set(10)\nn = 10\na = get_random_array(n, n)\nprint(a)\nfor key in a:\n d.insert(key, 2)\n\n\n---------------------------------------------------------------------------\nAttributeError Traceback (most recent call last)\n<ipython-input-4-ef6b1c7e9a54> in <module>\n 1 for key in a:\n----> 2 d.insert(key, 2)\n\n<ipython-input-2-f7154c908f8d> in insert(self, key, value)\n 14 \n 15 def insert(self, key, value):\n---> 16 h=self.hash(key) #calcolo la posizione h in cui deve essere inserita la chiave\n 17 if self.lookup(key):\n 18 for i in range(len(self.T[h])):\n\nAttributeError: 'dict_set' object has no attribute 'hash'\n\n\ncan someone help me??"
] | [
"python",
"dictionary",
"python-3.6",
"implementation"
] |
[
"python3 - how to scrape the data from span",
"I try to use python3 and BeautifulSoup.\nimport requests\nimport json\nfrom bs4 import BeautifulSoup\n\nurl = "https://www.binance.com/pl"\n\n#get the data\ndata = requests.get(url);\n\nsoup = BeautifulSoup(data.text,'lxml')\n\nprint(soup)\n\nIf I open the html code (in browser) I can see:\nhtml code in browser\nBut in my data (printing in console) i cant see btc price:\nwhat data i cant see in console\nCould u give me some advice how to scrape this data?"
] | [
"python-3.x",
"web-scraping",
"beautifulsoup"
] |
[
"Unable to enter correct characters in IntelliJ",
"I want to start developing apps using IntelliJ IDE. I have downloaded and installed it with no problem.\n\nNow, IntelliJ does the following when I enter on the keyboard:\n\n\n; : button = $\nctrl + shift = ^\nshift + \"\\' = @\n, button = ?\n. button = /\n\n\nAs a coder I will need a . (dot) and/or semicolon, in which IntelliJ does not respond correctly to what I am typing."
] | [
"intellij-idea"
] |
[
"sequelize: relations in both directions needed?",
"I have two existing tables in my database: \"user\" with the columns \"id\" and \"depId\" and \"department\" with \"id\" and \"name\". (user.depId ist the foreign key for department.id)\n\nNow I'd like to create a sequelize model for this. \n\nI already added this \n\nUser.belongsTo (Department, { foreignKey: 'depId', targetKey: 'id'});\n\n\nDo I have to add this also:\n\nDepartment.HasMany(User)\n\n\nor is one direction enough to work properly?"
] | [
"javascript",
"node.js",
"express",
"sequelize.js"
] |
[
"symbols in js file are not recognized in browser cache",
"I have a js file which contains the below text in one of its line \n\n \"St_Johns\": {\n \"exemplarCity\": \"St. JohnyX92s\"\n }\n\n\ni have invoked the getScriptFile() in service by using the ajax call and it returns the stream of bytes which is stored in the browser cache\n\n_\n\ngetScriptFile: function (fileName) {\n var that = this;\n $.ajax({\n url: this.serviceUrl() + \"/GetScript\",\n data: { fileName: fileName},\n dataType: \"script\",\n cache: true,\n error: function () {\n that._errorMsgPopup(that.locale.utils.FileDownloadError + culture, true);\n }\n });\n\n\nIn Service \n\npublic Stream GetScript(string fileName)\n {\n if (File.Exists(filePath + fileName))\n {\n stream = new MemoryStream(File.ReadAllBytes(filePath + fileName));\n }\n\n return stream;\n }\n\n\nNow the problem is some of the symbols in my js files are treated as '�' in browser cache. like the below \n\n\"St_Johns\": {\n \"exemplarCity\": \"St. John�s\"\n}\n\n\nPlease help me resolve this issue. i have tired UTF-8 encoding also.\n\nTIA"
] | [
"javascript",
"ajax"
] |
[
"How to use a variable in environment variable name in a Shell script?",
"I have a environment config file where i have defined the environment variables. I use source to get these variables inside my shell script(bash).\n\nI use a checkout command in my shell script which checks out the files from location defined in an environment variable. Now i need to use multiple locations to checkout the files which can be any number for different run of shell script.\n\nFor eg. User gives two paths, PATH1 and PATH2 in config file and a NUM_OF_PATHS as 2.\n\nIn my shell script I want to do something like below for using path.\n\ni=0\necho ${NUM_OF_PATHS}\nwhile [ $i -lt ${NUM_OF_PATHS} ]\ndo\n checkout $PATH{$i}\n i=`expr $i + 1`\ndone\n\n\nHow can I use the variable i to form an environment variable PATH1 or PATH2 etc.?"
] | [
"shell"
] |
[
"Optimal method to find perpendicular distance between numpy poly1d and arbitrary point",
"I have a numpy.poly1d that can be any arbitrary 1d polynomial. Given an arbitrary point P, I wish to find the perpendicular distance between the curve and the point, and the point on the curve where the shortest distance line intersects the curve, if the point P does not lie on the polynomial itself\nNow I can do something like the question Distance between a point and a curve in python, by sampling a set of points. But I believe that won't be fast enough considering that I have <100000 polynomials and <1000000 points per polynomial that I wish to find that distances to. Can someone suggest a more optimal method?\nHere is a sample image illustration of what I am looking for. Basically, given P and B(t) I wish to find the length of g(x) and point Q."
] | [
"python",
"numpy"
] |
[
"Using jQuery .load() with aspx",
"So I'm fairly new to the .NET framework, but what I'm trying to do is execute the following jQuery code:\n\n $(document).on('click', 'a[data-link]', function () {\n var $this = $(this);\n url = $this.data('link');\n $(\"#imagePreview\").load(\"imageProcess.aspx?\"+url);\n\n\nwhere url holds something like \"model=2k01&type=black&category=variable\".\nUnfortunately this doesn't work, becuase when I do something as simple as a Response.Write() in the aspx file, the div tag imagePreview doesn't do anything. However, removing the ? + url part works, but then I can't send any data over to the aspx file. I'm doing it this way because every link a[data-link] has different data that's being sent over, and I need to find a dynamic way to achieve this. Any suggestions would be much appreciated.\n\nUPDATE:\nHere is the part in my html code that is generating the url stuff:\n\n<a class='modelsBlue' href = '#' data-link='model=\" + $(this).find('model').text() + \"&type=\" + category + \"'>\" + $(this).find(\"model\").text() + \"</a>\n\n\nand #image preview is in my code as:\n\n<div id = \"imagePreview\"></div>\n\n\nWhen I try to run the code above, i get the following error which seems to be coming from the jQuery.js file:\n\nMicrosoft JScript runtime error: Syntax error, unrecognized expression: &type=AutoEarly\n\n\nHere is the imageProcess.aspx.cs file, which right now is just outputting all images in the directory:\n\nnamespace ModelMonitoring\n{\n public partial class imageProcess : System.Web.UI.Page\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n Response.Write(\"test\");\n foreach (var f in Directory.GetFiles(Directory.GetCurrentDirectory()))\n {\n Response.Write(f);\n Response.Write(\"<br />\");\n }\n }\n }\n}\n\n\nSECOND UPDATE:\nI don't get the error running in chrome or firefox, but the files are not being output."
] | [
"c#",
"jquery",
"asp.net",
".net",
"load"
] |
[
"Animation moves just on first button click",
"I have one question.\nI have a button ant when I click on it, imageView (with objectAnimator) goes down. I have my ˝animation down˝ in onClick and every thing is very simple, I click on the button and image goes down - there I have a question.\n\nFirst, there is my code:\n\nObjectAnimator objectAnimatorBlock1 = getDownObjectAnimator(imageBlock1);\n animatorSetBlock1 = new AnimatorSet();\n animatorSetBlock1.play(objectAnimatorBlock1);\n animatorSetBlock1.start();\n\nprivate ObjectAnimator getDownObjectAnimator(View v) {\n ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(v, \"translationY\", 0.0f, 860.0f);\n objectAnimator.setDuration(2000);\n return objectAnimator;\n\nand XML:\n\n\n<ImageView\n android:contentDescription=\"@string/image_description\"\n android:layout_marginRight=\"202dp\"\n android:layout_marginEnd=\"202dp\"\n android:layout_marginTop=\"-155dp\"\n android:layout_width=\"200dp\"\n android:layout_height=\"90dp\"\n android:id=\"@+id/imageBlock1\"\n android:layout_gravity=\"end|center_vertical\"\n android:src=\"@drawable/distance11\" />\n<Button\n android:layout_width=\"60dp\"\n android:onClick=\"countIN\"\n android:layout_marginLeft=\"20dp\"\n android:layout_height=\"61dp\"\n android:text=\"DROP THE BLOCK\"\n android:id=\"@+id/button2\"\n android:layout_gravity=\"start|center_vertical\"\n android:background=\"@drawable/layout100\"\n android:textStyle=\"normal|bold|italic\" />\n\n\nMy problem is: First time when I click on the button, image goes down and there also stand still(that is correct), but I would like that image goes down JUST when I first time click on a button. After first click animation is clear(finish animation) - then on second, third, fourth,... click , there is not any effect on image(it do not move). How can I do these?"
] | [
"java",
"android"
] |
[
"mysql how to encrypt and decrypt a column using aes",
"I have the following the table named MYTABLE with following columns\n\n `idMdP` int(11) NOT NULL AUTO_INCREMENT, \n `login` varchar(255) NOT NULL, \n `password` varchar(255) NOT NULL, \n `url` varchar(255) NOT NULL,\n\n\nI use it only via PHPMYADMIN.\n\nMy aim is to :\n\n\nencrypt (AES 256 or AES 512) the password column with a unique key\nusing the key to decrypt the column and visualise all columns via a sql query\n\n\nIs it possible?"
] | [
"mysql",
"phpmyadmin",
"aes",
"password-protection",
"qsqlquery"
] |
[
"Is it possible to have two (multiple) clients hosted on the same server in a Blazor WebAssembly app",
"I created a Blazor WebAssembly App named "BlazorWebApp" and checked the box for "ASP.NET Core hosted". Now, can I add another client app to access the same server? I tried by adding another Blazor WebAssembly named Client2 and unchecked the box for "Core hosted" , but now it doesn't work, displaying an empty browser. I would like to know how to set the server to select the client that will show after the build and what changes the newly added client needs to communicate with the server.\nI found this link here but it only solved the conflict error."
] | [
"asp.net-core",
"blazor",
"blazor-webassembly",
"blazor-client-side"
] |
[
"Convert a bit-string to a char",
"I'm trying to convert a bit-string to ASCII characters by 8 bits (each 8 bits = 1 ASCII char).\n\n public string BitsToChar(string InpS)\n {\n string RetS = \"\";\n for (int iCounter = 0; iCounter < InpS.Length / 8; iCounter++)\n RetS = System.String.Concat(RetS, (char)Convert.ToByte(InpS.Substring(iCounter * 8, 8)), 2); \n return RetS;\n }\n\n\nIt throws a System.OverflowException: Value was either too large or too small for an unsigned byte.\n\nIt's not clear for me how comes that an 8-bit portion of a binary string can be too small or too large for an 8-bit Byte type. \n\nAny ideas? Thank you."
] | [
"c#",
"string",
"binary",
"char"
] |
[
"How do I query belongs_to through a HABTM in Rails",
"I am trying to understand the best way to query a pretty basic HABTM relationship. I want to find all races by the associated discipline.id. Since I have a HABTM relationship in the middle I am just getting confused on the best way to do this.\n\nclass Discipline < ActiveRecord::Base\n has_many :event_types\nend\n\nclass EventType < ActiveRecord::Base\n belongs_to :discipline\n has_and_belongs_to_many :races\nend\n\nclass Race < ActiveRecord::Base \n has_and_belongs_to_many :event_types\nend\n\n\nThanks."
] | [
"ruby-on-rails",
"ruby",
"activerecord",
"has-and-belongs-to-many"
] |
[
"How to export variables from functions in Javascript?",
"I'm wondering how can I export a variable from inside a function to be used in another functions, I've used this code:\n\nBut in the latest function I'd like to add a variable called nombre from another function, but I'm not able, I thought about adding several values to a function, but at last, I only can imagine a function with endless parameters, if that's possible.\n\nThanks in advance!\nCristobal.\n\n\r\n\r\n<script>\r\n//Empieza el script justo aquí\r\n//Aquí definimos la función de cómo queremos llamar a nuestro personaje\r\n//La función nombreintroducido recoge el valor de la variable nombre y la usa más adelante\r\n var nombrepersonaje = function() {\r\n var nombre = prompt(\"Como quieres que se llame tu personaje\");\r\n nombreintroducido(nombre);\r\n }\r\n\r\n//Aquí definimos que si el nombre tiene menos de tres carácteres, se repite la función nombrepersonaje\r\n//Si se pulsa cancelar, se terminará el juego\r\n//Si introduces algún nombre de personaje que sea válido, se abrirá un mensaje emergente que mostrará el nombre introducido\r\nvar nombreintroducido = function (nombre){\r\nif (nombre === '') {\r\n confirm('Tu nombre de personaje ha de tener mas de 3 caracteres');\r\n nombrepersonaje();\r\n} else if (nombre === null){\r\nconfirm('No has introducido ningun nombre de personaje, el juego terminara ahora')\r\n}\r\nelse{\r\n confirm('Tu nombre de personaje es' + ' ' + nombre)\r\n\r\n }\r\n};\r\n\r\nvar eligeclase = function(){\r\nvar clase = prompt(\"Que clase quieres elegir: Guerrero o Mago\")\r\nclaseescogida(clase);\r\n}\r\n\r\nvar claseescogida = function (clase){\r\nif (clase === 'Guerrero'){\r\nconfirm('Has elegido la clase Guerrero: 10 Fuerza y 5 Inteligencia');\r\nconfirmaclase(clase);\r\n}\r\nelse if (clase === 'Mago') {\r\nconfirm ('Has escogido la clase mago: 10 Inteligencia y 5 Fuerza');\r\nconfirmaclase(clase);\r\n}\r\nelse {\r\nconfirm ('Tienes que escribir exactamente Guerrero o Mago');\r\neligeclase();\r\n}};\r\n\r\nvar confirmaclase = function(clase) {\r\nconfirm('Tu clase es finalmente ' + clase + ' ... y tu nombre es');\r\n}\r\n\r\n\r\n//Se podría decir que el minijuego empezaría aquí, ya que lo anterior son funciones que definimos\r\nnombrepersonaje();\r\neligeclase();\r\n\r\n\r\n\r\n//Termina el script justo aquí\r\n </script>"
] | [
"javascript",
"function",
"import",
"export"
] |
[
"How can I solve \"Fatal error: Out of memory...\" when I run command schedule laravel?",
"My command like this : \n\n<?php\nnamespace App\\Console\\Commands;\nuse Illuminate\\Console\\Command;\nuse App\\Models\\ItemDetail;\nclass ImportItemDetail extends Command\n{\n protected $signature = 'sync:item-detail';\n protected $description = 'sync item detail';\n public function __construct()\n {\n parent::__construct();\n ini_set('max_execution_time', 0);\n ini_set('memory_limit', '-1');\n }\n public function handle()\n {\n $path = storage_path('json/ItemDetail.json');\n $json = json_decode(file_get_contents($path), true);\n foreach ($json['value'] as $value) {\n ItemDetail::updateOrCreate(\n [ 'entry_number' => $value['Entry_Number'] ],\n [ \n 'item_number' => $value['Item_Number'],\n 'description' => $value['Description'],\n ....\n ]\n );\n }\n }\n}\n\n\nIf I run the commmand, there exist error like this :\n\nFatal error: Out of memory (allocated 255852544) (tried to allocate 8192 bytes)\n\n\nWhereas I had set ini_set('memory_limit', '-1'); in construct\n\nHow can I solve the error?\n\nNote :\n\nMy record in the json file contains hundreds of thousands of data. So it takes a long time to check the field\n\nUpdate \n\nMy ItemDetail.json like this :\n\n{\n \"@odata.context\":\"http://myapp-svr01.www.myapp.com:1224/DynamicsNAV100/ODataV4/$metadata#Collection(NAV.ODATAITEM)\",\"value\":[\n {\n \"@odata.etag\":\"W/\\\"JzE2O0lBQUFBQUNIbXdrQ0FBQAD5OzE4ODQ1MDQ4NjA7Jw==\\\"\",\"Entry_Number\":123,\"Item_Number\":\"9805010101\",\"Variant_Code\":\"039\",\"Posting_Date\":\"2018-01-02T00:00:00Z\",\"Entry_Type\":\"Sale\",\"Description\":\"MISC BISBAN POLOS 11MM A847\",\"Quantity\":-7200,\"Source_Type\":\"Customer\",\"Order_Type\":\" \",\"Sales_Amount_Actual\":1800000,\"ETag\":\"16;IAAAAACHmwkCAAAA9;1884504860;\"\n },{\n \"@odata.etag\":\"W/\\\"JzE2O0lBQUFBQUNIbkFrQ0FBQAD5OzE4ODQ1MDQ5MTA7Jw==\\\"\",\"Entry_Number\":124,\"Item_Number\":\"9805010102\",\"Variant_Code\":\"100\",\"Posting_Date\":\"2018-01-02T00:00:00Z\",\"Entry_Type\":\"Sale\",\"Description\":\"MISC BISBAN POLOS 11MM A915\",\"Quantity\":-7200,\"Source_Type\":\"Customer\",\"Order_Type\":\" \",\"Sales_Amount_Actual\":1800000,\"ETag\":\"16;IAAAAACHnAkCAAAA9;1884504910;\"\n }\n ]\n}\n\n\nI only gave 2 records in json above. Actually there are around 150,000 records"
] | [
"laravel",
"memory",
"command",
"laravel-5.6",
"schedule"
] |
[
"How to change title language Wordpress Soledad",
"I can't change language in the single post. I changed language in control panel, but this one element is still in english. Need help"
] | [
"wordpress"
] |
[
"what does \"((class)obj).method()\" do?",
"i saw the above code in one of my assignments and couldn't find any information about it. Would someone please explain what it means? \n\nobj would be an instance of the class class and method is a method of this object. \n\nWhy is class.obj.method wrong?\n\nI tried searching topics related to type-conversion which didn't deliver the answer that I'm looking for. I don't know how to research something like this. Any tips on this are welcome."
] | [
"java",
"casting"
] |
[
"Rails :: Why the attribute change doesn't persist?",
"Controller:\n\n@events = Event.all\[email protected] { |e| e.user_subscribed = \"someuser\" }\[email protected] { |e| puts \"error\" + e.user_subscribed }\n\n\nI have attr_accessor :user_subscribed. but the error is can't convert nil into String as e.user_subscribed evaluates to nil.\n\nI'm using mongoid on the backend.\n\nedit: this works, but it just copies the whole array.\n\n@events = @events.map do |e|\n e.user_subscribed = \"faaa\"\n e\nend"
] | [
"ruby-on-rails",
"ruby-on-rails-3",
"mongoid"
] |
[
"Execute Javascript through PHP",
"I'm using this PHP code to write a HTML table, but it takes time to load. I was thinking it would be a good idea to let JavaScript do the job, but the problem is that $width and $height are dynamic and is defined on the server-side. How do I get around that? \n\necho \"<table>\";\n\n for ($y = 0; $y < $height; $y++) {\n echo \"<tr>\";\n for ($x = 0; $x < $width; $x++) {\n echo '<td x=\"' . $x . ' y=\"' . $y . ' id=\"' . $x . '-' . $y . '\"></td>'; //coordinates to be used for cropping later\n }\n echo '</tr>';\n }\n echo '</table>';"
] | [
"javascript",
"php",
"html-table"
] |
[
"How to put delay while opening tab via Chrome Extension",
"As chrome.tabs.create is asynchronous, it opens link immediately. I have to open a certain links with delay. Is it possible?"
] | [
"google-chrome-extension",
"delay"
] |
[
"Sort array by both numeric and string keys",
"i have tried both ksort and asort but in both cases all always shows at bottom..\n\nbut i want to display array of index 'all' at top then numeric fields should be displayed.\n\nActually i am adding that key manually.\n\n $result['all'] = new stdClass();\n $result['all']->DisciplinaryAction = 'All';\n $result['all']->DisciplinaryActionID = 0;\n\n\ni tried ksort($result) and also tried asort($result) but in both cases text/string always arranged to bottom..\n\nArray\n(\n [0] => stdClass Object\n (\n [DisciplinaryAction] => counseling\n [DisciplinaryActionID] => 1\n )\n\n [1] => stdClass Object\n (\n [DisciplinaryAction] => verbal warning\n [DisciplinaryActionID] => 2\n )\n\n [2] => stdClass Object\n (\n [DisciplinaryAction] => written warning\n [DisciplinaryActionID] => 3\n )\n\n [3] => stdClass Object\n (\n [DisciplinaryAction] => suspension\n [DisciplinaryActionID] => 4\n )\n\n [4] => stdClass Object\n (\n [DisciplinaryAction] => termination\n [DisciplinaryActionID] => 5\n )\n\n [all] => stdClass Object\n (\n [DisciplinaryAction] => All\n [DisciplinaryActionID] => 0\n )\n\n)"
] | [
"php",
"arrays"
] |
[
"Parse nested yaml with Haskell",
"How would one define a type for the following yaml configuration:\n\nrequest: \n a: \"https://google/1\"\n b: \"https://google/2\" \n c: \"https://google/3\"\n\n\nWould it be like this?\n\ndata Config = Config { request :: id' } deriving (Show, Generic)\n\n\nand then define id' later?"
] | [
"haskell",
"yaml"
] |
[
"Android adb not found",
"When I run my android app from eclipse, I get this error. \n\nUnexpected exception 'Cannot run program \"/home/antz/Development/adt-bundle-linux/sdk/platform-tools/adb\": error=2 No such file or directory' while attempting to get adb version from /home/antz/Development/adt-bundle-linux/sdk/platform-tools/adb\n\n\nCOPY PASTE FROM Eclipse Error\n\n[2012-11-26 13:43:08 - adb] Unexpected exception 'Cannot run program \"/home/antz/Development/adt-bundle-linux/sdk/platform-tools/adb\": error=2, No such file or directory' while attempting to get adb version from '/home/antz/Development/adt-bundle-linux/sdk/platform-tools/adb'\n\n\nHowever my adb is exactly in the location where it says it's not. \n\nWhat is wrong and how do I fix this?\n\nI cd into the directory where adb is (/home/antz/Development/adt-bundle-linux/sdk/platform-tools/) and I typed in adb and it says\n\nantz@antz-90X3A:~/Development/adt-bundle-linux/sdk/platform-tools$ ls \naapt aidl dexdump fastboot llvm-rs-cc renderscript \nadb api dx lib NOTICE.txt source.properties \nantz@antz-90X3A:~/Development/adt-bundle-linux/sdk/platform-tools$ adb \nbash: /home/antz/Development/adt-bundle-linux/sdk/platform-tools/adb: No such file or directory\n\n\nadb is green which means its an executable, correct?\n\nfor example, dx is also green and when I typed in dx into the command prompt, it works... whats wrong with adb?"
] | [
"android",
"linux",
"adb"
] |
[
"Use Java constants in arrays defined by XML",
"I have an array like this that defines the entry values for a ListPreference:\n\n<string-array name=\"sortSelectionEntryValues\">\n<item>0</item>\n<item>1</item> \n</string-array>\n\n\nNow instead of using 0 and 1 in XML, I want to use Java constants like e.g. ORDER_ASC and ORDER_DESC, because later I will access the value of the selected ListPreference entry programmatically and I have to check the value in code, but comparing the value to a well named constant makes code easier to read. \n\nSo what I want is something like that:\n\nIn Java:\nclass MyOrderClass\n{\n public static final String ORDER_ASC=\"0\";\n public static final String ORDER_DESC=\"1\";\n}\n\nIn the XML:\n<string-array name=\"sortSelectionEntryValues\">\n<item>MyOrderClass.ORDER_ASC</item>\n<item>MyOrderClass.ORDER_DESC</item> \n</string-array>\n\n\nIs that somehow possible? Thanks for any hint!\n\n(Please note, the ordering is just a dumb example, I just need to know how to integrate Java constants into the XML definition of an array)"
] | [
"android",
"arrays",
"constants"
] |
[
"How to divide two columns element-wise in a pandas dataframe",
"I have two columns in my Pandas dataframe. I'd like to divide column a by column b, value by value, and show it as follows:\nimport pandas as pd\n\ncsv1=pd.read_csv('auto$0$0.csv')\ncsv2=pd.read_csv('auto$0$8.csv')\n\ndf1 = pd.DataFrame(csv1, columns = ['Column A','Column B'])\ndf2 = pd.DataFrame(csv2, columns = ['Column A','Column B'])\n\ndfnew = pd.concat([df1, df2])\n\nThe columns:\nColumn A | Column B |\n12-------|--2-------|\n14-------|--7-------|\n16-------|--8-------|\n20-------|--5-------|\n\nand the expected result\nResult\n6\n2\n2\n4\n\nHow do I do this?"
] | [
"python",
"pandas",
"dataframe"
] |
[
"Convert C char to UTF-16 for transmission over network",
"I'm writing a program that will interface with another machine running Java, and I need to send character arrays over the network. On the receiving end, the Java program uses DataInputStream's readChar() function and expects characters. However, since characters are stored as 1 byte in C, I'm having some trouble writing to the network.\n\nHow would I go about converting this?\n\nThe actual protocol specification is like so:\n\nshort: Contains length of char array\nchar 1, 2, 3...: The characters in the array\n\n\nFor background information, my short conversion is like so:\n\nchar *GetBytesShort(short data)\n{\n short net_data = NET_htons(data);\n char *ptr = (char *) malloc(sizeof(short));\n memcpy(ptr, &net_data, sizeof(short));\n return ptr;\n}\n\n\nI've tested it on the receiving end in Java, and the short does get sent over correctly with the correct length, but the character array does not.\n\nThanks in advance!"
] | [
"java",
"c",
"networking"
] |
[
"Make a Computer Vision Application use Custom Vision",
"I built a Computer Vision Application following the Microsoft tutorial here:\n\nhttps://github.com/Microsoft/computerscience/blob/master/Labs/Azure%20Services/Azure%20Storage/Azure%20Storage%20and%20Cognitive%20Services%20(MVC).md#Exercise1\n\nNow I want to use customvision.ai instead of the standard Computer Vision. I moved my customvision project to Azure and thought I just had to change Subscription Key and Vision Endpoint but it does not seem to work.\n\n<add key=\"VisionEndpoint\" value=\"CustomVisionEndpoint\" />\n<add key=\"SubscriptionKey\" value=\"ValueOfCustomVisionKeyInAzure\" />\n\n\nWhen I use the Computer Vision Endpoint and Key everything works fine, but if I use Custom Vision I get an error message:\n\nOperation returned an invalid status code 'NotFound'\n\nAnyone have any idea? Do I have to change additional values or what is the problem?\n\nThank you for any help\n\nBest regards,\nDaniel"
] | [
"azure",
"computer-vision",
"azure-cognitive-services",
"microsoft-custom-vision"
] |
[
"Using 2captcha with Python",
"I'm totally new with 2captchas and Python, so I'm trying to figure out how these two works. For now I'm working on a python script and running it on spyder to resolve images captcha. My code (using 2captcha API) returns html of the site in return response. It tries to sign up for a site and in return fails the main task that is to resolve captcha.\nMy code looks something like this\n\nimport requests\nfrom time import sleep\n\nAPI_KEY = '2captchaapi' # Your 2captcha API KEY\nsite_key = '2captcha site key' # site-key, read the 2captcha docs on how to get this\nurl = 'site' # example url\nproxy = 'proxy' # example proxy\n\nproxy = {'http': 'http://' + proxy, 'https': 'https://' + proxy}\n\ns = requests.Session()\n\n\n# here we post site key to 2captcha to get captcha ID (and we parse it here too)\ncaptcha_id = s.post(\n \"http://2captcha.com/in.php?key={}&method=userrecaptcha&googlekey={}&pageurl={}\".format(API_KEY, site_key, url), proxies=proxy).text.split('|')[1]\n# then we parse gresponse from 2captcha response\nrecaptcha_answer = s.get(\"http://2captcha.com/res.php?key={}&action=get&id={}\".format(API_KEY, captcha_id), proxies=proxy).text\nprint(\"solving ref captcha...\")\nwhile 'CAPCHA_NOT_READY' in recaptcha_answer:\n sleep(5)\n recaptcha_answer = s.get(\"http://2captcha.com/res.php?key={}&action=get&id={}\".format(API_KEY, captcha_id), proxies=proxy).text\n\nrecaptcha_answer = recaptcha_answer.split('|')[1]\n\nprint(recaptcha_answer)\n\npayload = {\n 'signup-form[votes]': '',\n 'signin-form[subs]': '',\n 'signin-form[post_referer]': 'site',\n 'signup-form[step2][hidden_captcha]': '',\n 'signup-form[details][login]': '[email protected]',\n 'signup-form[details][profile_name]': 'name1',\n 'signup-form[details][password]': 'secret44%',\n 'signup-form[details][password_confirm]': 'secret44%',\n 'signup-form[details][tos_pp]': 'on',\n 'signup-form[step2][optional][age]': '24',\n 'signup-form[step2][optional][sex]': 'Man',\n 'signup-form[step2][optional][country]': 'france',\n 'signup-form[step2][optional][language]': 'french',\n 'signup-form[step2][profilepic][file]': '',\n 'g-recaptcha-response': recaptcha_answer\n}\n\n\n# then send the post request to the url\nresponse = s.post(url, payload, verify=False)\n\n\nprint(response.text)\n\n\nPlease let me know how can I solve Image captchas using this code and if I'm using the right tools to solve this captcha challenge."
] | [
"python",
"captcha",
"2captcha"
] |
[
"Why is tensorflow giving an InvalidArgumentError when dataframe is split before before tokenization?",
"This is a weird problem and I have no idea why it's happening or how to solve it. But in running some simple test code with tensorflow and BERT for topic classification\nfrom transformers import DistilBertTokenizer\nfrom transformers import TFDistilBertForSequenceClassification\n\nimport tensorflow as tf\n\nfrom sklearn.preprocessing import LabelEncoder\n\nimport pandas as pd\nimport numpy as np\nfrom ast import literal_eval # Lists of topics needs to be split\n\n\ndef preprocess_text(df):\n # Remove punctuations and numbers\n df['text'] = df['text'].str.replace('[^a-zA-Z]', ' ', regex=True)\n\n # Single character removal\n df['text'] = df['text'].str.replace(r"\\s+[a-zA-Z]\\s+", ' ', regex=True)\n\n # Removing multiple spaces\n df['text'] = df['text'].str.replace(r'\\s+', ' ', regex=True)\n\n # Turn topic column into list from string with square brackets\n df['topic'] = df['topic'].apply(literal_eval)\n\n # Remove NaNs\n df['text'] = df['text'].fillna('')\n df['topic'] = df['topic'].fillna('')\n\n return df\n\n\n# Load dataframe with just text and topic columns\ndf = pd.DataFrame()\nfor chunk in pd.read_csv(r'test.csv',\n sep='|', chunksize=1000, usecols=['text', 'topic']): # Just take top 1000 for test\n df = chunk\n break\ndf = preprocess_text(df)\n\n# Unstack topics columns\ndf = df.explode('topic').reset_index(drop=True)\ndf['topic'] = df['topic'].astype('category')\ndf['topic'] = df['topic'].cat.add_categories('N/A').fillna('N/A')\n\n# Encode labels\nle = LabelEncoder()\ndf['topic_encoded'] = le.fit_transform(df['topic'])\n\ntext = list(df['text'])\nlabels = list(df['topic_encoded'])\n\ntokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')\n\ntrain_encodings = tokenizer(text, return_tensors='tf', truncation=True, padding=True, max_length=128)\n\ntrain_dataset = tf.data.Dataset.from_tensor_slices((dict(train_encodings), labels))\n\nmodel = TFDistilBertForSequenceClassification.from_pretrained(\n 'distilbert-base-uncased',\n num_labels=len(np.unique(np.array(labels)))\n)\n\noptimizer = tf.keras.optimizers.Adam(learning_rate=5e-5)\nmodel.compile(optimizer=optimizer, loss=model.compute_loss, metrics=['accuracy'])\n\nmodel.fit(\n train_dataset.shuffle(100).batch(8),\n epochs=2\n)\n\n\nEverything works perfectly, as one would expect. But when I add the code (after I encode the topic)\n# Consider only Top n tags - want to keep a smaller dataset for testing\nn = 5\ntop_tags = df['topic_encoded'].value_counts()[:n].index.tolist()\ndf = df[df['topic_encoded'].isin(top_tags)].sort_values(by='topic_encoded', ascending=True).reset_index(drop=True)\n\nI get the error\ntensorflow.python.framework.errors_impl.InvalidArgumentError: Received a label value of 16 which is outside the valid range of [0, 5). Label values: 0 0 0 0 0 0 16 0\n [[node compute_loss/sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits (defined at \\Users\\Projects\\transformers_test\\venv\\lib\\site-packages\\transformers\\modeling_tf_utils.py:220) ]] [Op:__inference_train_function_12942]\n\nFunction call stack:\ntrain_function\n\nI have no idea why adding this causes this issue. Even if I specify loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) it still gives the same error.\nEDIT\nI have fiddled with splitting df in many ways, and it appears that anyway I slice it, df = df[df['topic_encoded'] == 1] for example, I will get a InvalidArgumentError. So the problem is somehow being caused by only taking a portion of the dataframe.\nAny help would be greatly appreciated."
] | [
"python",
"pandas",
"tensorflow",
"machine-learning",
"bert-language-model"
] |
[
"isinstance fails for a type imported via package and from the same module directly",
"/Project\n|-- main.py\n|--/lib\n| |--__init__.py\n| |--foo.py\n| |--Types.py\n\n\n/Project/lib has been added to the PYTHONPATH variables.\n\nTypes.py:\n\nclass Custom(object):\n def __init__(self):\n a = 1\n b = 2\n\n\nfoo.py:\n\nfrom Types import Custom\ndef foo(o):\n assert isinstance(o, Custom)\n\n\nFinally, from main.py:\n\nfrom lib.Types import Custom\nfrom lib.foo import foo\na = Custom()\nfoo(a)\n\n\nThe problem now is, that a is of type lib.foo.Custom, while the isinstance call will check if it equals foo.Custom, which obviously returns false.\n\nHow can I avoid this problem, without having to change anything in the library (lib)?"
] | [
"python",
"python-3.x",
"python-3.4"
] |
[
"Vuejs, change a button color in a list when its clicked",
"I have a list of buttons that I populate using an array of objects:\n <div\n class="form-inline"\n v-for="(genre, index) in genreArray"\n :key="index"\n >\n <button class="btn m-1" type="button" @click="genreButton(genre, index)" \n :class="[\n { 'clicked': clicked}\n ]"\n >\n {{ genre.name }}\n </button>\n </div>\n\n\nThe array has this format:\ngenreButton=[{\n id='1234'\n name='buttonOne'\n},\n//and many more objects with same key and different values\n]\n\nI try to change color of a button that is clicked by adding a class to it:\ndata(){\n return {\n clicked: false \n }\n},\nmethods:{\n genreButton(genre, index){\n this.clicked = !this.clicked\n }\n}\n\nand this is the CSS:\n.clicked{\n background-color= red;\n}\n\nBut the issue is when I do it all the buttons change color. How can I ONLY change the color of the button that is clicked?"
] | [
"javascript",
"html",
"css",
"vue.js",
"object"
] |
[
"Ruby associations not happening",
"I'm using Facebook Koala gem to pull in data pertaining to Events.\n\nPlease tell me why despite adding the correct event_id to venues, admins, attendees that I cannot then go @event.admins in the event view?\n\nCode in User.rb, after omniauth logs me in.\n\nevents[\"events\"][\"data\"].each do |event|\n if event[\"admins\"]\n event_admins = event[\"admins\"][\"data\"]\n if (is_admin_for_event? event_admins)\n\n @new_event = Event.where(fb_id: event[\"id\"]).first_or_create(\n name: event[\"name\"],\n description: event[\"description\"],\n location_id: event[\"location\"],\n start_time: event[\"start_time\"],\n end_time: event[\"end_time\"],\n ticket_uri: event[\"ticket_uri\"],\n privacy: event[\"privacy\"],\n admin_id: event[\"admin_id\"],\n updated_time: event[\"updated_time\"],\n created_at: event[\"created_at\"],\n updated_at: event[\"updated_at\"],\n user_id: self.id)\n\n @new_owner = Owner.where(fb_id: event[\"owner\"][\"id\"]).first_or_create(\n name: event[\"owner\"][\"name\"])\n @new_owner.event_id = @new_event.id\n @new_owner.save!\n\n event[\"admins\"][\"data\"].each do |admin|\n @new_admin = Admin.find_or_initialize_by(fb_id: admin[\"id\"])\n\n if !@new_admin.events.include?(@new_event.id)\n @new_admin.events << @new_event\n end\n @new_event.save!\n end\n\n @new_venue = Venue.where(fb_id: event[\"venue\"][\"id\"]).first_or_create(\n\n fb_id: event[\"venue\"][\"id\"],\n latitude: event[\"venue\"][\"latitude\"],\n longitude: event[\"venue\"][\"longitude\"],\n city: event[\"venue\"][\"city\"],\n state: event[\"venue\"][\"state\"],\n country: event[\"venue\"][\"country\"],\n street: event[\"venue\"][\"street\"],\n zip: event[\"venue\"][\"zip\"])\n\n if !@new_venue.events.include?(@new_event)\n @new_venue.event_id = @new_event.id\n @new_event.venues\n @new_venue.save!\n end \n\n event[\"attending\"][\"data\"].each do |attendee|\n new_attendee = Attendee.where(fb_id: attendee[\"id\"]).first_or_create(\n name: attendee[\"name\"],\n first_name: attendee[\"first_name\"],\n last_name: attendee[\"last_name\"],\n email: attendee[\"email\"],\n rsvp_status: attendee[\"rsvp_status\"],\n picture_url: attendee[\"picture\"][\"data\"][\"url\"],\n event_id: @new_event.id) \n end\n\n if event.has_key?(\"maybe\")\n event[\"maybe\"][\"data\"].each do |attendee|\n new_attendee = Attendee.where(fb_id: attendee[\"id\"]).first_or_create(\n name: attendee[\"name\"],\n first_name: attendee[\"first_name\"],\n last_name: attendee[\"last_name\"],\n email: attendee[\"email\"],\n rsvp_status:attendee[\"rsvp_status\"],\n picture_url:attendee[\"picture\"][\"data\"][\"url\"],\n event_id: Event.last[\"id\"])\n end\n end\n end #/ is_admin_for_event?\n end #/event[admins]\n\n\nWhile using pry in numerous places I get \"nil\" when trying @new_event.admins but when I try to say @new_event.admins << Admin.first it doesn't understand << as a method. Whole repository found here: https://github.com/josephdburdick/anycrawl\n\nThanks."
] | [
"ruby",
"facebook-graph-api",
"ruby-on-rails-4",
"associations",
"koala"
] |
[
"Avoid redundant flex/flex-grow when expanding children to fill parent height",
"Is there a way to position a nested element at the bottom of a container distant parent container, without manually setting all nested wrappers to be flex/flex-grow? Ie, less CSS rules.\n\n\r\n\r\n* {\r\n box-sizing: border-box;\r\n}\r\n\r\n.example {\r\n display: flex;\r\n}\r\n.example .body-B {\r\n margin-left: 1rem;\r\n}\r\n\r\n.body-B {\r\n display: flex;\r\n}\r\n.body-B .wrapper-1,\r\n.body-B .wrapper-2 {\r\n display: flex;\r\n flex-grow: 2;\r\n}\r\n.body-B .wrapper-1 {\r\n flex-direction: column;\r\n}\r\n.body-B .actions {\r\n align-items: flex-end;\r\n display: flex;\r\n width: 100%;\r\n justify-content: space-evenly;\r\n}\r\n\r\n[class^=body] {\r\n border: 5px solid black;\r\n height: 500px;\r\n width: 23rem;\r\n}\r\n[class^=body] .title {\r\n border: 3px dotted grey;\r\n display: flex;\r\n justify-content: center;\r\n}\r\n[class^=body] .wrapper-1 {\r\n border: 3px solid green;\r\n}\r\n[class^=body] .wrapper-2 {\r\n border: 3px solid red;\r\n}\r\n[class^=body] .actions {\r\n border: 3px solid blue;\r\n}\r\n<div class=\"example\">\r\n <div class=\"body-A\">\r\n <div class=\"wrapper-1\">\r\n <p class=\"title\">Naturally positioned at top</p>\r\n <div class=\"wrapper-2\">\r\n <div class=\"actions\">\r\n <button class=\"action\">click</button>\r\n <button class=\"action\">click</button> \r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n <div class=\"body-B\">\r\n <div class=\"wrapper-1\">\r\n <p class=\"title\">Lots of<code>display: flex</code></p>\r\n <div class=\"wrapper-2\">\r\n <div class=\"actions\">\r\n <button class=\"action\">click</button>\r\n <button class=\"action\">click</button> \r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n</div>\r\n\r\n\r\n\n\nIs there a property/patter that would allow this basic functionality to apply to all children?"
] | [
"html",
"css",
"sass",
"flexbox"
] |
[
"Scrolling SKReferenceNodes from sks files",
"I want to scroll SKReferenceNodes created with my sks files I put together in the interface builder. I have scrolled SKSpriteNodes before, and I am trying to use the same code, but my SKReferenceNodes seem to have no frame, and so I can't position them.\n\nHere is my SKReferenceNode setup:\n\nlet BG_POINTS_PER_SEC = 50\nvar dt:NSTimeInterval = 0\nlet background1 = SKReferenceNode(fileNamed:\"BackgroundScene1\")\nlet background2 = SKReferenceNode(fileNamed:\"BackgroundScene2\")\n\n\nin didMoveToView\n\nbackground1.position = CGPointZero;\nbackground2.position = CGPointMake(background1.frame.size.width, 0)\n\nself.addChild(background1)\nself.addChild(background2)\n\n\nin update\n\nmoveBackground()\n\nfunc moveBackground() {\n let bgVelocity = CGPoint(x:-BG_POINTS_PER_SEC, y:0)\n let amtToMove = bgVelocity *CGFloat(dt)\n background1.position = background1.position + amtToMove\n background2.position = background2.position + amtToMove\n if (background1.position.x <= background1.frame.size.width) {\n background1.position.x = CGPointMake(background2.position.x + background2.frame.size.width, background1.position.y)\n }\n if (background2.position.x <= background2.frame.size.width) {\n background2.position.x = CGPointMake(background1.position.x + background1.frame.size.width, background2.position.y)\n }\n}\n\n\nAgain this works for the scrolling background using a SKSpriteNode, but the SKReferenceNode returns a 0 frame. Is this even possible to scroll SKReferenceNodes from sks files like this?"
] | [
"ios",
"swift",
"sprite-kit"
] |
[
"How do I write a findMany that will get in chunks?",
"Ember 1.5.1\nEmber-Data 1.0 beta 7\n\nI've tried to modify the DS.ActiveModelAdapter's findMany so it'll get in chunks of 40... this is because I can't use the links feature and it seems to be generating 400 errors because it has too many ids in the URL its creating.\n\nI tried using this adapter, but I keep getting error messages that look like this:\n\n Error: Assertion Failed: Error: no model was found for 'super'\n\n\nHere's my Adapter:\n\n App.ApplicationAdapter = DS.ActiveModelAdapter.extend({\n findMany: function(store, type, ids) {\n self = this;\n return new Ember.RSVP.Promise(function(resolve, reject) {\n var idsPerRequest = 40;\n var totalIdsLength = ids.length;\n var numberOfBins = Math.ceil( totalIdsLength / idsPerRequest ); // number per bin\n var bins = [];\n ids.forEach( function(someId, index) {\n var thisBinIndex = index % numberOfBins;\n var thisBin = Ember.A( bins[thisBinIndex] );\n thisBin.pushObject(someId);\n bins[thisBinIndex] = thisBin;\n });\n\n var requestPromises = bins.map(function(binOfIds) {\n return self.ajax(self.buildURL(type.typeKey), 'GET', { data: { ids: binOfIds } });\n });\n\n Ember.RSVP.all(requestPromises).then(function(resolvedBinRequests) {\n var resolvedObjects = Em.A([]);\n resolvedBinRequests.forEach(function(resolvedBin) {\n resolvedObjects.addObjects(resolvedBin);\n });\n resolve(resolvedObjects);\n }, function(error) {\n reject(error);\n });\n });\n }\n });\n\n\nCan anyone help me out with this? It'd be really appreciated. Am I just missing something obvious or have I perhaps done something silly?\n\nThanks in advance!\n\n[edit] Okay so further to this I've figured out why it's not working, and that's because the response that's coming back is a promise for the JSON payload, but what I'm doing is joining multiples of these into an array and returning that... which obviously won't be right... but what I need to do is merge the arrays inside the objects returned into one, I think (in concept)... I'm not really sure how to do this in actuality, though... I've tried various things, but none of them seem to work well... :("
] | [
"ember.js",
"ember-data"
] |
[
"Generating thumbnail from original bitmap string received on PHP server",
"I'm sending a full size bitmap (500x500) in base 64 string to a PHP server. When I received the data, I want to decode it and generate two JPEGS: one in the original size, and one smaller (thumbnail). Here's my original code:\n\n<?php\n $base=$_POST['originalImage']; // Bitmap in 500x500\n $binary=base64_decode($base);\n\n // ?? How to generate binary for bitmap in 200x200?\n?>"
] | [
"php",
"encoding",
"bitmap"
] |
[
"How to refresh the multiple select box when the model is updated in AngularJs",
"Please see the following jsfiddle. I put a simple example here to explain what I want to achieve.\n\nhttps://jsfiddle.net/nz9h6aje/1/\n\nhtml page:\n\n<div ng-app=\"testApp\" ng-controller=\"testCtrl\">\n1- <md-input-container>\n<label>Question</label>\n<input ng-model=\"models.Question1\">\n</md-input-container>\n2- <md-input-container>\n<label>Question</label>\n<input ng-model=\"models.Question2\">\n</md-input-container>\n<md-select placeholder=\"Dependency\" ng-model=\"models.Denpendency\" md-on-open=\"getQuestionSet()\" style=\"min-width: 300px;\" multiple>\n<md-option ng-value=\"setQuestion\" ng-repeat=\"setQuestion in setQuestions\">{{setQuestion}}</md-option>\n</md-select>\n</div>\n\n\njs file:\n\nangular.module('testApp', ['ngAnimate',\n'ngAria',\n'ngMaterial']).controller('testCtrl',function($scope){\n$scope.models={\nQuestion1:\"\",\nQuestion2:\"\",\nDependency:[] \n}\n\n$scope.getQuestionSet = function() {\n $scope.setQuestions = [];\n var tmpQuestion = 1 + \" - \" +$scope.models.Question1;\n $scope.setQuestions.push(tmpQuestion);\n tmpQuestion = 2 + \" - \" +$scope.models.Question2;\n $scope.setQuestions.push(tmpQuestion);\n};\n\n $scope.$watch('models', function (newVal, oldVal) {\n if (newVal.Question1 !== oldVal.Question1) {\n var tmpQuestion = 1 + \" - \" +$scope.models.Question1;\n $scope.models.Dependency[0] = tmpQuestion;\n }\n if (newVal.Question2 !== oldVal.Question2) {\n var tmpQuestion = 2 + \" - \" +$scope.models.Question2;\n $scope.models.Dependency[1] = tmpQuestion;\n }\n}, true);\n\n});\n\n\nThe value of the multiple selected box will change when the question changes. I have a model models.Dependency that stores the selected value of this multiple selected box. When the two questions changes, the selected value stored in the models.Dependency will changed as well. My codes now can change the models.Dependency when the questions changes. But the display of the selected box won't change. What should I do to refresh the multiple selected box to reflect the new data in models.Dependency. \n\nFor example, the two questions are 1- Question 1, 2-Question 2. Then when I click the multiple select box, I will see two options: 1-Question 1, 2-Question 2. When I changes the Questions, the options will change as well. \nIf I selected both of these two Questions, the multiple select box will display as \"1-Question 1, 2-Question 2\". If I changes the value of Question 1 to \"New Question 1\". The display of the multiple select remains the same. But if you click it, you will see the options has already been changed. The changed option is not selected. This is not correct. I want the changed option is selected and the display of this multiple select box also changes to \"1-New Question 1, 2-Question 2\".\n\nI hope I explain my requirement clearly.\nThank you."
] | [
"javascript",
"angularjs"
] |
[
"React infinite loop caused by component",
"I'm currently in the process of learning react and have come across a problem has had me stuck for most of the day. I have two simple components. Once called IncidentsBoard which holds other components called Incidents. \n\nThe idea is that (using dummy data) the IncidentBoard will show incidents of car crashes on it. My code: \n\nIncidentBoard:\n\nimport React from 'react';\nimport Incident from './Incidents';\nimport testData from './testdata';\n\nclass IncidentBoard extends React.Component {\n\n constructor(props) {\n super(props);\n this.state = {\n data: testData.features,\n filtered: []\n }\n }\n\n componentWillMount() {\n\n var filtered = this.state.data.filter( (incident, i) => {\n return incident.properties.event_type === 'Crash';\n })\n\n console.log(filtered);\n this.setState({filtered}) \n\n } \n\n render() {\n return <div>\n {this.state.filtered.map((incident, i) => {\n return <Incident id={i} description=\"swagg\" />\n })}\n </div>\n }\n}\nexport default IncidentBoard;\n\n\nIncident (which is currently mostly empty):\n\nimport React from 'react';\n\nclass Incident extends React.Component {\n\n render() {\n return <div><h1>test</h1></div>\n }\n\n}\n\nexport default Incident;\n\n\nWhen running this, it causes an infinite loop where componentWillMount() is run without end. I have also noticed that if I replace the Incident component in the render function in IncidentBoard that the error no longer happens. \n\nEDIT: More code\n\nindex.js\n\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport IncidentBoard from './Incidents';\n\nReactDOM.render(\n <IncidentBoard />, document.getElementById('react-container')\n)\n\n\ntestData is a just a big JSON object."
] | [
"javascript",
"reactjs"
] |
[
"Performance of Wolfram Mathematica InverseFunction",
"given the constants\n\nmu = 20.82;\nex = 1.25;\nkg1 = 1202.76;\nkp = 76.58;\nkvb = 126.92;\n\n\nI need to invert the function\n\nf[Vpx_,Vgx_] := Vpx Log[1 + Exp[kp (1/mu + Vgx/(Vpx s[Vpx]))]];\n\n\nwhere\n\ns[x_] := 1 + kvb/(2 x^2);\n\n\nso that I get a function of two variables, the second one being Vgx.\n\nI tried with\n\nt = InverseFunction[Function[{Vpx, Vgx}, f[Vpx, Vgx]], 1, 2];\n\n\ntested with t[451,-4]\n\nIt takes so much time that every time I try it I stop the evaluation.\n\nOn the other side, working with only one variable, everything works:\n\nVgx = -4;\nt = InverseFunction[Function[{Vpx}, f[Vpx,Vgx]]];\nt[451]\n\n\nIt's my fault? the method is inappropriate? or it's a limitation of Wolfram Mathematica?\n\nThanks\nTeodoro Marinucci\n\nP.S. For everyone interested it's a problem related to the Norman Koren model of triodes."
] | [
"performance",
"wolfram-mathematica"
] |
[
"How to read a large file using Nio2",
"I am trying to read a text file which has around 3 lakh lines as of now.\n\nHow am I reading? \n\nI am reading using the java.io.BufferedReader\n\nHere is a small code snippet which represents my approach.\n\nint lineNumber = 1;\nBufferedReader br = null;\nString currentLine = null;\nbr = new BufferedReader(new FileReader(f));//here f will be the file name to be read, I have passed\nwhile ((cuurentLine = br.readLine()) != null) {\n //here I have written logic to do processing after reading 1000 lines\n //line number = 1001 start processing, similarly it reads next 1000 lines, each line is put in a List collection\n //after reaching 1001 line clearing list and continuing the loop\n}\n\n\nI have tried using NIO2 the following case\n\nbr = Files.newBufferedReader(Paths.get(inputFileName), StandardCharsets.UTF_16);\n\n\nIt resulted in the follwoing exception\n\nexception :Exception in thread \"main\" java.lang.OutOfMemoryError: Java heap space\n at java.util.Arrays.copyOf(Unknown Source)\n at java.lang.AbstractStringBuilder.expandCapacity(Unknown Source)\n at java.lang.AbstractStringBuilder.ensureCapacityInternal(Unknown Source)\n at java.lang.AbstractStringBuilder.append(Unknown Source)\n at java.lang.StringBuffer.append(Unknown Source)\n at java.io.BufferedReader.readLine(Unknown Source)\n at java.io.BufferedReader.readLine(Unknown Source)\n at TexttoExcelMerger.readFileLineByLine(TexttoExcelMerger.java:66)\n at TexttoExcelMerger.main(TexttoExcelMerger.java:255)\n\n\nFirstly, Is my approach right?\n\nAre there any efficient and fast approaches in NIO2, apache FileUtils or any other API for reading a file faster, which improves my file reading \nprocess faster. Can I read set of lines like first 1000 like\nbr.readFirst(1000);,\nbut without reading line by line or iterating as in my logic?"
] | [
"java",
"file-io",
"nio2",
"fileutils"
] |
[
"Electrolysis compatibility shims doesn't work with evalInSandbox",
"We have a rather old XUL extension which we want to make sure works with Electrolysis. We will eventually migrate it to the WebExtensions API, but for now we want to use the compatibility shims.\n\nWe can access content stuff (using window.content for example) in the some of our scripts (e.g, the overlay scripts). However, our extension also load some scripts using evalInSandbox. It look something like this:\n\nvar sandbox = Components.utils.Sandbox(Components.classes[\"@mozilla.org/systemprincipal;1\"].createInstance(Components.interfaces.nsIPrincipal), {\n sandboxPrototype: window,\n wantXrays: false\n });\n// ...\nComponents.utils.evalInSandbox(script, sandbox, url, 0); \n\n\nWe don't seem to be able to access window.content on the scripts loaded in the sandbox. It seem like the shims don't work in this case. Is this a bug, or is it by design?\n\nThanks"
] | [
"firefox",
"firefox-addon",
"xul"
] |
[
"Use an SVG as background to an anchor element",
"I just started out with web development and am trying to build a simple tabbed website. I need an svg to fit perfectly behind an anchor element for all screen sizes but it shrinks down at lower sizes.\nHere's my HTML:\n\n <div id=\"seconddiv\">\n <h1>Example</h1>\n <nav>\n <a class=\"uls\" href=\"index.html\"><p>HOME</p></a>\n <a class=\"ul\" href=\"booking.html\"><p>BOOK NOW</p></a>\n <a class=\"ul\" href=\"contact.html\"><p>CONTACT US</p></a>\n </nav> \n </div> \n\n\nThe CSS goes like this:\n\nnav a {\ntext-align: center;\nfloat: left;\nwidth: 28.3%;\nmargin: 0 2.5% 0 2.5%;\n}\n.uls {\nbackground: rgba(0, 0, 0, 0) url(\"../img/tab.svg\") no-repeat center;\nbackground-size: 100% 100%;\n}\n\n\nThis is the svg:\n\n<svg version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\"\nxmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 957 286\"\nstyle=\"enable-background:new 0 0 957 286;\" preserveAspectRatio=\"none\">\n<path id=\"Selector\" style=\"opacity:0.5;\" \nd=\"M0.5,0.351l0.042,0.083c68.195,1.743,84.244,55.248,97.075,\n124.907l28.816,124.17c3.923,19.925,16.566,36.839,\n36.814,36.839h628.131c20.248,0,33.468-16.507,\n36.814-36.839h- 0.009L857,125.342\nc13.045-70.825,29.376-124.99,100.5-124.99H0.5z\"/>\n</svg>\n\n\nHere's what it looks at standard size:\nStandard Size\n\nHere's the reduced size:\nReduced Size"
] | [
"html",
"css",
"svg",
"web",
"tabs"
] |
[
"How to draw rectangle on face image with the help of eye and nose coordinates?",
"I am trying to draw rectangle on face image.\nI have its eye location and nose location co-ordinates.\nSo how can I do that?\n\nEx.\n\nI have one image. I have its respected eye cordinates:\n\n\nNose:- 351 186 \nLeft Eye:-379 138\nRight Eye:- 309 149\n\n\nI want to draw rectangle covering face image.\nHow can I do that?\n\nI want to know how haarcascade do that.\n\nWhat measurement it takes to compute rectangle."
] | [
"image-processing",
"computer-vision",
"haar-classifier"
] |
[
"jQuery Datepicker: Only Select Fridays AND Disable One Specific Date",
"I currently have datepicker only allowing Fridays. I would like to continue to only allow Fridays, but modify this code to disable one date: 12-31-2010 (which happens to be Friday). I have seen code examples on how to disable dates, but I do not know how to add this functionality into my current code without breaking it.\n\nFriday Only Code:\n\n//Get todays date\nvar m_names = new Array(\"January\", \"February\", \"March\",\n\"April\", \"May\", \"June\", \"July\", \"August\", \"September\",\n\"October\", \"November\", \"December\");\n\nvar d = new Date();\nvar curr_date = d.getDate();\nvar curr_month = d.getMonth();\nvar curr_year = d.getFullYear();\n\n//Function for datepicker\n$(function () { \n $('#datepicker').datepicker({ \n minDate: (new Date(d)),\n beforeShowDay: function(d) {return ( 5==d.getDay()? [true,''] : [false,'']);} \n }); \n});"
] | [
"jquery",
"datepicker"
] |
[
"How to pass Area in Url.Action and a model",
"I am trying to use Url.Action to specify an action, controller, and a model that I use to specify the parameters. This would look something like this:\[email protected]( \"action\", \"controller\", model)\n\nI'm now trying to specify an Area as well. It appears that most suggestions are that you do it like this:\[email protected]( \"action\", \"controller\", new {Area = \"area\"})\n\nDoes anyone know how you specify a model and an Area?"
] | [
"asp.net"
] |
[
"Display flex is not working in IE",
"I'm trying to do the center alignment for the image in <div class=\"product-image-area\"> using display:flex;\n\nThat is working fine on Edge, Firefox and Chrome but not on IE.\n\nCSS:\n\n.horizontal {\n display: flex;\n justify-content: center;\n}\n\n.vertical {\n display: flex;\n flex-direction: column;\n justify-content: center;\n}\n\n\nFiddle Here: JS Fiddle\n\nResult in Edge,chrome and Firefox\n\n\nResult in IE"
] | [
"html",
"css",
"internet-explorer",
"flexbox",
"centering"
] |
[
"ag-Grid server-side row model with Redux integration",
"How does one setup a server-side row model in ag-Grid when using a Redux store as the source of truth?\nOn the ag-Grid website two guides are available:\n\na guide on how to setup a grid with a server-side row model. This guide is given here and it's not React / Redux specific. As such, it follows an imperative style and I am not sure it can be made to work with Redux.\na guide on how to setup ag-Grid with React / Redux. This guide is given here but seems to apply exclusively to a client-side row model.\n\nHow could one go about using a server-side row model in ag-Grid with Redux integration or is such an approach ill-advised given that the ag-Grid framework apparently does not cater to this?"
] | [
"reactjs",
"redux",
"react-redux",
"ag-grid",
"ag-grid-react"
] |
[
"My template of creating folders from error when opening",
"I have a project to create automatic folders. but is giving error when opening in xampp.It seems that when running xampp, you have a problem. I am running a local server for this.I am new to php. Sorry for the bad indentation of the code. This is my code:\n<?php \nrequire_once 'Util.php';\nrequire_once 'NewFolderProjectItem.php';\n\nclass NewFolderProjectList extends NewFolderProjectItem {\n\n protected $projListPackege;\n protected $projList;\n protected $projListForExecution;\n\n // === PROJECT LIST\n public function getProjList(string $projID = null) {\n if ($projID) {\n return isset($this->projList[$projID])?$this->projList[$projID]:null;\n }\n if (!$projID) {\n return $this->projList;\n }\n }\n public function getProjListByID(string $projID) {\n return isset($this->projList[$projID])?$this->projList[$projID]:false;\n }\n public function newProjList(string $client, string $project_macro, string $project_lot, string $project_model, string $source = null, string $structure = null) {\n $this->setOk(true);\n\n if (!$this->getValidateList()) {\n $this->setOk(false);\n $this->setErr('NewFolderProjectList::newProjList::basic', 'Ainda não foi carregado os dados de validação de listas');\n }\n\n if (!$this->getNormalizeList()) {\n $this->setOk(false);\n $this->setErr('NewFolderProjectList::newProjList::basic', 'Ainda não foi carregado os dados de normalização de listas');\n }\n\n if ($this->getOk() && $this->getClient()) {\n $this->setOk(false);\n $this->setErr('NewFolderProjectList::newProjFolder::load', 'Já existe dados carregados');\n }\n\n if ($this->getOk()) {\n $this->setClient($client);\n $this->setProjMacro($project_macro);\n $this->setProjLot($project_lot);\n $this->setProjFolderModel($project_model);\n\n if ($source) {\n $this->setProjSource($source);\n }\n if ($structure) {\n $this->setProjStructure($structure);\n }\n }\n\n return $this->getOk();"
] | [
"php"
] |
[
"Error with transfering MySQL database (connected via PDO) from localhost to hosted server",
"Okay, so this is my code:\n\ntry {\n$pdo = new PDO ('mysql:host=127.0.0.1;dbname=db_name','user','password'); \n} catch (PDOException $e) {\nexit ('Database error.');\n}\n\n\nI tried so many different combinations with host name, username and password, and every time I get 'Database error'.\n\nMy question is: \nWhat should I do to succesfully transfer MySQL database from localhost to my hosted server using this part of code (which is my connection.php file)? \n\nThank you, in advance."
] | [
"php",
"mysql",
"pdo",
"localhost"
] |
[
"How to load images from html in the AsyncTask",
"In the AsyncTask, I am getting a json with some of the values as images. Below is the sample of my json\n\n{ \n \"text\": \"some text\",\n \"html1\": \"Hi, check out my fb profile picture at <img src = 'http:\\/\\/abc.com/image1.png'\\/> \",\n \"html2\": \"Hi, check out my whatsapp profile picture at <img src = 'http:\\/\\/abc.com\\/image1.png'\\/> \",\n .\n .\n .\n}\n\n\nIn async task postExecute Method I have\n\n( ( TextView ) findViewById( R.id.html1 ) ).setText( Html.fromHtml( ( String ) jsonObj.get( \"html1\" ), new ImageGetter()\n{\n @Override\n public Drawable getDrawable( String source )\n {\n return loadImage( source );\n }\n}, null ) );\n ( ( TextView ) findViewById( R.id.html2) ).setText( Html.fromHtml( ( String ) jsonObj.get( \"html2\" ), new ImageGetter()\n {\n @Override\n public Drawable getDrawable( String source )\n {\n return loadImage( source );\n }\n }, null ) );\n\n\nand my loadImage method looks like below\n\nprivate Drawable loadImage( String source )\n {\n Drawable drawable = null;\n URL sourceURL;\n try\n {\n sourceURL = new URL( source );\n URLConnection urlConnection = sourceURL.openConnection();\n urlConnection.connect();\n InputStream inputStream = urlConnection.getInputStream();\n BufferedInputStream bufferedInputStream = new BufferedInputStream( inputStream );\n Bitmap bm = BitmapFactory.decodeStream( bufferedInputStream );\n\n // convert Bitmap to Drawable\n drawable = new BitmapDrawable( getResources(), bm );\n\n drawable.setBounds( 0, 0, bm.getWidth(), bm.getHeight() );\n\n }\n catch ( MalformedURLException e )\n {\n e.printStackTrace();\n }\n catch ( IOException e )\n {\n e.printStackTrace();\n }\n return drawable;\n }\n\n\nI think the code is suffice but I am getting android.os.NetworkOnMainThreadException\n\nI have added the internet permission in manifest.xml"
] | [
"java",
"android",
"android-asynctask"
] |
[
"Seeing No CUDA capable GPU detected after i upgraded to cuda 6.5 from 5.5",
"Hey i am receving the error : No CUDA capable GPU detected \nafter i upgraded from Cuda 5.5 to Cuda 6.5 .\n\nNvidia driver version i have is 331.49 .\n\nIs this compatible for running 6.5 version or what is the best stable version for cuda 6.5"
] | [
"cuda"
] |
[
"Building Linphone: ERROR: The following binaries are missing: ndk-build. Please install them",
"I'm attempting to build the Linphone app, according the instructions here:\n\nhttps://github.com/BelledonneCommunications/linphone-android\n\nWhen I run prepare.py, I get the following error:\n\n\n ERROR: The following binaries are missing: ndk-build. Please install them.\n\n\nI have my path set to include the NDK folder. The problem is, there's no ndk-build.exe in that folder, or anywhere on my machine. There's a ndk-build.cmd file, but the prepare.py is specifically looking for ndk-build.exe.\n\nI've downloaded and looked through android-ndk-r15c-windows-x86_64.zip, android-ndk-r16b-windows-x86_64.zip, android-ndk-r17c-windows-x86_64.zip and android-ndk-r18b-windows-x86_64.zip and none of them contain ndk-build.exe.\n\nI know I'm missing something, I'm just not sure what it is.\n\nHere's the line from prepare.py looking for ndk-build.exe:\n\nndk_build = find_executable('ndk-build')"
] | [
"android",
"android-ndk",
"linphone"
] |
[
"How to scrap tables from raster files (like .jpeg, .jpg, .png, .gif) and save in excel format?",
"I have been trying to extract a table from .jpg format to excel format. I'm aware how to do it if it's a .pdf or html file. Please find the script below. I would be grateful if someone could help me figure this out. \nThanks,\n\nlibrary(httr)\nlibrary(magick)\nlibrary(tidyverse)\nurl_template <- \"https://www.environment.co.za/wp-content/uploads/2016/05/worst-air-pollution-in-south-africa-table-graph-statistics-1024x864.jpg\"\npb <- progress_estimated(n=length(url_template))\n\nsprintf(url_template) %>% \n map(~{\n pb$tick()$print()\n GET(url = .x, \n add_headers(\n accept = \"image/webp,image/apng,image/*,*/*;q=0.8\", \n referer = \"https://www.environment.co.za/pollution/worst-air-pollution-south-africa.html/attachment/worst-air-pollution-in-south-africa-table-graph-statistics\", \n authority = \"environment.co.za\")) \n }) -> store_list_pages\n\nmap(store_list_pages, content) %>% \n map(image_read) %>% \n reduce(image_join) %>% \n image_write(\"SApollution.pdf\", format = \"pdf\") \n\nlibrary(tabulizer)\nlibrary(tabulizerjars)\nlibrary(XML)\nwbk<-loadWorkbook(\"~/crap_exercise/img2pdf/randomdata.xlsx\", create=TRUE) \n# Extract the table from the document\nout <- extract_tables(\"SApollution.pdf\") #check if which=\"the table number\" is there\n\n#Combine these into a single data matrix containing all of the data\nfinal <- do.call(rbind, out[-length(out)])\n\n# table headers get extracted as rows with bad formatting. Dump them.\nfinal <- as.data.frame(final[1:nrow(final), ])\n\n# Column names\nheaders <- c('#', 'Uraban area', 'Province', 'PM2.5 (mg/m3)')\n\n# Apply custom column names\nnames(final) <- headers\ncreateSheet(wbk, \"pollution\")\nwriteWorksheet(wbk,poptable,sheet='pollution', header=T)\nsaveWorkbook(wbk)"
] | [
"r",
"web-scraping",
"jpeg",
"excel-tables"
] |
[
"Cannot escape Insert Mode in ideaVim",
"I am unable to use the <Esc> key to leave insert mode and return to Normal Mode. This has 'apparently' happened without any known change, but could be related to a not-so-recent bump of my IntelliJ version (IntelliJIdea2019.1 -> IntelliJIdea2019.2).\n\nOne possible solution mentioned online that I tried was to disable, then re-enable ideaVim in Menu | Tools | Vim emulation. Trying this did not appear to solve the problem."
] | [
"macos",
"intellij-idea",
"jetbrains-ide",
"ideavim"
] |
[
"Audio Chat using socketio",
"I am new in nodejs.\n I am working on voice chat application , in the application client can speak and his sound will broadcasted (using nodejs server) to other clients , I used socketio to send sound from microphone to server, but I did not know how receiver sound in client, Can any one help me?\n\nClient code for send voice (I do not know if this true way to send voice from microphone):\n\nnavigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;\nnavigator.getUserMedia( {audio:true}, gotStream , onError ); \n function gotStream(stream) \n {\n var context;\n if (window.AudioContext) {\n context = new AudioContext();\n } else {\n context = new webkitAudioContext();\n }\n var mediastream = context.createMediaStreamSource(stream);\n var bufferSize = 2048;\n var myscriptnode = context.createScriptProcessor(bufferSize, 1, 1);\n myscriptnode.onaudioprocess = function (event) {\n var recordedData = event.inputBuffer.getChannelData(0);\n socket.emit('broadcast', recordedData);\n };\n\n mediastream.connect(myscriptnode);\n myscriptnode.connect(context.destination);\n\n }\n\n\n function onError()\n {\n\n }\n\n\nServer code for receiver from client:\n\nsocket.on('broadcast', function(data){\n socket.emit('broadcast', data);\n });\n\n\nClient code to recive sound: \n\n socket.on('broadcast', function(data){\n // I do not know what I must do here \n });"
] | [
"node.js",
"websocket",
"socket.io",
"chat",
"audio-streaming"
] |
[
"Pig UDF running on AWS EMR with java.lang.NoClassDefFoundError: org/apache/pig/LoadFunc",
"I am developing an application that try to read log file stored in S3 bucks and parse it using Elastic MapReduce. Current the log file has following format \n\n------------------------------- \nCOLOR=Black \nDate=1349719200 \nPID=23898 \nProgram=Java \nEOE \n------------------------------- \nCOLOR=White \nDate=1349719234 \nPID=23828 \nProgram=Python \nEOE \n\n\nSo I try to load the file into my Pig script, but the build-in Pig Loader doesn't seems be able to load my data, so I have to create my own UDF. Since I am pretty new to Pig and Hadoop, I want to try script that written by others before I write my own, just to get a teast of how UDF works. I found one from here http://pig.apache.org/docs/r0.10.0/udf.html, there is a SimpleTextLoader. In order to compile this SimpleTextLoader, I have to add a few imports, as \n\nimport java.io.IOException; \nimport java.util.ArrayList;\nimport org.apache.hadoop.io.Text; \nimport org.apache.hadoop.mapreduce.Job; \nimport org.apache.hadoop.mapreduce.lib.input.TextInputFormat; \nimport org.apache.hadoop.mapreduce.InputFormat; \nimport org.apache.hadoop.mapreduce.RecordReader; \nimport org.apache.hadoop.mapreduce.lib.input.FileInputFormat; \nimport org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit; \nimport org.apache.pig.backend.executionengine.ExecException; \nimport org.apache.pig.data.Tuple; \nimport org.apache.pig.data.TupleFactory;\nimport org.apache.pig.data.DataByteArray; \nimport org.apache.pig.PigException; \nimport org.apache.pig.LoadFunc;\n\n\nThen, I found out I need to compile this file. I have to download svn and pig running\n\nsudo apt-get install subversion \nsvn co http://svn.apache.org/repos/asf/pig/trunk \nant\n\n\nNow i have a pig.jar file, then I try to compile this file.\n\njavac -cp ./trunk/pig.jar SimpleTextLoader.java \njar -cf SimpleTextLoader.jar SimpleTextLoader.class \n\n\nIt compiles successful, and i type in Pig entering grunt, in grunt i try to load the file, using \n\ngrunt> register file:/home/hadoop/myudfs.jar\ngrunt> raw = LOAD 's3://mys3bucket/samplelogs/applog.log' USING myudfs.SimpleTextLoader('=') AS (key:chararray, value:chararray); \n\n2012-12-05 00:08:26,737 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 2998: Unhandled internal error. org/apache/pig/LoadFunc Details at logfile: /home/hadoop/pig_1354666051892.log\n\n\nInside the pig_1354666051892.log, it has \n\nPig Stack Trace\n---------------\nERROR 2998: Unhandled internal error. org/apache/pig/LoadFunc\n\njava.lang.NoClassDefFoundError: org/apache/pig/LoadFunc\n\n\nI also try to use another UDF (UPPER.java) from http://wiki.apache.org/pig/UDFManual, and I am still get the same error by try to use UPPER method. Can you please help me out, what's the problem here? Much thanks! \n\nUPDATE: I did try EMR build-in Pig.jar at /home/hadoop/lib/pig/pig.jar, and get the same problem."
] | [
"hadoop",
"amazon-web-services",
"apache-pig",
"amazon-emr"
] |
[
"What is this syntax in java ` Sets.SetView`?",
"Here is some code that I was trying to understand \n\npublic static <E> Sets.SetView<E> difference(final Set<E> set1, final Set<?> set2) {\n Preconditions.checkNotNull(set1, \"set1\");\n Preconditions.checkNotNull(set2, \"set2\");\n final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));\n return new Sets.SetView<E>() {\n public Iterator<E> iterator() {\n return Iterators.filter(set1.iterator(), notInSet2);\n }\n\n public int size() {\n return Iterators.size(this.iterator());\n }\n\n public boolean isEmpty() {\n return set2.containsAll(set1);\n }\n\n public boolean contains(Object element) {\n return set1.contains(element) && !set2.contains(element);\n }\n };\n}\n\n\nI am confuse on what the function is returning, when I use it, it would seems like the function is returning Sets.SetView<E>\n\nFor example\n\n Set<Integer> a = new HashSet<>();\n Set<Integer> b = new HashSet<>();\n a.add(1);\n Sets.difference(a, b); // is of type Sets.SetView<Long>\n\n\nWhat is the extra <E> prepend in front?\n\nAnd why does the actual return value contains method definition?\n\n return new Sets.SetView<E>() {\n public Iterator<E> iterator() {\n return Iterators.filter(set1.iterator(), notInSet2);\n }\n\n public int size() {\n return Iterators.size(this.iterator());\n }\n\n public boolean isEmpty() {\n return set2.containsAll(set1);\n }\n\n public boolean contains(Object element) {\n return set1.contains(element) && !set2.contains(element);\n }\n };"
] | [
"java"
] |
[
"deserialize json process is always incomplete",
"hello i am newbie at arduinojson. I want to parse the datajson from serial (sent raspi then hc12). when I print the data that I receive is correct but the deserialization process is always incomplete. what should i do to fix it?\n[code]\nint session = 1; \nint id = 1;\nint stand = 100;\n\n bytecounthc12 = -1 ; \n yield(); \n char Bufferhc12[len]; \n bytecounthc12 = HC12.readBytesUntil('#', Bufferhc12, len); /\n datastrhc12 = "";\n yield();\n if (bytecounthc12 > 0) { \n checkdatahc12 = true; \n for (int i = 0; i < bytecounthc12; i++) { \n datastrhc12 += Bufferhc12[i]; \n }\n if(datastrhc12.length() == len) {\n Serial.println(datastrhc12); \n \n//String datastrhc12 ="{\\"sessionid\\": 1,\\"idmeter\\": [1,2,3],\\"standmeter\\": [0,0,0],\\"state\\": [false,false,false],\\"uplink\\": false}";\n //datastrhc12 = '\\0'; //nullterminated dibutuhkan untuk json string\n \n\nStaticJsonDocument<350> doc;\n Serial.setTimeout(10000);\n DeserializationError err = deserializeJson(doc,Serial); \n if(err) {\n Serial.print(F("deserializeJson() failed: "));\n Serial.println(err.c_str()); \n return;\n }\n\nif the deserialization process could run i expected get, deserialize running because i define variable input manually in tet editor arduino like this\nString input = "{"sessionid": 1,"idmeter": [1,2,3],"standmeter": [0,0,0],"state": [false,false,false],"uplink": false}";\nand why couldnt if read from serial?\nif i use readStringUntil data doesnt complete so using readbyte so much better.\nhelp me plese for deserialize process, Thanks before\nwhen I print the data that I receive is correct but the deserialization process is always incomplete"
] | [
"serialization",
"deserialization",
"arduinojson"
] |
[
"How does one create a validator that depends on more than one value for Zend_Form?",
"I've got a form that has a single text field (for company):\n\nclass Cas_Form_Company extends Zend_Form\n{\n\n public function init()\n {\n $this->addElement('hidden', 'id');\n $this->addElement('text', 'name', array('label' => 'Name'));\n $this->addElement('submit', 'submit', array('label' => 'Create'));\n\n $name = $this->getElement('name');\n $name->addValidator('stringLength', false, array(2,45));\n $name->addValidator(new Cas_Model_Validate_CompanyUnique());\n\n $this->setMethod('post');\n $this->setAction(Zend_Controller_Front::getInstance()->getBaseUrl() . '/Company/Submit');\n }\n\n public function SetFromExistingCompany(Cas_Model_Company $company)\n {\n $this->getElement('id')->setValue($company->GetId());\n $this->getElement('name')->setValue($company->GetName());\n $this->getElement('submit')->setLabel('Edit');\n $this->addElement('submit', 'delete', array('label' => 'Delete', 'value' => 'delete'));\n }\n\n public function Commit()\n {\n if (!$this->valid())\n {\n throw new Exception('Company form is not valid.');\n }\n\n $data = $this->getValues();\n if (empty($data['id']))\n {\n Cas_Model_Gateway_Company::FindOrCreateByName($data['name']);\n }\n else\n {\n $company = Cas_Model_Gateway_Company::FindById((int)$data['id']);\n $company->SetName($data['name']);\n Cas_Model_Gateway_Company::Commit($company);\n }\n }\n}\n\n\nI've also created a little validator which enforces that I want companies to have unique names:\n\nclass Cas_Model_Validate_CompanyUnique extends Zend_Validate_Abstract\n{\n protected $_messageTemplates = array(\n 'exists' => '\\'%value%\\' is already a company.'\n );\n\n /**\n * @param string $value\n * @return bool\n */\n public function isValid($value)\n {\n $this->_setValue($value);\n $company = Cas_Model_Gateway_Company::FindByName($value);\n if ($company)\n {\n $this->_error('exists');\n return false;\n }\n\n return true;\n }\n}\n\n\nNow, this works just fine for creating new companies. The problem comes in when I want to allow editing of companies. This is because for an edit operation, while the company name needs to be unique, a form containing the name already pertaining to the given ID isn't an edit at all (and therefore is valid). That is, the form is valid if either the name doesn't already exist in the database, or the name given matches the name already assigned to that ID.\n\nHowever, writing this as a validator seems to be problematic, because the validator only gets the value it's working on -- not the ID in question.\n\nHow does one write a validator for this sort of thing?"
] | [
"zend-framework",
"zend-form",
"zend-validate"
] |
[
"xml parsing in iOS show null",
"I must read an XML file and read the id attribute within the XML file, but the dictionary out null. The xml is:\n\n <?xml version='1.0' encoding='UTF-8'?>\n <root>\n<event id=\"2\"></event>\n </root>\n\n\nMy code:\n\n - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName\nattributes:(NSDictionary *)attributeDict {\n\n NSLog(@\"elementName is %@\", elementName);\n // elementName is root\n NSLog(@\"AttributeDict is %@\", attributeDict);\n //AttributeDict is { } why?\n //I must extract \"id\" in event but does not entry\n\nif ([elementName isEqualToString:@\"event\"]){ \n\n NSLog(@\" %@\", elementName);\n\n}\n\n}"
] | [
"ios",
"xml",
"xml-parsing"
] |
[
"Read CSV line-by-line in Kotlin",
"I'm writing a simple import application and need to read a CSV file, show result in a grid and show corrupted lines of the CSV file in another grid.\n\nIs there any built-in lib for it or any easy pythonic-like way? \n\nI'm doing it on android."
] | [
"android",
"csv",
"kotlin"
] |
[
"After I changed ID Javascript, not working next \"click\" event, what is the problem?",
"let x = [\"1\", \"3\", \"5\"]\n\n$(\"#button\").click(\n function num() {\n $(\"#answers\").html(x[0])\n document.getElementById(\"button\").setAttribute(\"id\", \"button2\");\n }\n)\n\n$(\"#button2\").click(\n function num2() {\n $(\"#answers\").html(x[1])\n document.getElementById(\"button\").setAttribute(\"id\", \"button3\");\n }\n)\n\n$(\"#button3\").click(\n function num3() {\n $(\"#answers\").html(x[2])\n }\n)"
] | [
"javascript"
] |
[
"Highlight.js not workng on Laravel 5.3 Target Page",
"I am developing a Blog with Laravel 5.3. In the Add Post Page, I use CKEDITOR with Code Snippet Plugin. In this area Everything is OK. Code added in the textarea field by plugin is also become highlighted.\n\nIn the Target Page I added:\n\n<link rel=\"stylesheet\" href=\"//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.8.0/styles/default.min.css\">\n\n\nIn the Header section of the page.\n\nand\n\n<script src=\"//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.8.0/highlight.min.js\"></script>\n<script>hljs.initHighlightingOnLoad();</script>\n\n\nIn the footer section of the page.\n\nThe page received the following html code from the Database.\n\n&lt;p&gt;The place for Laravel Blade Template.&lt;/p&gt;\n&lt;pre&gt;\n&lt;code class=&quot;language-html&quot;&gt;&lt;div&gt;&lt;h1&gt;\nThis is a Header&lt;/h1&gt;&lt;/div&gt;&lt;/code&gt;&lt;/pre&gt;\n\n&lt;p&gt;&nbsp;&lt;/p&gt;\n\n\nwhich is showing like this.\n\n<p>The place for Laravel Blade Template.</p> <pre> \n<code class=\"language-html\"><div><h1>This is a Header</h1></div></code>\n</pre> <p> </p> \n\n\nSo the code section is not highlighted.\n\nHow can I do that. What's my wrong? I need Help."
] | [
"laravel",
"highlight"
] |
[
"Control Multiple Android Devices",
"I want to be able to connect and control multiple android devices remotely via the Internet, sending the same command to each device simultaneously.\n\nI do not need many functions, although some extra features would really help but will get to that later,\nI need to be able to upload new media content to each device and then display that media content on each device, that is it. (am open on how to display media, whether slide show or single video does not matter, sound not needed/optional)\n\nAll devices will be identical and will not be used for anything else.\n\nIt would also be nice if I could remotely check if devices are switched on and running normally.\n\nI do know I can get remote access apps, but this would mean connecting to each device one by one which is not an option, as eventually looking to control about at least 5 devices.\n\nSomeone please let me know if this is possible, whether it's already possible or whether it can be developed.\n\nThanks in advance to those who reply with anything helpful"
] | [
"android"
] |
[
"python dictionary for students records",
"i am trying to create a program in python 3 where it will ask the user to input the students name(name) and his/hers ID numbers(ID) all in one go separated by comma. Then present all the dictionary values in the following format eg:\nName:John ID:123\nName:Mary ID:234\nName:Eve ID:345\nthe program will run forever unless the user inputs q to exit\n\nup to now i managed to create the following:\n\naddName = raw_input(\"New Name:\")\naddid = raw_input(\"ID:\")\ndictionary = {}\ndictionary[addName] = addid\nprint('Name: ' + addName + ' ID: ' + addid)\n\n\ni would like to have the program run continuesly, unless the user enters q to exit. How can i do the input in one line so the user will input its name and then its id, separated by comma? Also print all Names and IDs that the dictionary contains."
] | [
"python-3.x"
] |
[
"How to get latest tag name not using `git fetch --tags`",
"There has been an answer said how to get a latest tag, https://stackoverflow.com/a/7979255/7909869. But the premise is we must use git fetch --tags first after I use git clone REPO --depth=1. My REPO has many tags that means git fetch --tags will take a lot of time to download tags, and my request here is just to get the latest tag name not the whole code."
] | [
"git"
] |
[
"whether gremlin needs to store all data in java?",
"gremlin is a graph query language developed by stephen mallette, etc.\napache tinkerpop.\n\nI looked through its open source and found it provide API for developers(vendors). And I have a question whether I can use an OLTP or OLAP written in other languages, not java, as my graph system. \n\nI guess it maybe difficult because I think the java class containing data like edges, vertexes and their properties need to be calculated in GraphProgram or VertexProgram process in gremlin. If I want to use gremlin to make a query for my graph, I have to copy one complete data in java and implement the necessary function to override the provided interface. Is that right? Could anyone give me any suggestions?"
] | [
"java",
"graph",
"gremlin",
"tinkerpop",
"tinkerpop3"
] |
[
"The script which runs python in shell",
"I am running python on Linux.\nI want to know the script which runs the python interpreter.\n\nMeaning, Whenever i run the command python on a linux shell, a Python prompts opens and get input from keyboard and take those inputs to the underlying python interpreter.I want to know which shellscript (or python script) does this?. I want to know the location of it."
] | [
"python",
"linux",
"shell"
] |
[
"png's to ffmpeg conversion`",
"I have a bunch of png images that I want to feed through ffmpeg to create a animation.\n\nAnybody have some guidelines or ideas as to how I can achieve this?"
] | [
"ffmpeg",
"png"
] |
[
"Using get_terms which have posts, which these posts have a custom field",
"I have a custom taxonomy ('itemtype') which is used on a custom post type only ('item').\n\nI want to display all the terms which have posts, however only the terms which posts have custom meta.\n\nAny ideas. \n\nIve tried this but it does not work and shows as empty:\n\n$terms = get_terms(array(\n 'taxonomy' => 'itemtype',\n 'hide_empty' => true, \n 'meta_query' => array(\n array(\n 'key' => 'is_archived',\n 'value' => '1',\n 'compare' => '='\n )\n ),\n ));\n\n\nIn a nutshell, It should find all of the terms which have posts that match that meta_query, hiding any empty.\n\nThanks in advance."
] | [
"wordpress",
"wordpress-theming",
"custom-taxonomy"
] |
[
"How to initialize the value property of a radio button group in Angular?",
"I am trying to display a text-field based on the selected value of a radio button group.\n\nIf the user selects \"Yes\", then I want to display the text-field. If the user selects \"No\", then I don't want to display this text-field.\n\nBelow is my HTML:\n\n <radio-button-wrapper\n [(ngModel)]=\"damageReported\"\n name=\"rdoDamageReported\">\n\n <radio\n id=\"preselection_damageReported_01\"\n heading=\"Yes\"\n name=\"validationDamageReported\"\n value=\"Yes\">\n </radio>\n\n <radio \n id=\"preselection_damageReported_02\"\n heading=\"No\"\n name=\"validationDamageReported\"\n value=\"No\"\n (click)=\"clearSecondCompanyFields()\">\n </radio>\n</radio-button-wrapper>\n\n<div class=\"form-group\" *ngIf=\"damageReported.value === 'Yes'\">\n <label\n for=\"txtOtherCompanyName\"\n class=\"control-label\">\n Please state the name of the other insurance company:\n </label>\n <input\n class=\"form-control\"\n id=\"txtOtherCompanyName\"\n name=\"txtOtherCompanyName\"\n [(ngModel)]=\"otherCompanyName\"\n type=\"text\"/>\n</div>\n\n\nIn my .TS file, I have this uninitialized variable:\n\npublic damageReported;\n\n\nThe error message I am getting in the console is: \n\n\n TypeError: _co.damageReported is undefined\n\n\nI know this is because I haven't initialized damageReported in my .TS file. \n\nBut if I initialize it like so: damageReported = '';\n\nI get this compile error when I try to use the radio button value at a later stage in the code:\n\nthis.postData(\n this.damageReported.value\n)\n\n\npostData(\n damageReported: string\n)\n\n\n\n Property 'value' does not exist on type 'string'.ts(2339)\n\n\nCan someone please show me how I can initialize the variable while also being able to use the .value property? Thanks a lot!"
] | [
"angular"
] |
[
"Create a new thread only when a previous one finished",
"I am working on a system with 4 cores. My code can be split up into parts that each work independently, but that require a significant amount of memory. \n\nIs it possible to make my system wait for a thread to finish before creating a new one, such that I only have 4 threads running simultaneously, while still using all my cores completely?"
] | [
"c++",
"multithreading"
] |
[
"get text content of an element by jquery",
"I want to get content of my dt s an set them as value attr of input.\nthis is my code.\n\n//Html/php inline\n\n$c=1;\n while($user=mysqli_fetch_array($usersQryResult)){\n echo\"\n <tr>\n <td>$c</td>\n <td>$user[user]</td>\n <td>$user[pass]</td>\n <td>$user[email]</td>\n <td>$user[level]</td>\n <td>$user[status]</td>\n <td>$user[lastlogin]</td>\n <td><i onclick=\\\"editUser($user[id],this)\\\" class='fa fa-pencil-square-o' title='edit user info'></i></td>\n <td><i onclick=\\\"deleteUser($user[id],this)\\\" class='fa fa-trash-o deletUser' title='remove user' ></i></td> \n </tr>\n \";\n $c++;\n\n\n//js/jquery\n\nfunction editUser(id,thisObj){\n var contents=$(thisObj).parent().siblings().text();\n $(\"#chUserName\").val(contents[1]);\n $(\"#chUserPass\").val(contents[2]);\n $(\"#chUserEmail\").val(contents[5]);\n}\n\n\nbut contens[1],contents[2],content[3] return 3 characters of my userName: for example: \"Hamid\" . will return H a m !!!?/"
] | [
"javascript",
"jquery",
"html"
] |
[
"Extract specific words using regex or substring from a column in R",
"I have the below data:\n\n Opex_Spend_Month Opex_Spend_YTD Major_Category NBS_Region Sub_Category\n92179.84 113542.84 Contingent Labour EUROPE TEMP:OTH.CONT.WORKER\n297.82 82392.82 Contingent Labour EUROPE TEMP:OTH.CONT.WORKER\n13974.8 34917.8 Contingent Labour EUROPE TEMP:OTH.CONT.WORKER\n138.6 63125.6 Contingent Labour EUROPE TEMP:OTH.CONT.WORKER\nNA 73097 Contingent Labour EUROPE TEMP:MSP NON IT\nNA 96035 Contingent Labour EUROPE TEMP:MSP NON IT\n1388.65 68934.65 Contingent Labour EUROPE TEMP:MSP NON IT\n5393.76 18748.76 Contingent Labour EUROPE TEMP:MSP IT\n528.38 82195.38 Contingent Labour EUROPE TEMP:MSP IT\n22369 95468 Contingent Labour EUROPE TEMP:MSP IT\n\n\nFrom the column Sub_Category I want to be able to select the last parts of Cont Worker, Non IT & IT and I am not sure what regex or substring function to use.\n\nDesired Output\n\nOpex_Spend_Month Opex_Spend_YTD Major_Category NBS_Region Sub_Category Category\n92179.84 113542.84 Contingent Labour EUROPE TEMP:OTH.CONT.WORKER Cont Worker\n297.82 82392.82 Contingent Labour EUROPE TEMP:OTH.CONT.WORKER Cont Worker\n13974.8 34917.8 Contingent Labour EUROPE TEMP:OTH.CONT.WORKER Cont Worker\n138.6 63125.6 Contingent Labour EUROPE TEMP:OTH.CONT.WORKER Cont Worker\nNA 73097 Contingent Labour EUROPE TEMP:MSP NON IT Non IT\nNA 96035 Contingent Labour EUROPE TEMP:MSP NON IT Non IT\n1388.65 68934.65 Contingent Labour EUROPE TEMP:MSP NON IT Non IT\n5393.76 18748.76 Contingent Labour EUROPE TEMP:MSP IT IT\n528.38 82195.38 Contingent Labour EUROPE TEMP:MSP IT IT\n22369 95468 Contingent Labour EUROPE TEMP:MSP IT IT\n\n\nCan someone please help me with this??"
] | [
"r",
"regex",
"text",
"substr"
] |
[
"Splash screen too slow in Xamarin Android",
"I'm creating an app that shows a splash screen and then creates the main activity. I'm following this tutorial that seems pretty straight forward: https://developer.xamarin.com/guides/android/user_interface/creating_a_splash_screen/\n\nAfter implementing that I can successfully see the splash but there are some times (1 out of 20) that with an S5 I see the following screen:\n\n\n\nFollowed by the (right) splash (taken from the Emulator but just to make my point):\n\n\n\nSo my guess would be that sometimes Xamarin is taking to long to load the app therefore it has a delay showing the splash. Is there any way to prevent that?\n\nUPDATE 1\nI've followed the tutorial but I've removed the sleep for this:\n\nInsights.Initialize (\"<APP_KEY>\", Application.Context);\nStartActivity(typeof (MainActivity));"
] | [
"android",
"xamarin",
"xamarin.android"
] |
[
"How to synchronize client IDs from different devices (Android, iPhone, etc.) and backend server IDs",
"I am syncing using SyncAdapter, custom ContentProvider and AccountManager services. I am a bit stucked with the synchronization implementation. I have been greatly helped by the SDK example \"SampleSyncAdapter\" for Contacts which stores the mobile device IDs (_id in Android) in the server tables so when it responds with the dirty list, the device knows whether to add or update content. \n\nDoes this pattern mean that I have to add a new server side columns for every client? I might support other platforms in the future (e.g. iPhone data IDs - I'm not familiar with its SDK)."
] | [
"android",
"synchronization",
"android-syncadapter"
] |
[
"Unable to start the chipKit BasicIOShield with PIC32 using PICKIT3 programmer",
"I have chipKit uC32 (PIC32MX340F512H) ,chipkit BasicIOShield and PICkit3\nprogrammer all from the Microchip.\n\nI'm using MPLABX IDE.\n\nSince I'm very new to this so I didn't know where to start I have searched and look at the web and find only tutorial which using MPIDE which I'm not allowed to use in my project.\nI have read the Reference manual and Data sheet for and make test project but any way the uC32 Board refuse to recognize the BasicIOShield and I was unable to connect this two together.\n\nAny tips and link would be great. Thanks in advance."
] | [
"embedded",
"microcontroller",
"led",
"mplab",
"pic32"
] |
[
"Extract line with regexp php",
"http://www.goldfixing.com/vars/goldfixing.vars\nI have this file, and there is\nthis line\n\n&pmeuro=983.327 &\n\nHow can I extract only number from that file? \n\nBest regards."
] | [
"php",
"regex",
"numbers",
"extract"
] |
[
"rounded recyclerview with cardview item inside",
"I have rounded RecyclerView in top right and top left corner with Drawable file\n<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">\n <corners android:topLeftRadius="30dp"\n android:topRightRadius="30dp"/>\n <solid android:color="#eee"/>\n</shape>\n\nand use CardView as item for RecyclerView\nproblem is here that when I scroll RecyclerView, items come over on RecyclerView in corners.\ncan anyone tell me what is my mistake or show me how to fix this?\ncode of layout\n<?xml version="1.0" encoding="utf-8"?>\n<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"\n xmlns:app="http://schemas.android.com/apk/res-auto"\n xmlns:tools="http://schemas.android.com/tools"\n android:layout_width="match_parent"\n android:layout_height="match_parent"\n android:background="#ff0000"\n tools:context=".MainActivity">\n\n\n <androidx.recyclerview.widget.RecyclerView\n android:background="@drawable/bg"\n android:layout_marginTop="100dp"\n android:id="@+id/recyclerView"\n android:layout_width="0dp"\n android:layout_height="0dp"\n app:layout_constraintBottom_toBottomOf="parent"\n app:layout_constraintEnd_toEndOf="parent"\n app:layout_constraintStart_toStartOf="parent"\n app:layout_constraintTop_toTopOf="parent" />\n\n\n</androidx.constraintlayout.widget.ConstraintLayout>\n\nI expect see List Items comes under the RecyclerView in top left and top right corner\nbut see this image of problem"
] | [
"android",
"android-recyclerview",
"cardview",
"radius"
] |
[
"How to read Avro data and put the Avro fields into dataframe Columns using Spark Structured Streaming 2.1.1?",
"Code from the website \n\nDataSet<Row> ds = sparkSession.readStream()\n .format(\"com.databricks.spark.avro\")\n .option(\"avroSchema\", schema.toString)\n .load();\n\n\nSince Avro Messages has fields. I am wondering how to put each field of the message in a separate column of a DataSet/Dataframe ? Does the above code automatically do that?\n\nI"
] | [
"java",
"apache-spark",
"apache-spark-sql"
] |
[
"Create a folder in google drive php",
"Is there any way we could create a folder on google drive using PHP? I've been searching all the web for the last 72 hours with no results.\nWhat do you think guys?\nThanks !"
] | [
"php",
"directory",
"google-drive-api",
"google-drive-realtime-api"
] |
[
"Socket.io connection event not fired on server",
"I am trying to build a command-line chat room using Node.js and Socket.io.\n\nThis is my server-side code so far, I have tried this with both http initialisations (with express, like on the official website's tutorial, and without it):\n\n#app = require('express')()\n#http = require('http').Server(app)\nhttp = require('http').createServer()\nio = require('socket.io')(http)\n\n\nio.sockets.on 'connect', (socket) ->\n console.log 'a user connected'\n\n\nhttp.listen 3000, () ->\n console.log 'listening on *:3000'\n\n\nI start this with nodejs server.js, the \"Listening on\" is showing up.\n\nIf I run lsof -i tcp:3000, the server.js process shows up.\n\nHowever, when I start this client-side code:\n\nsocket = require('socket.io-client')('localhost:3000', {})\n\nsocket.on 'connect', (socket) ->\n console.log \"Connected\"\n\n\nNo luck... When I run nodejs client.js, neither \"connect\" events, from server nor client, are fired!\n\nMy questions are :\n- What am I doing wrong? \n- Is it necessary to start a HTTP server to use it? Sockets are on the transport layer, right? So in theory I don't need a HTTP protocol to trade messages."
] | [
"node.js",
"coffeescript",
"socket.io"
] |
[
"Why Consumer thread is not able to remove messages from Vector?",
"I am trying to create a solution for Producer/ Consumer problem where one thread is putting message in Vector and another is removing from it.\n\nimport java.util.Vector;\npublic class Producer implements Runnable {\n static final int MAXQUEUE = 5;\n private Vector<String> messages;\n\n public Producer(Vector<String> messages) {\n super();\n this.messages = messages;\n }\n\n @Override\n public void run() {\n try {\n while (true) \n putMessage();\n } catch (InterruptedException e) {\n }\n }\n\n private synchronized void putMessage() throws InterruptedException {\n while (messages.size() == MAXQUEUE) {\n wait();\n }\n messages.addElement(new java.util.Date().toString());\n System.out.println(\"put message\");\n notifyAll();\n }\n\n public static void main(String args[]) { \n Vector<String> messages = new Vector<String>();\n new Thread(new Producer(messages)).start();\n new Thread(new Consumer(messages)).start();\n }\n}\n\nclass Consumer implements Runnable{\n public Consumer(Vector<String> messages) {\n super();\n this.messages = messages;\n }\n private Vector<String> messages;\n\n public synchronized String getMessage() throws InterruptedException {\n notifyAll();\n while (messages.size() == 0) {\n wait();//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.\n }\n String message = (String) messages.firstElement();\n messages.removeElement(message);\n return message;\n }\n\n @Override\n public void run() {\n try {\n while (true) {\n String message = getMessage();\n System.out.println(\"Got message: \" + message);\n }\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n}\n\n\nWhenever I am running the program, it is printing put message 5 times. I don't understand even after notifyAll(), it is not giving lock to consumer."
] | [
"java",
"multithreading",
"producer-consumer"
] |
[
"HtmlAgilityPack Strip Nested Divs & Spans From Html But Keep Content",
"I have users trying to paste things like this into a text area\n\n <p><span style=\"font-size:16px\">\n<span dir=\"RTL\">در وقايع تاريخي صدر اسلام لفظ <span style=\"color:#008000\">\n<span style=\"font-size:22px\">شيعه </span>\n</span>تنها به معناي لغوي آن یعنی <span style=\"color:#FF0000\">مناصره</span> و\n<span style=\"color:#FF0000\"> پیروی</span> و متابعه آمده است، بلكه ميبينيم كه در عهدنامه حکمیّت و واگذاري حكومت بين دو خليفه علي و معاويه </span>\n<span dir=\"RTL\">ب</span> \n<span dir=\"RTL\">كلمه شيعه بر پيروان علي اطلاق شده؛ همآنگونه که</span></span>بر پيروان معاويه نيز اطلاق شده و به پيروان علي اختصاص نيافته است.</p>\n\n\nAs you can see it has many nested spans. I get the same with divs from some people too. How would I go about stripping ALL the span and div tags out BUT keeping the content InnerText? So I'm left with a chunk of text wrapped in the P tag?\n\nAny help greatly appreciated."
] | [
"c#",
"replace",
"html-agility-pack"
] |
[
"Angular animate make element slide up from bottom instead of slide down from top",
"I recently tried Angular's animation on a slide in-out animation. I am having problem in getting my component to slide in from the bottom when opening. and then slide back down when closing.\n\nI have an example of having the current sliding animation. Which slides down from the top and back up. How can I achieve to slide up from button, and slide back down to the button when closing?\nhttps://stackblitz.com/edit/slide-in-out-qn"
] | [
"angular",
"angular-animations"
] |
[
"java else if. not sure where im going wrong",
"I keep getting else without if. Any ideas why? Thanks all. By the way i'm a student so please bear with me.\n\npublic class QuizGrading\n{\n public static void main (String [] args)\n {\n int grade = 100; \n Scanner in = new Scanner (System.in);\n grade.input.in.nextlnt();\n { \n System.out.print(\"Please enter grade\");\n }\n if (grade >= 90)\n {\n System.out.println(\"You have been graded A\");\n }\n else if (grade <= 80 && >= 89) \n {\n System.out.println(\"You have been graded B\");\n }\n } \n}"
] | [
"java"
] |
[
"Filtering elements while reading .plist array into NSArray",
"First post - hope I'm doing it right!\n\nI have a file, lexicon.plist, containing an array of about 250K words. I want to load all words of length 'n' into an NSArray.\n\nI know about the NSArray instance method:\n\n\n(id)initWithContentsOfFile:(NSString *)aPath\n\n\nbut I don't see any way to intervene in the process of reading the file into the NSArray. The only solution I can see is to first load the entire lexicon into one NSArray, and then run through it in a loop selecting the elements of length 'n'.\n\nI'm very new at Cocoa, but I have come across some methods that perform some sort of iterative task, that accept a \"block\" of code that is invoked at each iteration. I was wondering if such a functional variant of initWithContentsOfFile might exist, or how else I might iteratively read an array from a .plist file and filter the elements I'm interested in.\n\n[And if you're wondering if this might be a case of premature optimization - it is ;-) But I'd still like to know.]"
] | [
"cocoa",
"filter",
"nsarray",
"plist"
] |
[
"How do I remove a string from a variable using JS in Selenium IDE?",
"Currently I have a variable: \"Your temporary password is: av9GhRN59O\".\nI need the variable to become \"av9GhRN59O\". How do I go about doing this inside Selenium IDE?"
] | [
"javascript",
"selenium",
"selenium-ide"
] |
[
"Storing SSIS Execution Results in to a table",
"I'm in SQL Server 2008 and created a few SSIS packages. I would like to know if we have any standard approach to dump all execution results into a table to track the status of packages instead of taking output into a screenshot.\n\nI have implemented Package Logging in my SSIS package and executed it. , I selected SSIS log provider for SQL Server and selected an OLEDB connection for configuration, selected events to be logged. But, I'm not sure where to look for after executing package. Can anyone please advise where I can see the results stored? I thought it might be creating a table automatically, which seems not to be the case!! \n\nTo be more clear, I started off with this MSDN Link Enable Package Logging in SQL Server Data Tools"
] | [
"sql-server",
"sql-server-2008",
"ssis"
] |
[
"R multiple integrals",
"I have a four integrals like this:\n\n\n\nTo calculate this function, my R code is as follows:\n\ntol <- 1e-05\nt.cutoff = 1e-15\n\nintegrand <- function(kappa, sigma, eta, tau) sqrt((tau-eta)/(sigma-kappa))*exp(-(sigma-kappa))\n\nintegrate1 <- function(sigma, eta, tau) integrate(integrand, tol * sigma, (1 - tol) * sigma, sigma = sigma, eta = eta, tau = tau)$value\nintegrate1.vec <- function(sigma, eta, tau) mapply(integrate1, sigma, eta, tau)\n\nintegrate2 <- function(eta, tau) integrate(integrate1.vec, tol * eta, (1 - tol) * eta, eta = eta, tau = tau)$value\nintegrate2.vec <- function(eta, tau) mapply(integrate2, eta, tau)\n\nintegrate3 <- function(tau) integrate(integrate2.vec, tol * tau, (1 - tol) * tau, tau = tau)$value\nintegrate3.vec <- function(tau) mapply(integrate3, tau)\n\n\nc_t <- function(t) ifelse(t > t.cutoff, integrate(integrate3.vec, tol * t, (1 - tol) * t)$value, 0)\n\nc_t(1)\n\n\nI think my above code is low efficient; I wonder if there is any improvement or available package for this kind of integrals. Thanks in advance!"
] | [
"r"
] |
[
"Why doesn't enabledelayedexpansion work with pipelined commands?",
"I'm trying to use a Windows batch file to run a command, pipe its output to another command, and capture the exit status of the first command. But apparently, I can't do that, although I'll grant that Windows batch files are so arcane that I may have missed a technique. How can I both capture the exit status of a command and pipe its output?\n\nIt's the classic do_a_thing | tee logfile.txt usage, but I want to be able to check whether do_a_thing succeeded or not. After lots of fooling around, googling, and reading StackOverflow, I came up with the following:\n\nsetlocal enabledelayedexpansion\nset rc=-1\n( false & set rc=!errorlevel! & echo rc=!rc! ) | tee logfile.txt\necho %rc%\n\n\nWhich I had hoped would produce: \n\nC:\\>test.bat \nC:\\>setlocal enabledelayedexpansion \nC:\\>set rc=-1 \nC:\\>(false & set rc=!errorlevel! & echo rc=!rc! ) | tee logfile.txt\nrc=1 \nC:\\>echo 1\n1\n\n\nBut, alas, it did not:\n\nC:\\>test.bat\nC:\\>setlocal enabledelayedexpansion\nC:\\>set rc=-1\nC:\\>(false & set rc=!errorlevel! & echo rc=!rc! ) | tee logfile.txt\nrc=!rc!\nC:\\>echo -1\n-1\n\n\nRemoving the \"| tee logfile.txt\" produces the expected value of !rc!, but of course, it doesn't let me capture the log file.\n\nC:\\>test.bat\nC:\\>setlocal enabledelayedexpansion\nC:\\>set rc=-1\nC:\\>(false & set rc=!errorlevel! & echo rc=!rc! )\nrc=1\nC:\\>echo 1\n1"
] | [
"windows",
"batch-file"
] |
[
"Avoid Equatable and Hashable boilerplate, Swift 4.2",
"On project we are using classes for model's layer and because of that I have to write code like this:\n\n// MARK: - Hashable\nextension Player: Hashable {\n static func == (lhs: Player, rhs: Player) -> Bool {\n return lhs.hashValue == rhs.hashValue\n }\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(self.name)\n }\n}\n\n\nCan this boilerplate can be somehow avoided? Is it possible to implement that Equatable compare by .hashValue by default? Thanks."
] | [
"swift",
"swift4.2",
"equatable"
] |
[
"Rails 4 Bootstrap 3.3, media queries causing error",
"I am a newb, but I'm trying something that I think should be easy, but I'm getting a rails server error. I want my text to break into columns for larger devices.\n\nI have in my html: \n\n<div class=\"col\">\n <p>\n Ricter Web Printing...\n </p> \n</div>\n\n\nmy css.scss has:\n\n.col {\n@media (min-width: @screen-hs-min) {\n /* rules for mobile horizontal (480 > 768) */\n -webkit-column-count: 1; /* Chrome, Safari, Opera */\n -moz-column-count: 1; /* Firefox */\n column-count: 1;\n}\n@media (min-width: @screen-sm-min) {\n /* rules for tablet (768 > 992) */\n -webkit-column-count: 2; /* Chrome, Safari, Opera */\n -moz-column-count: 2; /* Firefox */\n column-count: 2;\n}\n@media (min-width: @screen-md-min) {\n /* rules for desktop (992 > 1200) */\n -webkit-column-count: 2; /* Chrome, Safari, Opera */\n -moz-column-count: 2; /* Firefox */\n column-count: 2;\n}\n@media (min-width: @screen-lg-min) {\n /* rules for large (> 1200) */\n -webkit-column-count: 3; /* Chrome, Safari, Opera */\n -moz-column-count: 3; /* Firefox */\n column-count: 3;\n}\n\n\nThe columns work fine with no media query. The media query is copied and pasted right from the bootstrap site. Other bootstrap is working perfectly including a responsive nav...\n\nAny help greatly appreciated."
] | [
"twitter-bootstrap",
"ruby-on-rails-4",
"media-queries",
"multiple-columns"
] |
[
"Django and ModelForm. How to change IntegerField to dropdown box",
"I have a model that looks like this\n\nclass RSVP (models.Model):\n def __unicode__(self):\n return self.firstName + \" \" + self.lastName\n firstName = models.CharField(max_length=30)\n lastName = models.CharField(max_length=30)\n rsvpID = models.CharField(max_length=9, unique = True)\n allowedAdults = models.IntegerField(default = 2)\n allowedChildren = models.IntegerField(default = 0)\n adultsAttending = models.IntegerField(default = 0)\n childrenAttending = models.IntegerField(default = 0)\n\n\nand I have a ModelForm that looks like this\n\nclass RsvpForm(ModelForm):\n class Meta:\n model = RSVP\n exclude= ('firstName', 'lastName', 'allowedAdults', 'allowedChildren')\n\n\nWhat I would like to happen is that instead of a text field for the adultsAttending, a dropdown box with the values 0 to allowedAdults shows up. This is for a wedding rsvp site and I'd like to set the max number of +1's an invitee can bring on an individual basis\n\nAny thoughts on how to go about this?"
] | [
"django",
"django-forms"
] |
[
"How to generate keyboard Event ENTER on a TextField in flutter_driver Tests",
"I am writing an integration test using flutter_driver for searching using text field I have to enter(Keyboard Event) after entering text, I cannot find any solution to generate keyboard event in flutter_Driver, is there any solution to this?\ntest('search tests, search a user by name', () async {\n print('Waiting for join now button');\n print('search test started');\n await driver.clearTimeline();\n print('pause for 5 sec');\n await Future.delayed(Duration(seconds: 5));\n print('Tapping search field');\n await driver.waitFor(searchbar.searchFieldFinder);\n await driver.tap(searchbar.searchFieldFinder);\n print('enter user searching');\n await driver.enterText('Test user');\n\n //**Enter Keyboard Event here** \n\n }, timeout: Timeout(Duration(minutes: 2)));"
] | [
"flutter",
"dart",
"automation",
"automated-tests",
"flutterdriver"
] |
[
"What is the new Bootstrap 4 control-label class?",
"Visual Studio 2013, asp.net web app .Net 4.5\n\nThe Bootstrap 4 migration doc says:\n\n\n Renamed .control-label to .form-control-label.\n\n\nBut I can't find any such class in any bs 4 css file.\nSo what is the replacement?"
] | [
"bootstrap-4"
] |
[
"Comparing types including base types in C#",
"If I catch exception, it catches type and its base types too:\n\ntry\n{\n throw new EndpointNotFoundException(...);\n}\ncatch (CommunicationException e)\n{\n // EndpointNotFoundException is caught (inherits from CommunicationException)\n}\n\n\nBut how can I compare types in the same manner?\n\nvar e = new EndpointNotFoundException(...);\nif (e.GetType() == typeof(CommunicationException)) // is not true\n{\n\n}\n\n\nI know I can watch Type.BaseType, but is not there easiest way how to match types including its base type tree?"
] | [
"c#",
"types",
"comparison"
] |
[
"Json-ld defining type for node",
"I have a simple json file like:\n\n{\n \"name\": \"something\"\n}\n\n\nNow I Have a json-ld definition where there are objects. There is object with id #something - it exists lets say on http://example.com/test.jsonld#something.\n\nNow I want to add context without modyfying original data so Name becomes a type and value becomes IRI to http://example.com/test.jsonld#something.\n\nI've done something like this:\n\n{\n \"@context\":{\n \"name\":\"@type\"\n },\n \"@id\":\"1234\",\n \"name\":\"something\"\n}\n\n\nThis gives me in jsonld playground almost what I want:\n\n{\n \"@id\": \"1234\",\n \"@type\": \"http://json-ld.org/playground/something\",\n}\n\n\nHow do I add context so value \"something is expanded to IRI http://example.com/test.jsonld#something instead of playgorund ?\n\nTried with \"@base\" but it also changes the @id to url."
] | [
"json-ld"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.