diff --git "a/eval_stackex_ai_fil.json" "b/eval_stackex_ai_fil.json" new file mode 100644--- /dev/null +++ "b/eval_stackex_ai_fil.json" @@ -0,0 +1 @@ +[{"id": "242", "prompt": "**Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. \n\n**Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here.\n\n```\n# load packages\nlibrary(Rtsne)\n\n# Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations\nx.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400)\n\n# Generate Test Data: random standard normal vector with N=1 observation for J=400 variables\nx.test <- rnorm(n=400, mean=0, sd=1)\n\n# perform t-SNE\nset.seed(1)\nfit.tsne <- Rtsne(X=x.train, dims=2)\n\n```\n\nwhere the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. \n\n**Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like,\n\n```\n# The function I am looking for (but doesn't exist yet):\npred <- predict(object=fit.tsne, newdata=x.test)\n\n```\n\n(How) Is this possible? Can you help me out with this?", "response_j": "From the author himself ():\n\n> \n> Once I have a t-SNE map, how can I embed incoming test points in that\n> map?\n> \n> \n> t-SNE learns a non-parametric mapping, which means that it does not\n> learn an explicit function that maps data from the input space to the\n> map. Therefore, it is not possible to embed test points in an existing\n> map (although you could re-run t-SNE on the full dataset). A potential\n> approach to deal with this would be to train a multivariate regressor\n> to predict the map location from the input data. Alternatively, you\n> could also make such a regressor minimize the t-SNE loss directly,\n> which is what I did in this paper ().\n> \n> \n> \n\nSo you can't directly apply new data points. However, you can fit a multivariate regression model between your data and the embedded dimensions. The author recognizes that it's a limitation of the method and suggests this way to get around it."}, {"id": "754", "prompt": "Is $S$ linearly dependent on $\\textsf V = \\mathcal{F}(\\Bbb R,\\Bbb R)$ and $S = \\{t, e^t ,\\sin(t)\\}$.\nHow to prove that a set of functions are linearly dependent?", "response_j": "Suppose we have some scalars $a\\_0,a\\_1,a\\_2$ in $\\Bbb R$ such that\n$$a\\_0t+a\\_1e^t+a\\_2\\sin t =0 \\tag{1}$$\nfor all real number $t$. Making $t=0$ this gives us $a\\_1=0$. Returning to $(1)$, we have\n$$a\\_0t+a\\_2\\sin t =0 \\tag{2}$$\nNow, make $t=\\pi$ and then $a\\_0\\pi=0$, which means $a\\_0=0$."}, {"id": "761", "prompt": "I'm trying to implement simple ScopedExit class. Here's the code:\n\n```\n#include \n#include \n\ntemplate\nclass ScopedExit\n{\npublic:\n ScopedExit(std::function exitFunction)\n {\n exitFunc_ = exitFunction; \n }\n\n ~ScopedExit()\n {\n exitFunc_();\n }\nprivate:\n std::function exitFunc_;\n};\n\ntemplate<>\nclass ScopedExit\n{\npublic:\n ScopedExit(std::function exitFunction)\n {\n exitFunc_ = exitFunction; \n }\n\n ~ScopedExit()\n {\n exitFunc_();\n }\nprivate:\n std::function exitFunc_;\n};\n\nvoid foo()\n{\n std::cout << \"foo() called\\n\";\n}\n\nclass Bar\n{\npublic:\n void BarExitFunc(int x, int y)\n {\n std::cout << \"BarExitFunc called with x =\" << x << \"y = \" << y << \"\\n\";\n }\n};\n\nint main()\n{\n Bar b;\n std::cout << \"Register scoped exit func\\n\";\n {\n ScopedExit exitGuardInner(std::bind(&Bar::BarExitFunc, &b, 18, 11));\n }\n ScopedExit exitGuardOutter(foo);\n std::cout << \"About to exit from the scope\\n\";\n return 0;\n}\n\n```\n\nSo, there are a couple of questions:\n\n1. How to pass exit's function arguments to it? For example, I bind BarExitFunc with two integer arguments: 18 and 11. So how can I pass it to the exitFunc\\_ in the destructor? I think I need something like invoke function with std::forward<>.\n2. gcc 4.7.2 (from ideone.com) complains about exitGuardOutter. It says:\n\n> \n> prog.cpp:60:16: error: missing template arguments before \u2018exitGuardOutter\u2019\n> \n> \n> prog.cpp:60:16: error: expected \u2018;\u2019 before \u2018exitGuardOutter\u2019\n> \n> \n> \n\nThanks in advance.", "response_j": "> \n> How to pass exit's function arguments to it? For example, I bind BarExitFunc with two integer arguments: 18 and 11. So how can I pass it to the exitFunc\\_ in the destructor?\n> \n> \n> \n\nI can see no reason whatsoever to pass arguments to `exitFunc_` at call time in the destructor. Whatever you do, you'll have to provide those arguments upfront in the `ScopedExit` constructor anyway.\n\nThe most straightforward way is simply to use a `function` and `bind` any required arguments at the definition site like you're already doing:\n\n```\nScopedExit guard(std::bind(someFunction, someArg, otherArg));\n\n```\n\nThis allows you to get rid of the variadic template arguments altogether and simplifies your template *a lot*.\n\n---\n\nNow, if what is bothering you is that you have to type `std::bind` and you would rather use such a syntax:\n\n```\nScopedExit guard(someFunction, someArg, otherArg);\n\n```\n\nReally, I don't see the point since it makes the template more complicated, but why not... Just bind/forward the arguments in the constructor itself and still store a `function`:\n\n```\ntemplate\nScopedExit(std::function exitFunction, Args&&... args)\n{\n exitFunc_ = std::bind(exitFunction, std::forward(args)...); \n}\n\n```\n\nNow you systematically `bind` the function even if there are no arguments to bind, so you may want to specialize your class to avoid this useless `bind` when there are no arguments. This is left as an exercise.\n\n---\n\n> \n> gcc 4.7.2 (from ideone.com) complains about exitGuardOutter\n> \n> \n> \n\nThis is because `foo` isn't a `std::function` and the compiler can't deduce the correct template arguments. As already mentioned by @ForEveR you could just define your guard variable as `ScopedExit guard(foo);`.\n\nOr, **wrapping it all up** and keeping in mind what I first said (`bind` is best left out of your template and used at the definition site of your guard) you could just get rid of `std::function` in the constructor and generalize for any functor (which, BTW, is how the Standard library does whenever it needs a functor/callback). For storage you can just use `std::function` since it accepts non-void return types too:\n\n```\nclass ScopedExit\n{\npublic:\n template\n ScopedExit(Functor exitFunction)\n {\n exitFunc_ = exitFunction; \n }\n\n ~ScopedExit()\n {\n exitFunc_();\n }\nprivate:\n std::function exitFunc_;\n};\n\nint foo() { return 0; }\n\nstruct Bar {\n void bye(int, int) {}\n};\n\nstruct Baz {\n void operator ()() {}\n};\n\nint main() {\n const std::string what = \"lambda!\";\n ScopedExit guard1([&]() { std::cout << \"yay a \" << what << std::endl; });\n\n ScopedExit guard2(foo); // note how std::function accepts non-void return types\n\n Bar b;\n ScopedExit guard3(std::bind(&Bar::bye, &b, 1, 2));\n\n ScopedExit guard4(Baz());\n}\n\n```\n\nNote how your original variadic template class has now become a flexible non-template class with just a templated constructor whose template argument is deduced automatically, and which accepts almost[see note below] any kind of functor you can think about.\n\n---\n\n**Note:** I said *almost* any functor because this doesn't work with default arguments:\n\n```\nvoid foobar(int = 0) {}\nScopedExit guard5(foobar); // error: too few arguments to function\n\n```\n\nEven if you stored a `Functor` directly instead of a `std::function` you wouldn't be able to make use of the default arguments anyway (the signature of `foobar` is still `void(int)` even with a default argument) so one always has to handle this corner-case at the definition site with something like:\n\n```\nvoid foobar(int = 0) {}\nScopedExit guard5([]() { foobar(); });\n\n```"}, {"id": "1282", "prompt": "Bellow is a PHP script.\n\nI tried to implement the Observer pattern (without MVC structure)... only basic.\n\nThe error which is encountered has been specified in a comment.\nFirst I tried to add User objects to the UsersLibrary repository. There was a error such as User::update() does not exists or something.\n\nWhy is that error encountered? What fix should be applied and how?\n\n```\n interface IObserver {\n public function update(IObservable $sender);\n }\n interface IObservable {\n public function addObserver(IObserver $obj);\n public function notify();\n }\n class UsersLibrary implements IObservable {\n private $container;\n private $contor;\n //private $z;\n public function __construct() {//IObserver $a) {\n $this->container = array();\n $this->contor = 0;\n echo \"
[constructing UsersLibrary...]
\";\n $this->addObserver(new Logger());\n //$this->z = $a;\n }\n public function add($obj) {\n echo \"
[adding a new user...]
\";\n $this->container[$this->contor] = $obj;\n $this->contor++;\n $this->notify();\n }\n public function get($index) {\n return $this->container[$index];\n }\n public function addObserver(IObserver $obj) {\n $this->container[] = $obj;\n }\n public function notify() {\n echo \"
[notification in progress...]
\";\n foreach($this->container as $temp) {\n //echo $temp;\n #################################################################\n $temp->update(); //--------ERROR\n //Fatal Error: Call to a member function update() on a non-object.\n #################################################################\n }\n //$this->container[0]->update();\n //$this->z->update($this);\n }\n}\nclass User {\n private $id;\n private $name;\n public function __construct($id, $name) {\n $this->id = $id;\n $this->name = $name;\n }\n public function getId() {\n return $this->id;\n }\n public function getName() {\n return $this->name;\n }\n}\nclass Logger implements IObserver {\n public function __construct() {\n echo \"
[constructing Logger...]
\";\n }\n public function update(IObservable $sender) {\n echo \"
A new user has been added.
\";\n }\n}\n$a = new UsersLibrary(); //new Logger());\n//$a->add(new User(1, \"DemoUser1\"));\n//$a->add(new User(2, \"DemoUser2\"));\n$a->add(\"Demo\");\necho $a->get(0);\n//echo $a->get(0)->getName();\n\n```", "response_j": "Your `User` class is not implementing `interface IObserver` and therefore is not forced to have the method `update()`.\n\nYou have to instantiate a `new User()` in order to add it to the `UsersLibrary`:\n\n```\n$library = new UsersLibrary();\n$user = new User(1, \"Demo\");\n$library->add($user);\n\n```\n\nAlso, you are mixing **Users** and **Loggers** into your UsersLibrary container. Maybe think about separating the containers for them?"}, {"id": "1347", "prompt": "Brand new to Python and could use some help importing multiple Excel files to separate Pandas dataframes. I have successfully implemented the following code, but of course it imports everything into one frame. I would like to import them into df1, df2, df3, df4, df5, etc. \n\nAnything helps, thank you!\n\n```\nimport pandas as pd\nimport glob\n\ndef get_files():\n directory_path = input('Enter directory path: ')\n filenames = glob.glob(directory_path + '/*.xlsx')\n number_of_files = len(filenames)\n df = pd.DataFrame()\n for f in filenames:\n data = pd.read_excel(f, 'Sheet1')\n df = df.append(data)\n print(df)\n print(number_of_files)\n\nget_files()\n\n```", "response_j": "The easiest way to do that is to use a list. Each element of the list is a dataframe\n\n```\ndef get_files():\n directory_path = input('Enter directory path: ')\n filenames = glob.glob(directory_path + '/*.xlsx')\n number_of_files = len(filenames)\n df_list = []\n for f in filenames:\n data = pd.read_excel(f, 'Sheet1')\n df_list.append(data)\n print(df_list)\n print(number_of_files)\n return df_list\n\nget_files()\n\n```\n\nYou can then access your dataframes with `df_list[0]`, `df_list[1]`..."}, {"id": "1668", "prompt": "I want to find (or make) a python script that reads a different python script line by line and prints the commands executed and the output right there after.\n\nSuppose you have a python script, `testfile.py` as such:\n\n```\nprint(\"Hello world\")\n\nfor i in range(3):\n print(f\"i is: {i}\")\n\n```\n\nNow, I want a different python script that parses the `testfile.py` and outputs the following:\n\n```\nprint(\"Hello world\")\n## Hello world\nfor i in range(3):\n print(f\"i is: {i}\")\n## i is: 0\n## i is: 1\n## i is: 2\n\n```\n\nAny suggestions on existing software or new code on how to achieve this is greatly appreciated!\n\n---\n\nAttempts / concept code:\n========================\n\n### Running `ipython` from python:\n\nOne of the first thoughts were to run ipython from python using `subprocess`:\n\n```\nimport subprocess\nimport re\ntry:\n proc = subprocess.Popen(args=[\"ipython\", \"-i\"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)\n # Delimiter to know when to stop reading\n OUTPUT_DELIMITER = \":::EOL:::\"\n # Variable to contain the entire interaction:\n output_string = \"\"\n # Open testfile.py\n with open(\"testfile.py\") as file_:\n for line in file_:\n # Read command\n cmd = line.rstrip()\n # Add the command to the output string\n output_string += cmd + \"\\n\"\n proc.stdin.write(f\"{cmd}\\n\")\n # Print the delimiter so we know when to end:\n proc.stdin.write('print(\"{}\")\\n'.format(OUTPUT_DELIMITER))\n proc.stdin.flush()\n # Start reading output from ipython\n while True:\n thisoutput = proc.stdout.readline()\n thisoutput = thisoutput.rstrip()\n # Now check if it's the delimiter\n if thisoutput.find(OUTPUT_DELIMITER) >= 0:\n break\n output_string += thisoutput + \"\\n\"\n\nexcept Exception as e:\n proc.stdout.close()\n proc.stdin.close()\n raise\nproc.stdout.close()\nproc.stdin.close()\nprint(\"-\" * 4 + \"START OUTPUT\" + \"-\" * 4)\nprint(output_string)\nprint(\"-\" * 4 + \"END OUTPUT\" + \"-\" * 4)\n\n```\n\nIn this approach, the problem becomes indented blocks, like the `for` loop.\nIdeally something like this would work using just plain `python` (and not `ipython`).", "response_j": "[`code.InteractiveConsole.interact`](https://docs.python.org/3/library/code.html#code.InteractiveConsole.interact) does exactly what is asked."}, {"id": "1743", "prompt": "We received a note from the security review team highlighting a CRUD/FLS vulnerability in our package and in the note it says there is a \"Instances of SELECT vulnerability found across the application\".\n\nAn example provided is shown below in a \"with sharing\" class:\n\n> \n> myAttachments = [SELECT name, id, parentid, CreatedDate,CreatedById FROM Attachment WHERE parentid=:myAccount.id];\n> \n> \n> \n\nIf the user does not have access to the object or the field, the result will be null. So the FLS must be enforced.\n\nThe documentation [here](https://developer.salesforce.com/page/Enforcing_CRUD_and_FLS) does not specify the issue. How can we resolve this issue?", "response_j": "I contacted Salesforce's Support team and they provided [this article](https://support.microsoft.com/en-us/kb/2994633) as a temporary fix. \n\nThey also mentioned: \n\n> \n> \"Our R&D team has investigated this matter and logged a New Issue for it to be repaired. Unfortunately, I cannot provide a timeline as to when this repair will be implemented due to Safe Harbor constraints.\"\n> \n> \n> \n\n[Salesforce Known Issue](https://success.salesforce.com/issues_view?id=a1p3A000000IZSEQA4)"}, {"id": "1859", "prompt": "Haskell does not have loops like many other languages. I understand the reasoning behind it and some of the different approaches used to solve problems without them. However, when a loop structure is necessary, I am not sure if the way I'm creating the loop is correct/good.\n\nFor example (trivial function):\n\n```\ndumdum = do\n putStrLn \"Enter something\"\n num <- getLine\n putStrLn $ \"You entered: \" ++ num\n dumdum\n\n```\n\nThis works fine, but is there a potential problem in the code?\n\nA different example:\n\n```\na = do \n putStrLn \"1\"\n putStrLn \"2\"\n a\n\n```\n\nIf implemented in an imperative language like Python, it would look like:\n\n```python\ndef a():\n print (\"1\")\n print (\"2\")\n a()\n\n```\n\nThis eventually causes a maximum recursion depth error. This does not seem to be the case in Haskell, but I'm not sure if it might cause potential problems.\n\nI know there are other options for creating loops such as `Control.Monad.LoopWhile` and `Control.Monad.forever` -- should I be using those instead? (I am still very new to Haskell and do not understand monads yet.)", "response_j": "For general iteration, having a recursive function call itself is definitely the way to go. If your calls are in [tail position](https://en.wikipedia.org/wiki/Tail_call), they don't use any extra stack space and behave more like `goto`1. For example, here is a function to sum the first n integers using constant stack space2:\n\n```\nsum :: Int -> Int\nsum n = sum' 0 n\n\nsum' !s 0 = s\nsum' !s n = sum' (s+n) (n-1)\n\n```\n\nIt is roughly equivalent to the following pseudocode:\n\n```\nfunction sum(N)\n\n var s, n = 0, N\n loop: \n if n == 0 then\n return s\n else\n s,n = (s+n, n-1)\n goto loop\n\n```\n\nNotice how in the Haskell version we used function parameters for the sum accumulator instead of a mutable variable. This is very common pattern for tail-recursive code.\n\nSo far, general recursion with tail-call-optimization should give you all the looping power of gotos. The only problem is that manual recursion (kind of like gotos, but a little better) is relatively unstructured and we often need to carefully read code that uses it to see what is going on. Just like how imperative languages have looping mechanisms (for, while, etc) to describe most common iteration patterns, in Haskell we can use higher order functions to do a similar job. For example, many of the list processing functions like `map` or `foldl'`3 are analogous to straightforward for-loops in pure code and when dealing with monadic code there are functions in Control.Monad or in the [monad-loops](http://hackage.haskell.org/package/monad-loops) package that you can use. In the end, its a matter of style but I would err towards using the higher order looping functions.\n\n---\n\n1 You might want to check out [\"Lambda the ultimate GOTO\"](http://library.readscheme.org/page1.html), a classical article about how tail recursion can be as efficient as traditional iteration. Additionally, since Haskell is a lazy languages, there are also some situations where recursion at non-tail positions can still run in O(1) space (search for \"Tail recursion modulo cons\")\n\n2 Those exclamation marks are there to make the accumulator parameter be eagerly evaluated, so the addition happens at the same time as the recursive call (Haskell is lazy by default). You can omit the \"!\"s if you want but then you run the risk of running into a [space leak](http://www.haskell.org/haskellwiki/Foldr_Foldl_Foldl%27).\n\n3 Always use `foldl'` instead of `foldl`, due to the previously mentioned space leak issue."}, {"id": "1893", "prompt": "I would like to have the SQL Server PowerShell extensions available to me whenever I start PowerShell by loading the snap-ins in my profile.ps1 script. I found an article [here](http://blogs.msdn.com/b/mwories/archive/2008/06/14/sql2008_5f00_powershell.aspx) with a script example that shows how to do this, and this works fine on my 32-bit Windows XP box. \n\nUnfortunately, on my 64-bit Windows 7 machine, this blows up. If I try to launch this script with the 64-bit PowerShell, I get:\n\n```\nAdd-PSSnapin : No snap-ins have been registered for Windows PowerShell version 2.\nAt C:\\Users\\xxxx\\Documents\\WindowsPowerShell\\profile.ps1:84 char:13\n+ Add-PSSnapin <<<< SqlServerCmdletSnapin100\n+ CategoryInfo : InvalidArgument: (SqlServerCmdletSnapin100:String\n[Add-PSSnapin], PSArgumentException\n+ FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand\n\n```\n\nIf I run this instead in a 32-bit PowerShell, I get:\n\n```\nGet-ItemProperty : Cannot find path 'HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds \\Microsoft.SqlServer.Management.PowerShell.sqlps' because it does not exist.\nAt C:\\Users\\xxxx\\Documents\\WindowsPowerShell\\profile.ps1:39 char:29\n+ $item = Get-ItemProperty <<<< $sqlpsreg\n+ CategoryInfo : ObjectNotFound: (HKLM:\\SOFTWARE\\...owerShell.sqlps:String) [Get-ItemProperty], ItemNotFoundException\n+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemPropertyCommand\n\n```\n\nI'd like to be able to run this in a 64-bit PowerShell if possible. To this end, I tracked down what I thought was the Powershell extension dlls and in a 64-bit Administrator elevated PowerShell I ran:\n\n```\ncd \"C:\\Program Files (x86)\\Microsoft SQL Server\\100\\Tools\\Binn\"\ninstallutil Microsoft.SqlServer.Management.PSProvider.dll\ninstallutil Microsoft.SqlServer.Management.PSSnapins.dll\n\n```\n\nNo dice. Although installutil seemed to indicate success, I still get the \"No snap-ins have been registered for Windows PowerShell version 2\" error message when I run the script.\n\nAnyone have any suggestions as to where I go from here?", "response_j": "I've used this script without issue on x64 machines. The problem with the x86 invocation is that the script looks for registry keys which on an x64 instance are only accessible from x64 PowerShell. For the x64 invocation you could try registering the snapins since that is the error message you're receiving. Run as administrator...\n\nChange this:\n\n```\ncd $sqlpsPath\nAdd-PSSnapin SqlServerCmdletSnapin100\nAdd-PSSnapin SqlServerProviderSnapin100 \n\n```\n\nto this:\n\n```\ncd $sqlpsPath\n$framework=$([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory())\nSet-Alias installutil \"$($framework)installutil.exe\"\ninstallutil Microsoft.SqlServer.Management.PSSnapins.dll\ninstallutil Microsoft.SqlServer.Management.PSProvider.dll\nAdd-PSSnapin SqlServerCmdletSnapin100\nAdd-PSSnapin SqlServerProviderSnapin100 \n\n```\n\nAn even better solution is not use add-pssnapin instead turn sqlps into a module. I have blog post here:\n\n\nUpdate for SQL Server 2012 - now ships a sqlps module you can install instead of the above blog: "}, {"id": "2237", "prompt": "I have Json Data through which I'm doing this .\n\n```\n fun getFact(context: Context) = viewModelScope.launch{\n try {\n val format = Json {\n ignoreUnknownKeys = true\n prettyPrint = true\n isLenient = true\n }\n\n val factJson = context.assets.open(\"Facts.json\").bufferedReader().use {\n it.readText()\n }\n val factList = format.decodeFromString>(factJson)\n _uiState.value = ViewState.Success(factList)\n } catch (e: Exception) {\n _uiState.value = ViewState.Error(exception = e)\n }\n}\n\n```\n\nThis is the way i m getting my job from viewModle in Ui sceeen\n\n```\n viewModel.getFact(context) \n\nwhen (val result = \nviewModel.uiState.collectAsState().value) {\n is ViewState.Error -> {\n Toast.makeText(\n context,\n \"Error ${result.exception}\",\n Toast.LENGTH_SHORT\n ).show()\n }\n\n is ViewState.Success -> {\n val factsLists = mutableStateOf(result.fact)\n val randomFact = factsLists.value[0]\n\n FactCard(quote = randomFact.toString()) {\n factsLists.value.shuffled()\n }\n\n }\n }\n\n```\n\nI have fact card where i want to show that fact .also i have there a lambda for click where i want my factList to refresh every time whenever is clicked.\n\n```\n@Composable\nfun FactCard(quote: String , onClick : ()-> Unit) {\n\n val fact = remember { mutableStateOf(quote)}\n\n Box(\n contentAlignment = Alignment.Center,\n modifier = Modifier.\n .clickable { onClick() }\n ) {\n\n Text(.. )\n }\n}\n\n```\n\nI don't know how to approach this, i think there is silly thing I'm doing.", "response_j": "Composables can only recompose when you update state data. You aren't doing that. Your click event should return the new quote that you want to display. You then set `fact.value` to the new quote. Calling `fact.value` with a new value is what triggers a recompose:\n\n```\nwhen (val result = viewModel.uiState.collectAsState().value) {\n is ViewState.Error -> {\n Toast.makeText(\n context,\n \"Error ${result.exception}\",\n Toast.LENGTH_SHORT\n ).show()\n }\n\n is ViewState.Success -> {\n val factsLists = mutableStateOf(result.fact)\n val randomFact = factsLists.value[0]\n\n FactCard(quote = randomFact.toString()) {\n return factsLists.value.shuffled()[0]\n }\n\n }\n}\n\n@Composable\nfun FactCard(quote: String , onClick : ()-> String) {\n\n var fact = remember { mutableStateOf(quote)}\n\n Box(\n contentAlignment = Alignment.Center,\n modifier = Modifier.\n .clickable { \n fact.value = onClick() \n }\n ) {\n\n Text(.. )\n }\n}\n\n```"}, {"id": "2329", "prompt": "Using Jquery How can I select an option by either its value or text in 1 statement?\n\n```\n\n\n```\n\nI can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement?\n\n```\n$('select option[text=\"Two\"]'); //This selects by text\n\n$('select option[value=\"4\"]'); //This selects by value\n\n```", "response_j": "It pretty simple to respond orientation change in react native. Every view in react native have a listener called **onLayout** which get invoked upon orientation change. We just need to implement this. It's better to store dimension in state variable and update on each orientation change so that re-rendering happens after change. Other wise we need to reload the view to respond the orientation change. \n\n[![enter image description here](https://i.stack.imgur.com/omHkY.gif)](https://i.stack.imgur.com/omHkY.gif)\n\n```\n import React, { Component } from \"react\";\n\n import { StyleSheet, Text, View, Image, Dimensions } from \"react-native\";\n\n var { height, width } = Dimensions.get(\"window\");\n\nexport default class Com extends Component {\nconstructor() {\n console.log(\"constructor\");\n super();\n this.state = {\n layout: {\n height: height,\n width: width\n }\n };\n}\n_onLayout = event => {\n console.log(\n \"------------------------------------------------\" +\n JSON.stringify(event.nativeEvent.layout)\n );\n\n this.setState({\n layout: {\n height: event.nativeEvent.layout.height,\n width: event.nativeEvent.layout.width\n }\n });\n};\n\nrender() {\n console.log(JSON.stringify(this.props));\n return (\n \n \n \n );\n}\n}\n\n```"}, {"id": "2575", "prompt": "I adapted the following code found [here](http://pythonexcels.com/automating-pivot-tables-with-python/) to create a pivot table in my existing excel sheet:\n\n```\nimport win32com.client as win32\nwin32c = win32.constants\nimport sys\nimport itertools\ntablecount = itertools.count(1)\n\ndef addpivot(wb,sourcedata,title,filters=(),columns=(),\n rows=(),sumvalue=(),sortfield=\"\"):\n\n newsheet = wb.Sheets.Add()\n newsheet.Cells(1,1).Value = title\n newsheet.Cells(1,1).Font.Size = 16\n tname = \"PivotTable%d\"%tablecount.next()\n pc = wb.PivotCaches().Add(SourceType=win32c.xlDatabase,\n SourceData=sourcedata)\n pt = pc.CreatePivotTable(TableDestination=\"%s!R4C1\"%newsheet.Name,\n TableName=tname,\n DefaultVersion=win32c.xlPivotTableVersion10)\n for fieldlist,fieldc in ((filters,win32c.xlPageField),\n (columns,win32c.xlColumnField),\n (rows,win32c.xlRowField)):\n for i,val in enumerate(fieldlist):\n wb.ActiveSheet.PivotTables(tname).PivotFields(val).Orientation = fieldc\n wb.ActiveSheet.PivotTables(tname).PivotFields(val).Position = i+1\n wb.ActiveSheet.PivotTables(tname).AddDataField(wb.ActiveSheet.PivotTables(tname).\n PivotFields(sumvalue),sumvalue,win32c.xlSum)\n\ndef runexcel():\n excel = win32.gencache.EnsureDispatch('Excel.Application')\n #excel.Visible = True\n try:\n wb = excel.Workbooks.Open('18.03.14.xls')\n except:\n print \"Failed to open spreadsheet 18.03.14.xls\"\n sys.exit(1)\n ws = wb.Sheets('defaulters')\n xldata = ws.UsedRange.Value\n newdata = []\n for row in xldata:\n if len(row) == 4 and row[-1] is not None:\n newdata.append(list(row))\n rowcnt = len(newdata)\n colcnt = len(newdata[0])\n wsnew = wb.Sheets.Add()\n wsnew.Range(wsnew.Cells(1,1),wsnew.Cells(rowcnt,colcnt)).Value = newdata\n wsnew.Columns.AutoFit()\n src = \"%s!R1C1:R%dC%d\"%(wsnew.Name,rowcnt,colcnt)\n addpivot(wb,src,\n title=\"Employees by leads\",\n filters=(\"Leads\",),\n columns=(),\n rows=(\"Name\",),\n sumvalue=\"Actual hours\",\n sortfield=())\n\n if int(float(excel.Version)) >= 12:\n wb.SaveAs('new18.03.14.xlsx',win32c.xlOpenXMLWorkbook)\n else:\n wb.SaveAs('new18.03.14.xls')\n excel.Application.Quit()\n\nif __name__ == \"__main__\":\n runexcel()\n\n```\n\nThis line of code,\n `wb.ActiveSheet.PivotTables(tname).AddDataField(wb.ActiveSheet.PivotTables(tname).PivotFields(sumvalue),sumvalue,win32c.xlSum)` \n\nreturns the following error: \n\n`pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u'PivotFields method of PivotTable class failed', u'xlmain11.chm', 0, -2146827284), None)`.\n\nWhen I remove that line, the pivot table is generated without any data fields. Is there something I'm doing wrong?", "response_j": "As this is the one of the first Google hits when searching for Excel pivot tables from Python, I post my example code. This code generates a simple pivot table in Excel through a COM server, with some basic filters, columns, rows, and some number formatting applied.\nI hope this helps someone not to waste half a day on it (like I did...)\n\n```\nimport win32com.client\nExcel = win32com.client.gencache.EnsureDispatch('Excel.Application') # Excel = win32com.client.Dispatch('Excel.Application')\n\nwin32c = win32com.client.constants\n\nwb = Excel.Workbooks.Add()\nSheet1 = wb.Worksheets(\"Sheet1\")\n\nTestData = [['Country','Name','Gender','Sign','Amount'],\n ['CH','Max' ,'M','Plus',123.4567],\n ['CH','Max' ,'M','Minus',-23.4567],\n ['CH','Max' ,'M','Plus',12.2314],\n ['CH','Max' ,'M','Minus',-2.2314],\n ['CH','Sam' ,'M','Plus',453.7685],\n ['CH','Sam' ,'M','Minus',-53.7685],\n ['CH','Sara','F','Plus',777.666],\n ['CH','Sara','F','Minus',-77.666],\n ['DE','Hans','M','Plus',345.088],\n ['DE','Hans','M','Minus',-45.088],\n ['DE','Paul','M','Plus',222.455],\n ['DE','Paul','M','Minus',-22.455]]\n\nfor i, TestDataRow in enumerate(TestData):\n for j, TestDataItem in enumerate(TestDataRow):\n Sheet1.Cells(i+2,j+4).Value = TestDataItem\n\ncl1 = Sheet1.Cells(2,4)\ncl2 = Sheet1.Cells(2+len(TestData)-1,4+len(TestData[0])-1)\nPivotSourceRange = Sheet1.Range(cl1,cl2)\n\nPivotSourceRange.Select()\n\nSheet2 = wb.Worksheets(2)\ncl3=Sheet2.Cells(4,1)\nPivotTargetRange= Sheet2.Range(cl3,cl3)\nPivotTableName = 'ReportPivotTable'\n\nPivotCache = wb.PivotCaches().Create(SourceType=win32c.xlDatabase, SourceData=PivotSourceRange, Version=win32c.xlPivotTableVersion14)\n\nPivotTable = PivotCache.CreatePivotTable(TableDestination=PivotTargetRange, TableName=PivotTableName, DefaultVersion=win32c.xlPivotTableVersion14)\n\nPivotTable.PivotFields('Name').Orientation = win32c.xlRowField\nPivotTable.PivotFields('Name').Position = 1\nPivotTable.PivotFields('Gender').Orientation = win32c.xlPageField\nPivotTable.PivotFields('Gender').Position = 1\nPivotTable.PivotFields('Gender').CurrentPage = 'M'\nPivotTable.PivotFields('Country').Orientation = win32c.xlColumnField\nPivotTable.PivotFields('Country').Position = 1\nPivotTable.PivotFields('Country').Subtotals = [False, False, False, False, False, False, False, False, False, False, False, False]\nPivotTable.PivotFields('Sign').Orientation = win32c.xlColumnField\nPivotTable.PivotFields('Sign').Position = 2\n\nDataField = PivotTable.AddDataField(PivotTable.PivotFields('Amount'))\nDataField.NumberFormat = '#\\'##0.00'\n\nExcel.Visible = 1\n\nwb.SaveAs('ranges_and_offsets.xlsx')\nExcel.Application.Quit()\n\n```"}, {"id": "3186", "prompt": "I use a `entity` form type to provide a list of `Position` entities in a form. I use it often enough (each with the same \"setup\" code to customize it) that I've decided to make a custom form type from it for better re-use.\n\nHere's the current form type:\n\n```\nclass PositionType extends AbstractType\n{\n private $om;\n\n public function __construct(ObjectManager $om, $mode)\n {\n $this->om = $om;\n }\n\n public function buildForm(FormBuilderInterface $builder, array $options)\n {\n }\n\n public function setDefaultOptions(OptionsResolverInterface $resolver)\n {\n // I need to pass \"mode\" as an option when building the form.\n $mode = ???\n $query_builder = function (EntityRepository $em) use ($mode) {\n // Limit the positions returned based on the editing mode\n return $em\n ->createQueryBuilder('Position')\n ->orderBy('Position.name')\n ->leftJoin('Position.type', 'Type')\n ->andWhere('Type.id IN (:ids)')\n ->setParameter('ids', Type::typesForMode($mode))\n ;\n };\n\n $resolver\n ->setRequired(array('mode'))\n ->setDefaults(array(\n 'label' => 'Position',\n 'class' => 'AcmeBundle:Position',\n 'property' => 'name',\n 'query_builder' => $query_builder,\n 'empty_value' => '',\n 'empty_data' => null,\n 'constraints' => array(\n new NotBlank(),\n ),\n ))\n ;\n }\n\n public function getParent()\n {\n return 'entity';\n }\n\n public function getName()\n {\n return 'position';\n }\n}\n\n```\n\nDon't worry about the specifics in the query builder, that doesn't matter. The part that does matter is I'm trying to use a form type option in the query builder.\n\nHow can I do this? The problem is I can't use `$mode` (the option I want to pass to alter the query builder) in `setDefaultOptions`.\n\nI was beginning to look for a way to set the query builder from inside `buildForm` but I'm not sure I can do that.", "response_j": "This is fairly easy to achieve. You can build an option that depends on another option.\n\n[OptionResolver Component - Default Values that Depend on another Option](http://symfony.com/doc/current/components/options_resolver.html#default-values-that-depend-on-another-option)\n\nBasically you will do:\n\n```\n$resolver\n ->setRequired(array('mode', 'em')) // \"em\" for EntityManager as well\n ->setDefaults(array(\n 'label' => 'Position',\n 'class' => 'AcmeBundle:Position',\n 'property' => 'name',\n #####################################################\n 'query_builder' => function(Options $options){\n // Obviously you will need to pass the EntityManager\n $em = $options['em'];\n\n // Limit the positions returned based on the editing mode\n return $em\n ->createQueryBuilder('Position')\n ->orderBy('Position.name')\n ->leftJoin('Position.type', 'Type')\n ->andWhere('Type.id IN (:ids)')\n ->setParameter('ids', Type::typesForMode($options['mode'])) // \n ;\n },\n ####################################\n 'empty_value' => '',\n 'empty_data' => null,\n 'constraints' => array(\n new NotBlank(),\n ),\n ))\n;\n\n```\n\nThis is just a rough representation of what `OptionsResolver` can do. Hope it helps :)"}, {"id": "3266", "prompt": "Suppose that a Tor client wants to access a certain hidden service. According to the protocol, instead of submitting a request directly to the server IP (which is hidden[1][2]), this client submit a request via a series of relays. \n\nHowever, at some point, there will be a final relay in charge of delivering the client's message specifically to the server running the hidden service. In order to do so, this final relay must know the IP of this hidden server, otherwise the current internet infrastructure cannot deliver the message.\n\nIf the aforementioned steps are indeed correct, this means that in order to host a website using TOR Hidden Service you must reveal the IP address to a final relay. Therefore, Tor network does not hide the IP address of hidden services.\n\nHow to reconcile that? Am I missing something?\n\n---\n\n[1]: \"TOR Hidden Service allows you to host a website, without revealing where the website is, and hence protects the identity of the publisher/webmaster.\", [WikiBooks](https://en.wikibooks.org/wiki/How_to_Protect_your_Internet_Anonymity_and_Privacy/TOR_Hidden_Service_for_Anonymous_Websites)\n\n[2]: \"The Tor network hides the IP address of hidden services, instead using onion addresses and public keys to keep the real location hidden.\", [Privay.net](https://privacy.net/make-site-visible-dark-web-tor-hidden-services/)", "response_j": "Tor uses TCP tunnels, so - regardless of the previous answer - no need to use it. The hidden service is reached from the Tor node that is hosting it, usually through a localhost. The scenario you've described about IP revealing - yes, it *can* be a privacy problem. The design doc states clear - the system is anonymizing mostly the client, not the server - it's only rudimentary in a *standard* setup. To conceal your server IP use bridges-only for your hosting server(s) - that will elevate the privacy, but if you want both client and server to be equally anonymized - use I2P, not Tor - it's designed for exactly that purpose"}, {"id": "3284", "prompt": "Here is my problem:\n\nI have a task running a Docker image on Amazon ECS but I would like to make a new Docker image from the running instance of the container.\n\nI see the id of the instance on Amazon ECS; I have made an AMI but I would like to make a new docker image that I can pull from Amazon.\n\nAny ideas?\n\nRegards and thanks.", "response_j": "To create a image from container execute the command below:\n\n> \n> `docker commit container_id imagename`\n> \n> \n>"}, {"id": "3444", "prompt": "Can Anyone Please Convert the following Arduino Code to Embedded c code? I am very thankful to the one who converts this to an embedded c code. (this code is for Arduino lcd interfacing with Ultrasonic sensor)\n\n```\n #include \n int inches = 0;\n int cm = 0;\n\n // initialize the library with the numbers of the interface pins\n LiquidCrystal lcd(12, 11, 5, 4, 3, 2);\n\n void setup() {\n // set up the LCD's number of columns and rows:\n lcd.begin(16, 2);\n // Print a message to the LCD.\n pinMode(7, INPUT);\n }\n\n void loop() {\n lcd.clear();\n cm = 0.01723 * readUltrasonicDistance(7);\n inches = (cm / 2.54);\n if (cm<40){\n lcd.setCursor(0, 0);\n // print the number of seconds since reset:\n lcd.print(\"Caution: \");\n lcd.setCursor(0,1);\n lcd.print(\"Objects Nearby\");\n delay(1000);\n }\n }\n\n long readUltrasonicDistance(int pin)\n {\n pinMode(pin, OUTPUT); // Clear the trigger\n digitalWrite(pin, LOW);\n delayMicroseconds(2);\n // Sets the pin on HIGH state for 10 micro seconds\n digitalWrite(pin, HIGH);\n delayMicroseconds(10);\n digitalWrite(pin, LOW);\n pinMode(pin, INPUT);\n // Reads the pin, and returns the sound wave travel time in microseconds\n return pulseIn(pin, HIGH);\n }\n\n```", "response_j": "Accepted answer is not an accessible solution.\n----------------------------------------------\n\nI have made some corrections and some observations here. Do not use the accepted answer in production if you stumble across this question in the future. It is an awful experience with a keyboard.\n\nThe answer below fixes some of the CSS issues to make it more accessible. \n\nHowever **I would recommend you reconsider the no JavaScript requirement.** \n\nI can understand having a good fall-back (which the example I give below with the fixes is) but there is no way you can make a fully accessible set of CSS only tabs. \n\nFirstly you should use WAI-ARIA to complement your HTML to make things even more clear for screen readers. See the [tabs examples on W3C](http://%20https://www.w3.org/TR/wai-aria-practices/examples/tabs/tabs-1/tabs.html) to see what WAI-ARIA roles you should be using. This is NOT possible without JavaScript as states need to change (`aria-hidden` for example should change).\n\nSecondly, you should be able to use certain shortcut keys. Press the `home` key for example in order to return to the first tab, something you can only do with a little JS help.\n\nWith that being said here are a few things I fixed with the accepted answer to at least give you a good starting point as your 'no JavaScript **fallback**'.\n\n### Problem 1 - `tabindex` on the label.\n\nBy adding this you are creating a focusable element that cannot be activated via keyboard (you cannot press `space` or `Enter` on the label to change selection, unless you use JavaScript).\n\nIn order to fix this I simply removed the `tabindex` from the labels.\n\n### Problem 2 - no focus indicators when navigating via keyboard.\n\nIn the example the tabs only work when you are focused on the radio buttons (which are hidden). However at this point there is no focus indicator as the styling is applying styling to the checkbox when it is focused and not to its label. \n\nIn order to fix this I adjusted the CSS with the following\n\n```\n/*make it so when the checkbox is focused we add a focus indicator to the label.*/\n.tabs__input:focus + label {\n outline: 2px solid #333;\n}\n\n```\n\nProblem 3 - using the same state for `:hover` and `:focus` states.\n------------------------------------------------------------------\n\nThis is another bad practice that needs to go away, always have a different way of showing hover and focus states. Some screen reader and screen magnifier users will use their mouse to check they have the correct item focused and orientate themselves on a page. Without a separate hover state it is difficult to check you are hovered over a focused item.\n\n```\n/*use a different colour background on hover, you should not use the same styling for hover and focus states*/\n.tabs__label:hover{\n background-color: #ccc;\n}\n\n```\n\nExample\n-------\n\nIn the example I have added a hyperlink at the top so you can see where your focus indicator is when using a keyboard.\n\nWhen your focus indicator is on one of the two tabs you can press the arrow keys to change tab (which is expected behaviour) and the focus indicator will adjust accordingly to make it clear which tab was selected.\n\n```css\n.tabs {\r\n background-color: #eee;\r\n min-height: 400px;\r\n}\r\n\n.tabs__list {\r\n border-bottom: 1px solid black;\r\n display: flex;\r\n flex-direction: row;\r\n list-style: none;\r\n margin: 0;\r\n padding: 0;\r\n position: relative;\r\n}\r\n\n.tabs__tab {\r\n padding: 0.5rem;\r\n}\r\n\n.tabs__content {\r\n display: none;\r\n left: 0;\r\n padding: 0.5rem;\r\n position: absolute;\r\n top: 100%;\r\n}\r\n\n.tabs__input {\r\n position: fixed;\r\n top:-100px;\r\n}\r\n\n.tabs__input+label {\r\n cursor: pointer;\r\n}\r\n\n.tabs__label:hover{\r\n background-color: #ccc;\r\n}\r\n\n.tabs__input:focus + label {\r\n outline: 2px solid #333;\r\n}\r\n\n.tabs__input:checked+label {\r\n color: red;\r\n}\r\n\n.tabs__input:checked~.tabs__content {\r\n display: block;\r\n}\n```\n\n```html\nA link so you can see where your focus indicator is\r\n
\r\n
    \r\n
  • \r\n \r\n \r\n
    \r\n Tab 0 content\r\n
    \r\n
  • \r\n
  • \r\n \r\n \r\n
    \r\n Tab 1 content\r\n
    \r\n
  • \r\n
\r\n
\n```"}, {"id": "3578", "prompt": "Can anybody help in knowing whether IFC entity type names are case sensitive or case insensitive.\n\nFor example: Can we replace `IFCPERSON` with `IfcPerson` (camel case) or `ifcperson` (small) in an \\*.ifc file?", "response_j": "How about applying the following convention in every single context:\n\nSimply assume that they are case sensitive and work accordingly.\n\nIf you always do that, you will never have a problem.\n\nIf you see different casing examples, and all of them work, you can assume it is not case sensitive.\n\nOtherwise, you will always be on the safe side if you simply follow the case conventions that you see and are proven.\n\nFurthermore, you should always implement unit tests for every piece of functionality.\n\nIf you have questions about case sensitivity, implement unit tests to prove your assumptions right."}, {"id": "3850", "prompt": "I'm trying to use a plotly example in Python 3, but getting a syntax error in this line:\n\n```\nreturn map(lambda (x, y, an): (x, y), cornersWithAngles)\n\n```\n\nI already read that using parentheses to unpack the arguments in a lambda is not allowed in Python 3, but I don't know how exactly to adjust my code to solve that problem.\n\nHere is the complete code (error is on line 16):\n\n```\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nfrom plotly.tools import FigureFactory as FF\n\nimport scipy\n\ndef PolygonSort(corners):\n n = len(corners)\n cx = float(sum(x for x, y in corners)) / n\n cy = float(sum(y for x, y in corners)) / n\n cornersWithAngles = []\n for x, y in corners:\n an = (np.arctan2(y - cy, x - cx) + 2.0 * np.pi) % (2.0 * np.pi)\n cornersWithAngles.append((x, y, an))\n cornersWithAngles.sort(key = lambda tup: tup[2])\n return map(lambda (x, y, an): (x, y), cornersWithAngles)\n\ndef PolygonArea(corners):\n n = len(corners)\n area = 0.0\n for i in range(n):\n j = (i + 1) % n\n area += corners[i][0] * corners[j][1]\n area -= corners[j][0] * corners[i][1]\n area = abs(area) / 2.0\n return area\n\ncorners = [(0, 0), (3, 0), (2, 10), (3, 4), (1, 5.5)]\ncorners_sorted = PolygonSort(corners)\narea = PolygonArea(corners_sorted)\n\nx = [corner[0] for corner in corners_sorted]\ny = [corner[1] for corner in corners_sorted]\n\nannotation = go.Annotation(\n x=5.5,\n y=8.0,\n text='The area of the polygon is approximately %s' % (area),\n showarrow=False\n)\n\ntrace1 = go.Scatter(\n x=x,\n y=y,\n mode='markers',\n fill='tozeroy',\n)\n\nlayout = go.Layout(\n annotations=[annotation],\n xaxis=dict(\n range=[-1, 9]\n ),\n yaxis=dict(\n range=[-1, 12]\n )\n)\n\ntrace_data = [trace1]\nfig = go.Figure(data=trace_data, layout=layout)\n\npy.iplot(fig, filename='polygon-area')\n\n```", "response_j": "This is an oversight in the SystemVerilog LRM. There's no syntax to specify a required set of parameters for an interface in a module header. \n\nYou might check your synthesis tool to see if they provide any way of specifying parameter overrides for the top-level synthesis instance."}, {"id": "3859", "prompt": "I hosted one `DotNetNUke Application` to my production server, and locally it works perfectly. But, when browsing it redirects to the error page. \n\nHow do I set the `default.aspx` as my application default page? I am getting the error as below: \n\n```\nDotNetNuke Error\n\n--------------------------------------------------------------------------------\n\nWindows Vista\n\n Return to Site \n\n```\n\nCan anyone can help me, please? Will be appreciated.\n\n**UPDATE:**\nHi, I changed the Path in the PortalAlias table to the server url and `default.aspx` as the starting page, but it displays the `error.aspx` as default page. \n\nPlease help me resolve this problem..", "response_j": "That's very easy - build a folder tree based on GUID values parts.\n\nFor example, make 256 folders each named after the first byte and only store there files that have a GUID starting with this byte. If that's still too many files in one folder - do the same in each folder for the second byte of the GUID. Add more levels if needed. Search for a file will be very fast.\n\nBy selecting the number of bytes you use for each level you can effectively choose the tree structure for your scenario."}, {"id": "4641", "prompt": "Lets say, I have Product and Score tables. \n\n```\nProduct\n-------\nid\nname\n\nScore\n-----\nid\nProductId\nScoreValue\n\n```\n\nI want to get the top 10 Products with the highest AVERAGE scores, how do I get the average and select the top 10 products in one select statement?\n\nhere is mine which selects unexpected rows\n\n```\nSELECT TOP 10 Product.ProductName Score.Score \nFROM Product, Score \nWHERE Product.ID IN (select top 100 productid \n from score \n group by productid \n order by sum(score) desc) \norder by Score.Score desc\n\n```", "response_j": "Give this a try,\n\n```\nWITH records\nAS\n(\n SELECT a.ID, a.Name, AVG(b.ScoreValue) avg_score,\n DENSE_RANK() OVER (ORDER BY AVG(b.ScoreValue) DESC) rn\n FROM Product a\n INNER JOIN Score b\n ON a.ID = b.ProductID\n GROUP BY a.ID, a.Name\n)\nSELECT ID, Name, Avg_Score\nFROM records\nWHERE rn <= 10\nORDER BY avg_score DESC\n\n```\n\nThe reason why I am not using `TOP` is because it will not handle duplicate record having the highest average. But you can use `TOP WITH TIES` instead."}, {"id": "5027", "prompt": "I'm convinced someone else must have had this same issue before but I just can't find anything.\n\nGiven a table of data:\n\n```\nDECLARE @Table TABLE\n(\n [COL_NAME] nvarchar(30) NOT NULL,\n [COL_AGE] int NOT NULL\n);\n\nINSERT INTO @Table\nSELECT N'Column 1', 4 UNION ALL\nSELECT N'Col2', 2 UNION ALL\nSELECT N'Col 3', 56 UNION ALL\nSELECT N'Column Four', 8 UNION ALL\nSELECT N'Column Number 5', 12 UNION ALL\nSELECT N'Column Number Six', 9;\n\n```\n\nIf I use SSMS and set my output to text, running this script:\n\n```\nSELECT [COL_AGE], [COL_NAME] AS [MyCol] FROM @Table\n\n```\n\nProduces this:\n\n```\nCOL_AGE MyCol\n----------- -----------------\n4 Column 1\n2 Col2\n56 Col 3\n8 Column Four\n12 Column Number 5\n9 Column Number Six\n\n```\n\nNote that the data is neatly formatted and spaced.\n\nI want to display the contents like SQL does when you post your results to text:\n\n```\n'Column 1 '\n'Col2 '\n'Col 3 '\n'Column Four '\n'Column Number 5 '\n'Column Number Six'\n\n```\n\nThe following is just to describe what I want, I understand it's obviously a horrible piece of script and should never make its way into production:\n\n```\nSELECT \n N'''' + LEFT( \n [COL_NAME] + SPACE( ( SELECT MAX(LEN([COL_NAME])) FROM @Table ) )\n , ( SELECT MAX(LEN([COL_NAME])) FROM @Table ) \n ) + N'''' \nFROM @Table\n\n```\n\nOriginally, I tried this script, which is what I'm trying to get right:\n\n```\nSELECT \n N'''' + LEFT( \n [COL_NAME] + SPACE(MAX(LEN([COL_NAME])))\n , MAX(LEN([COL_NAME])) \n ) + N''''\nFROM @Table\n\n```\n\nBut it returns the following error:\n\n> \n> Msg 8120, Level 16, State 1, Line 28 Column '@Table.COL\\_NAME' is\n> invalid in the select list because it is not contained in either an\n> aggregate function or the GROUP BY clause.\n> \n> \n> \n\nThe script is part of a much bigger script and it all has to happen within the SELECT statement, I can't use external variables to first look up the MAX(LEN()) because the bigger script iterates through other tables.\n\nAny help would be appreciated.", "response_j": "I just used a quick CROSS APPLY to get the length of the buffer you want to use:\n\n```\nselect\n N'''' + LEFT( \n [COL_NAME] + SPACE( t2.MLEN )\n , t2.MLEN \n ) + N''''\nfrom @Table\nCROSS APPLY ( SELECT MAX(LEN([COL_NAME])) MLEN FROM @Table ) t2\n\n```"}, {"id": "5176", "prompt": "I trying to deploy an app to Heroku, but when I push my config.ru file I've got errors. \n\nFollow Heroku's log:\n\n```\n2013-01-16T21:04:14+00:00 heroku[web.1]: Starting process with command `bundle exec rackup config.ru -p 29160`\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:51:in `initialize'\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/bin/rackup:19:in `
'\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:51:in `instance_eval'\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:137:in `start'\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/config.ru:in `new'\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:304:in `wrapped_app'\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/bin/rackup:4:in `'\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:40:in `parse_file'\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:200:in `app'\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/config.ru:in `
'\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/builder.rb:40:in `eval'\n2013-01-16T21:04:16+00:00 app[web.1]: /app/config.ru:1:in `block in
': undefined method `\ufeffrequire' for # (NoMethodError)\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/lib/rack/server.rb:254:in `start'\n2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/bin/rackup:19:in `load'\n2013-01-16T21:04:17+00:00 heroku[web.1]: State changed from starting to crashed\n2013-01-16T21:04:17+00:00 heroku[web.1]: Process exited with status 1\n2013-01-16T21:04:18+00:00 heroku[router]: at=error code=H10 desc=\"App crashed\" method=GET path=/ host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=\n2013-01-16T21:04:19+00:00 heroku[router]: at=error code=H10 desc=\"App crashed\" method=GET path=/favicon.ico host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=\n2013-01-16T21:04:20+00:00 heroku[router]: at=error code=H10 desc=\"App crashed\" method=GET path=/favicon.ico host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=\n2013-01-16T21:04:37+00:00 heroku[router]: at=error code=H10 desc=\"App crashed\" method=GET path=/ host=mazzocato.herokuapp.com fwd=201.95.41.116 dyno= queue= wait= connect= service= status=503 bytes=\n2013-01-16T21:04:06+00:00 heroku[web.1]: Unidling\n\n```\n\nFollow my config.ru file:\n\n```\nrequire './app'\nrun Sinatra::Application\n\n```\n\nmy main file is `app.rb`\n\nAny help?", "response_j": "Try this:\n\n```\n(.*)<\\/A>\n\n```\n\nGroup1 and Group2 will give you the desired result."}, {"id": "5396", "prompt": "Why does block with text shift to the bottom? I know how to fix this issue (need to add \"overflow: hidden\" to the box), but I don't understand why it shift to the bottom, text inside the box is short, margins in browser-inspector are same as margins of example without text.\n\n[Example of the problem](https://codepen.io/AzatKaumov/pen/ZKQpOR/)\n\nHTML:\n\n```\n
\n
\n SIMPLE TEXT\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n\n```\n\nCSS:\n\n```\nhtml, body {\n font-size: 10px;\n margin: 0;\n height: 100%;\n}\n\n.box1 {\n display: inline-block;\n margin: 5px;\n width: 50px;\n height: 50px;\n background: blue;\n /* Fix the problem */\n /* overflow: hidden; */\n color: white;\n}\n\n.box2 {\n display: inline-block;\n margin: 5px;\n width: 50px;\n height: 50px;\n background: red;\n}\n\n.with-text:before {\n display: block;\n content: \"with-text\";\n text-transform: uppercase;\n margin: 1rem;\n}\n\n.with-text {\n box-sizing: border-box;\n height: 50%;\n border: 1px solid;\n}\n\n.without-text:before {\n display: block;\n content: \"without text\";\n text-transform: uppercase;\n margin: 1rem;\n}\n\n.without-text { \n box-sizing: border-box;\n height: 50%;\n border: 2px solid black;\n}\n\n```", "response_j": "The problem is that by default vertical alignment of **inline elements** \u2013 **baseline**, \n\nThe text inside element affects it and pushes div to the bottom. \n\nUse `vertical-align: top` to solve issue."}, {"id": "5614", "prompt": "I'm having some trouble with a problem in linear algebra:\n\nLet $A$ be a matrix with dimensions $m \\times n$ and $B$ also a matrix but with dimensions $n \\times m$ which is **not** a null matrix. (That's all that's written - I assume A may or may not be a null matrix).\n\nGiven that $AB=0$:\n\n1. Prove there is a non-trivial solution to the system of equations $Ax=0$\n2. Assume $A\\neq0$ . Does the system $Bx=0$ also have a non-trivial solution? If so, prove the argument. If not, provide a contradictory example.\n\nThere's a third part to the question but I managed to solve it and its content isn't really relevant here because it provided us a defined $A$ of real numbers, but I'm pretty lost with the first two arguments - I'm having trouble putting what I think into words. Can anyone help with this? Thanks!\n\nEDIT:\n\nOkay so I think I'm supposed to deal with the different cases of $m$ and $n$:\n\nIf $n > m$ obviously the system $Ax=0$ has infinite solutions because we'll have more variables than equations.\n\nWhat I haven't quite figured out is how to prove that:\n\nIf $AB=0$ and $m=n$ or $m > n$, then it immediately follows that $Rank(A) < n$ .\n\nAny help with this would be greatly appreciated.", "response_j": "Solved it.\n\n1. If $AB=0$ that means that matrix $A$ multiplied by any column vector $b$ in $B$ will be equal to the zero vector. Since we know that $B\\neq 0$, there must be at least one column vector $b$ in $B$ that **isn't** the zero vector. So to summarize, since $A$ multiplied by any column vector in $B$ returns 0 and we know there is a non-zero column vector in $B$, the system of equations $Ax=0$ has at least one non-trivial solution, where $x$ can be the zero vector or a non-zero vector from $B$.\n2. I have found a contradictory example. Basically to disprove the argument I need to find matrices $A,B$ that meet the following criteria:\n\n\t* $A\\_{m\\times n}, B\\_{n\\times m}$\n\t* $A,B\\neq0$\n\t* $Bx=0$ **only** has a trivial solution\n\nHere they are:\n\n$$\nA=\\begin{bmatrix}\n0&0&0&1\\\\\n0&0&0&0\\\\\n0&0&0&0\n\\end{bmatrix}\\_{3\\times 4}\\ ,\\ \nB=\n\\begin{bmatrix}\n1&0&0\\\\\n0&1&0\\\\\n0&0&1\\\\\n0&0&0\n\\end{bmatrix}\n\\\\\n$$\n$$\nA\\_{m\\times n}, B\\_{n\\times m}\\ \\ \\checkmark\n\\\\\nA,B\\neq 0\\ \\ \\checkmark\n\\\\\nAB=0\\ \\ \\checkmark\n\\\\\nBx=0\\rightarrow\\ one\\ solution\\ \\ \\checkmark \n$$\n\nAnd there's a perfect contradictory example to the argument."}, {"id": "5615", "prompt": "I have a gridview. its data source is a datatable that is loaded from the database. In this gridview, i have a template column.\n\n```\n\n \n \n
\n

\n <%# Eval(\"Name\") %>\n

\n
\n
\n
\n
\n

\n KEY<%# Eval(\"[product_type_key]\") %>

\n
\n\n Source\n
\n
\n
\n\n```\n\nIn this I want Source hyperlink only show when data available into `<%# Eval(\"SourceURL\") %>`. If I am not able to get the SourceURL value into `RowDatabound Event` . Please Guide me.\n\nI plan for this too but this is not working properly.\n\n```\n />'> Source\n\n```", "response_j": "use this instead \n\n```\n\n\n```\n\nSimilarly you could use the `` tag to control its visiblity. The if condition would go in Style attribue and not in href attribute. Something like this\n\n```\nStyle=display:Eval('some_val') == null ? none : block\n\n```"}, {"id": "5730", "prompt": "my code broke somewhere along the way, and crashes when using the navigation bar buttons.\n\nError message:\n`*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView newMemoViewController:didAddMemo:]: unrecognized selector sent to instance 0x5b55a60'`\n\nWhen debugging, the program does run the `cancel` method, and throws an exception at the `@synthesize` line. However, I cannot see anything wrong with it. \n\nThe symptoms are identical, so I am including the relevant code only for the `Cancel` button:\n\n**NewMemoViewController.h**\n\n```\n#import \n@protocol NewMemoDelegate;\n\n@class AKVoiceMemo;\n\n@interface NewMemoViewController : UIViewController {\n @private\n AKVoiceMemo *voiceMemo;\n id delegate;\n}\n\n@property (nonatomic, retain) AKVoiceMemo *voiceMemo;\n@property (nonatomic, assign) id delegate;\n\n@end\n\n@protocol NewMemoDelegate \n- (void)newMemoViewController:(NewMemoViewController *)newMemoViewController didAddMemo:(AKVoiceMemo *)voiceMemo;\n\n@end\n\n```\n\n**NewMemoViewController.m**\n\n```\n#import \"NewMemoViewController.h\"\n\n@synthesize delegate;\n\n- (void)viewDidLoad {\n UIBarButtonItem *cancelButtonItem = [[UIBarButtonItem alloc] initWithTitle:@\"Cancel\" style:UIBarButtonItemStyleBordered target:self action:@selector(cancel)];\n self.navigationItem.leftBarButtonItem = cancelButtonItem;\n [cancelButtonItem release];\n}\n\n- (void)cancel {\n [self.delegate newMemoViewController:self didAddMemo:nil];\n}\n\n```\n\nYour help would be appreciated.\n\n**Edit**: the delegate is the `RootViewController`:\n\n```\n- (void)newMemoViewController:(NewMemoViewController *)newMemoViewController didAddMemo:(AKVoiceMemo *)voiceMemo {\n if (voiceMemo){\n // Show the note in a new view controller\n // TODO: Implement this\n }\n\n [self dismissModalViewControllerAnimated:YES];\n}\n\n```", "response_j": "You're probably setting the delegate of `NewMemoViewController` to a `UIView` object instead of an object that implements the `NewMemoDelegate` protocol.\n\nThe error message is telling you that a `newMemoViewController:didAddMemo:` message was sent to a `UIView` object and the `UIView` object didn't know what to do with it. Since your `cancel` method calls `newMemoViewController:didAddMemo:` on the delegate, it is the *delegate* which is the `UIView` object that doesn't recognize the `newMemoViewController:didAddMemo:` message. In other words, your delegate is a `UIView` and it doesn't implement the `NewMemoDelegate` protocol.\n\nIf you are correctly setting the delegate, then @jtbandes makes a great point: The delegate is probably being released and a `UIView` object is taking over the same memory location, thus \"becoming\" the delegate by accident. You're doing the right thing by using the `assign` attribute for your delegate; that's fairly standard Cocoa practice. However, you do need to make sure that the delegate is retained by another object, and *that* object needs to make sure that the delegate sticks around as long as `NewMemoViewController` needs it to."}, {"id": "5828", "prompt": "To explain my problem more easily I will create the following fictional example, illustrating a very basic many-to-many relationship. A **Car** can have many **Parts**, and a **Part** can belong to many **Cars**.\n\n**DB SCHEMA:**\n\n```\nCAR_TABLE\n---------\nCarId\nModelName\n\nCAR_PARTS_TABLE\n---------------\nCarId\nPartId\n\nPARTS_TABLE\n-----------\nPartId\nPartName\n\n```\n\n**CLASSES:**\n\n```\npublic class Car \n{\n public int CarId {get;set;}\n public string Name {get;set;}\n public IEnumerable Parts {get;set;}\n}\n\npublic class Part \n{\n public int PartId {get;set;}\n public string Name {get;set}\n}\n\n```\n\nUsing this very simple model I would like to get any cars that have all the parts assigned to them from a list of parts I am searching on.\n\nSo say I have an array of PartIds:\n\n```\nvar partIds = new [] { 1, 3, 10};\n\n```\n\nI want to mimic the following c# code in terms of a database call:\n\n```\nvar allCars = /* code to retrieve all cars */\n\nvar results = new List();\n\nforeach (var car in allCars) \n{\n var containsAllParts = true;\n\n foreach (var carPart in car.Parts)\n {\n if (false == partIds.Contains(carPart.PartId))\n {\n containsAllParts = false;\n break;\n }\n }\n\n if (containsAllParts)\n {\n results.Add(car);\n }\n}\n\nreturn results;\n\n```\n\nTo be clear: I want to get the Cars that have ALL of the Parts specified from the partIds array.\n\nI have the following query, which is REALLY inefficient as it creates a subquery for each id within the partIds array and then does an IsIn query on each of their results. I am desperate to find a much more efficient manner to execute this query.\n\n```\nCar carAlias = null;\nPart partAlias = null;\n\nvar searchCriteria = session.QueryOver(() => carAlias);\n\nforeach (var partId in partIds)\n{\n var carsWithPartCriteria = QueryOver.Of(() => carAlias)\n .JoinAlias(() => carAlias.Parts, () => partAlias)\n .Where(() => partAlias.PartId == partId)\n .Select(Projections.Distinct(Projections.Id()));\n\n searchCriteria = searchCriteria\n .And(Subqueries.WhereProperty(() => carAlias.Id).In(carsWithPartCriteria));\n}\n\nvar results = searchCriteria.List();\n\n```\n\nIs there a decent way to execute this sort of query using NHibernate?", "response_j": "```\nPart partAlias=null;\nSession.QueryOver().JoinQueryOver(x=>x.Parts,()=>partAlias)\n.WhereRestrictionOn(()=>partAlias.Id).IsIn(partIds) //partIds should be implement an ICollection\n.List();\n\n```\n\nHope that helps."}, {"id": "7116", "prompt": "```\npublic Void traverseQuickestRoute(){ // Void return-type from interface\n findShortCutThroughWoods()\n .map(WoodsShortCut::getTerrainDifficulty)\n .ifPresent(this::walkThroughForestPath) // return in this case\n\n if(isBikePresent()){\n return cycleQuickestRoute()\n }\n ....\n}\n\n```\n\nIs there a way to exit the method at the `ifPresent`?\n\nIn case it is not possible, for other people with similar use-cases: I see two alternatives\n\n```\nOptional woodsShortCut = findShortCutThroughWoods();\nif(woodsShortCut.isPresent()){\n TerrainDifficulty terrainDifficulty = woodsShortCut.get().getTerrainDifficulty();\n return walkThroughForrestPath(terrainDifficulty);\n}\n\n```\n\nThis feels more ugly than it needs to be and combines if/else with functional programming.\nA chain of `orElseGet(...)` throughout the method does not look as nice, but is also a possibility.", "response_j": "`return` is a control statement. Neither lambdas (arrow notation), nor method refs (`WoodsShortcut::getTerrainDifficulty`) support the idea of control statements that move control to outside of themselves.\n\nThus, the answer is a rather trivial: Nope.\n\nYou have to think of the stream 'pipeline' as the thing you're working on. So, the question could be said differently: Can I instead change this code so that I can modify how this one pipeline operation works (everything starting at `findShortCut()` to the semicolon at the end of all the method invokes you do on the stream/optional), and then make this one pipeline operation the whole method.\n\nThus, the answer is: **`orElseGet` is probably it.**\n\nDisappointing, perhaps. 'functional' does not strike me as the right answer here. The problem is, there are things for/if/while loops can do that 'functional' cannot do. So, if you are faced with a problem that is simpler to tackle using 'a thing that for/if/while is good at but functional is bad at', then it is probably a better plan to just use for/if/while then.\n\nOne of the core things lambdas can't do are about the transparencies. Lambdas are non-transparant in regards to these 3:\n\n* Checked exception throwing. `try { list.forEach(x -> throw new IOException()); } catch (IOException e) {}` isn't legal even though your human brain can trivially tell it should be fine.\n* (Mutable) local variables. `int x = 5; list.forEach(y -> x += y);` does not work. Often there are ways around this (`list.mapToInt(Integer::intValue).sum()` in this example), but not always.\n* Control flow. `list.forEach(y -> {if (y < 0) return y;});` does not work.\n\nSo, keep in mind, you really have only 2 options:\n\n* Continually retrain yourself to not think in terms of such control flow. You find `orElseGet` 'not as nice'. I concur, but if you really want to blanket apply functional to as many places as you can possibly apply it, the whole notion of control flow out of a lambda needs not be your go-to plan, and you definitely can't keep thinking 'this code is not particularly nice because it would be simpler if I could control flow out', you're going to be depressed all day programming in this style. The day you never even think about it anymore is the day you have succeeded in retraining yourself to 'think more functional', so to speak.\n* Stop thinking that 'functional is always better'. Given that there are so many situations where their downsides are so significant, perhaps it is not a good idea to pre-suppose that the lambda/methodref based solution must somehow be superior. Apply what seems correct. That should often be \"Actually just a plain old for loop is fine. Better than fine; it's the right, most elegant1 answer here\".\n\n[1] \"This code is elegant\" is, of course, a non-falsifiable statement. It's like saying \"The Mona Lisa is a pretty painting\". You can't make a logical argument to prove this and it is insanity to try. \"This code is elegant\" boils down to saying \"*I* think it is prettier\", it cannot boil down to an objective fact. That also means in team situations there's no point in debating such things. Either everybody gets to decide what 'elegant' is (hold a poll, maybe?), or you install a dictator that decrees what elegance is. If you want to fix that and have meaningful debate, the term 'elegant' needs to be defined in terms of objective, falsifiable statements. I would posit that things like:\n\n* in face of expectable future change requests, this style is easier to modify\n* A casual glance at code leaves a first impression. Whichever style has the property that this first impression is accurate - is better (in other words, code that confuses or misleads the casual glancer is bad). Said even more differently: Code that really needs comments to avoid confusion is worse than code that is self-evident.\n* this code looks familiar to a wide array of java programmers\n* this code consists of fewer AST nodes (the more accurate from of 'fewer lines = better')\n* this code has simpler semantic hierarchy (i.e. fewer indents)\n\nThose are the kinds of things that should *define* 'elegance'. Under almost all of those definitions, 'an `if` statement' is as good or better in this specific case!"}, {"id": "7738", "prompt": "So i have `.cont` that's centered in using position absolute and is height 80% of body. \n\nInside it there are two divs. One is fixed height. And other one needs to expand to rest of parent, `.cont`.\n\nSo How do i make it expand to parent.\n\nOne other requirement is that content in both of these needs to be vertically and horizontally centered. \n\n```\nbody\n .cont\n .top\n .fillRest\n\n```\n\nHere is jsfiddle: \n\n1. make .fillRest Expand to rest of .cont.\n2. vertically and Horizontally center h1 headings in both divs.\n\nDon't Use calc()\n\ncan use display table, flow, position, and other tricks. \n\n![enter image description here](https://i.stack.imgur.com/k68V6.png)", "response_j": "Here you go. Absolutely position the white container with a top-padding that equals the height of your fixed-height top div. Then give the top div a z-index so it goes over your white box:\n\nFiddle - \n\n```\n* {margin: 0; padding: 0;}\n\nhtml, body {\n height: 100%;\n background-color: #3dd;\n color: #aaa;\n font-family: helvetica;\n}\n.cont {\n position: absolute;\n top: 0; bottom: 0;\n right: 0; left: 0;\n background-color: #1af;\n width: 400px;\n margin: auto;\n height: 80%;\n}\n.top {\n height: 100px;\n background-color: pink;\n position: relative;\n z-index: 1;\n}\n.fillRest {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n padding-top: 100px;\n height: 100%;\n background-color: #fff;\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\nh1 {\n text-align: center;\n width: 200px;\n margin: auto;\n background-color: #eee;\n}\n\n```"}, {"id": "8181", "prompt": "I'm trying to translate a simple button hover example to emca6 (I'm using babel) and keep failing. I guess that my bind is wrong somehow but I'm new to jscript and don't completely understand the: \n\n`\n\n```\nconstructor(props) {\n super(props);`\n\n```\n\nI mean I get that it's like super in python, but why the weird syntax with props passed as parameter? \n\n```\n/* non emca6 */\nimport React from 'react'\n\nvar HoverButton = React.createClass({\n getInitialState: function () {\n return {hover: false};\n },\n\n mouseOver: function () {\n this.setState({hover: true});\n },\n\n mouseOut: function () {\n this.setState({hover: false});\n },\n\n render: function() {\n var label = \"foo\";\n if (this.state.hover) {\n label = \"bar\";\n }\n return React.createElement(\n \"button\",\n {onMouseOver: this.mouseOver, onMouseOut: this.mouseOut},\n label\n );\n }\n});\n\nReact.render(React.createElement(HoverButton, null), document.body);\n\nexport default HoverButton;\n\n/* emca6 */\n\nimport React from 'react';\n\nclass HoverButton extends React.Component {\n constructor(props) {\n super(props);\n this.state = ({hover: false});\n this.mouseOver = this.mouseOver.bind(this);\n this.mouseOut = this.mouseOut.bind(this);\n }\n\n mouseOver(){\n this.setState = ({hover: true});\n }\n\n mouseOut(){\n this.setState = ({hover: false});\n }\n\n render() {\n var label = \"idle\";\n if (this.state.hover) {\n label = \"active\";\n } \n return React.createElement(\n \"button\",\n {onMouseEnter: this.mouseOver, onMouseOut: this.mouseOut},\n label,\n\n );\n }\n}\n\nexport default HoverButton;\n\n```", "response_j": "Josh,\nSorry your experience had been frustrating. I'm not at a computer at the moment but wanted to see if I could provide some help and will try to repro your scenario as soon as I can.\n\n* All types that compose your function (either in a single or multiple .csx files) are compiled into a single assembly. So the error coming from EF is indeed puzzling.\n* App.config is not supported in functions.\n\nOne approach you can try in the meantime (until we can find what is causing the issue you're running into), is to deploy your EF types and POCO as a separate assembly that you can then reference from your function. To do so, just copy that assembly into a bin folder under your function folder and add `#r \"YourAssemblyName.dll\"` to the top of your function file. Hopefully this will unblock you.\n\nI'll post an update when I'm able to repro your scenario and have more information."}, {"id": "8369", "prompt": "I have a twist on a common question I've seen in here, and I'm puzzled. \n\nWhat I need is simply a dialog box for each sub item of a list item. I have seen a dialog for a list item, but I need it down to the list item's item. Currently I've tried doing that within the adapter when inside the getView() method.\n\nFor example:\n\n```\n@Override\npublic View getView(int position, View convertView, ViewGroup parent)\n{\n View v = convertView;\n\n if (v == null)\n {\n LayoutInflater li = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n v = li.inflate(_resourceId, null);\n }\n\n string description = \"howdy Test\";\n\n TextView description = (TextView) v.findViewById(R.id.description);\n description.setText(description );\n description.setOnClickListener(new View.OnClickListener()\n {\n public void onClick(View view)\n {\n AlertDialog.Builder dia = new AlertDialog.Builder(view.getContext());\n dia.setTitle(view.getContext().getResources().getString(R.string.DESCRIPTION_TITLE));\n dia.create();\n }\n });\n}\n\n```\n\nWith that example above, it does go into the onClick() method, but nothing happens with the AlertDialog. Has anyone else tried this? is there a better way? Even better what am I doing wrong?\n\nThanks,\nKelly", "response_j": "You have to call the `show()` method on your **dia** object.[Link here to the android docs!](http://developer.android.com/reference/android/app/AlertDialog.Builder.html#show%28%29)"}, {"id": "8880", "prompt": "I am relatively new to batch scripting particularly in a windows environment. I would like to be able to gather the HDD information about a specific machine through the following command:\n\n```\nwmic idecontroller\n\n```\n\nHowever when I run that command, the output that I recieve looks like this: \n\n```\nAvailability Caption ConfigManagerErrorCode ConfigManagerUserConfig CreationClassName Description DeviceID ErrorCleared ErrorDescription InstallDate LastErrorCode Manufacturer MaxNumberControlled Name PNPDeviceID PowerManagementCapabilities PowerManagementSupported ProtocolSupported Status StatusInfo SystemCreationClassName SystemName TimeOfLastReset \n ATA Channel 0 0 FALSE Win32_IDEController IDE Channel PCIIDE\\IDECHANNEL\\4&160FD31B&0&0 (Standard IDE ATA/ATAPI controllers) ATA Channel 0 PCIIDE\\IDECHANNEL\\4&160FD31B&0&0 37 OK Win32_ComputerSystem TEST \n ATA Channel 3 0 FALSE Win32_IDEController IDE Channel PCIIDE\\IDECHANNEL\\4&160FD31B&0&3 (Standard IDE ATA/ATAPI controllers) ATA Channel 3 PCIIDE\\IDECHANNEL\\4&160FD31B&0&3 37 OK Win32_ComputerSystem TEST \n ATA Channel 4 0 FALSE Win32_IDEController IDE Channel PCIIDE\\IDECHANNEL\\4&160FD31B&0&4 (Standard IDE ATA/ATAPI controllers) ATA Channel 4 PCIIDE\\IDECHANNEL\\4&160FD31B&0&4 37 OK Win32_ComputerSystem TEST \n ATA Channel 5 0 FALSE Win32_IDEController IDE Channel PCIIDE\\IDECHANNEL\\4&160FD31B&0&5 (Standard IDE ATA/ATAPI controllers) ATA Channel 5 PCIIDE\\IDECHANNEL\\4&160FD31B&0&5 37 OK Win32_ComputerSystem TEST \n Intel(R) 6 Series/C200 Series Chipset Family 6 Port SATA AHCI Controller - 1C03 0 FALSE Win32_IDEController Intel(R) 6 Series/C200 Series Chipset Family 6 Port SATA AHCI Controller - 1C03 PCI\\VEN_8086&DEV_1C03&SUBSYS_04A31028&REV_04\\3&11583659&0&FA Intel Intel(R) 6 Series/C200 Series Chipset Family 6 Port SATA AHCI Controller - 1C03 PCI\\VEN_8086&DEV_1C03&SUBSYS_04A31028&REV_04\\3&11583659&0&FA 37 OK Win32_ComputerSystem TEST \n\n```\n\nIf I wanted to only gather information from a specific column, and store each of those strings into a variable, what would be the best method? For example, if I wanted to store all of the fields under \"Description\" to an array of strings!", "response_j": "Here you go. Batch doesn't have arrays per se, but you can duplicate an array like this:\n\n```\n@echo off\nsetlocal enabledelayedexpansion\n\nset cnt=0\nfor /f \"tokens=2 delims==\" %%a in ('wmic idecontroller get description /value^| Find \"=\"') do (\n set /a cnt+=1\n set Ide[!cnt!]=%%a\n)\n\nfor /L %%a in (1,1,%cnt%) do echo !Ide[%%a]!\n\n```"}, {"id": "9658", "prompt": "I'm want to add **OR** condition in the JSON query of Cube.js. But once I added one more condition in the filter it always adds **AND** condition in SQL query.\n\nBelow is the JSON query that I'm trying.\n\n```\n{\n \"dimensions\": [\n \"Employee.name\",\n \"Employee.company\"\n ],\n \"timeDimensions\": [],\n \"measures\": [],\n \"filters\": [\n {\n \"dimension\": \"Employee.company\",\n \"operator\": \"contains\",\n \"values\": [\n \"soft\"\n ]\n },\n {\n \"dimension\": \"Employee.name\",\n \"operator\": \"contains\",\n \"values\": [\n \"soft\"\n ]\n }\n ]\n}\n\n```\n\nIt generates below SQL query.\n\n```sql\nSELECT\n `employee`.name `employee__name`,\n `employee`.company `employee__company`\nFROM\n DEMO.Employee AS `employee`\nWHERE\n `employee`.company LIKE CONCAT('%', 'soft', '%') \n AND \n `employee`.name LIKE CONCAT('%', 'soft', '%')\nGROUP BY\n 1,\n 2;\n\n```\n\nWhat is the JSON query for Cube.js if I want to generate below SQL\n\n```sql\nSELECT\n `employee`.name `employee__name`,\n `employee`.company `employee__company`\nFROM\n DEMO.Employee AS `employee`\nWHERE\n `employee`.company LIKE CONCAT('%', 'soft', '%') \n OR\n `employee`.name LIKE CONCAT('%', 'soft', '%')\nGROUP BY\n 1,\n 2;\n\n```", "response_j": "API support for logical operators isn't shipped yet. Meanwhile there're several workarounds:\n\n1. Define dimension that mimics **OR** behavior. In your case it's\n\n```js\ncube(`Employee`, {\n // ...\n\n dimensions: {\n companyAndName: {\n sql: `CONCAT(${company}, ' ', ${name})`,\n type: `string`\n }\n }\n});\n\n```\n\n2. Define segments. Those can be also generated: \n\n```js\ncube(`Employee`, {\n // ...\n\n segments: {\n soft: {\n sql: `${company} LIKE CONCAT('%', 'soft', '%') OR ${name} LIKE CONCAT('%', 'soft', '%')` \n }\n }\n});\n\n```"}, {"id": "9810", "prompt": "Anyone point out the issue?\nKeep getting \"The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.\"\n\n```\npublic IEnumerable FindAllAppointmentsWithReminders()\n{\n DateTime reminderDate = DateTime.Today.Date;\n IEnumerable apps = RepositorySet \n .OfType()\n .Include(\"Client\")\n .Where(c => EntityFunctions.TruncateTime(c.Client.Reminder.Date) == reminderDate.Date \n && reminderDate.Date > EntityFunctions.TruncateTime(c.StartTime.Date));\n\n return apps;\n} \n\n```", "response_j": "Remove all the `.Date` from your method but this:\n\n```\nDateTime reminderDate = DateTime.Today.Date;\n\n```\n\nEntityFramework doesn't support the `.Date` property of `Datetime`. For this reason there is the pseudo-function `EntityFunctions.TruncateTime`, and for the `reminderDate` you already remove the time in the `DateTime reminderDate = DateTime.Today.Date`.\n\n```\npublic IEnumerable FindAllAppointmentsWithReminders()\n{\n DateTime reminderDate = DateTime.Today.Date;\n IEnumerable apps = RepositorySet \n .OfType()\n .Include(\"Client\")\n .Where(c => EntityFunctions.TruncateTime(c.Client.Reminder) == reminderDate \n && reminderDate > EntityFunctions.TruncateTime(c.StartTime));\n\n return apps;\n}\n\n```"}, {"id": "10924", "prompt": "I would like to get the value for of a hiddenfield if a checkbox is checked on my gridview\n\nmy gridview:\n\n```\n\n \n \n \n \n \n \n ..............\n\n\n```\n\nand here is how I loop trhough the rows and check:\n\n```\nstring myid = string.Empty; \nfor (int i = 0; i < gv_enfant.Rows.Count; i++) \n{ \n CheckBox chbox = (CheckBox)gv_enfant.Rows[i].Cells[0].FindControl(\"CheckBoxenfant\"); \n if (chbox.Checked) \n { \n myid = ((HiddenField)gv_enfant.Rows[i].Cells[0].FindControl(\"codeenfant\")).Value; \n } \n}\n\n```\n\nI put a breakpoint on the condition, debugger never hit that line", "response_j": "Late answer, but if it still helps (or for anyone else) you should be able to do the following with SQL 2008.\n\n```\nDECLARE @point GEOMETRY = GEOMETRY::STPointFromText('POINT(0 0)', 0);\nDECLARE @line GEOMETRY = GEOMETRY::STLineFromText('POINT(10 10, 20 20)', 0);\n\nSELECT STIntersection(@point.STBuffer(@point.STDistance(@line)));\n\n```\n\nEssentially, you calculate the distance between the two geometries,use that as a buffer on the point which should result in the geometries touching, and take the intersection (point) of that."}, {"id": "11052", "prompt": "I am currently using apTreeshape to simulate phylogenetic trees using the \"Yule-Hardy\" Method. What I want to do is randomly generate between 20 and 25 different numbers for three different groupings (small, medium and large trees) and then generate about 40 trees for every random number chosen from within the grouping.\n\nI know how I would do this in Python of Matlab, but in R things seem to behave a bit differently.\n\nMy thought was that if I were to generate a vector full of random numbers (one for each size grouping) and then use that to generate a vector which would basically contain all of the repeated values of each random number.\n\nHere is what I have:\n\n```\nsm_leaves<-c(sample(3:50,25,replace=F));\ns_leafy<-numeric();\n\nfor (i in 1:length(sm_leaves)) { \n for (j in 1:10) {\n s_leafy[j+i-1]=sm_leaves[i];\n }\n}\n\n```\n\nThis is giving me output like:\n\n```\n> s_leafy\n[1] 5 38 6 22 29 20 19 46 9 18 39 50 34 11 43 7 8 32 10 42 14 37\n[23] 23 13 28 28 28 28 28 28 28 28 28 28\n\n```\n\nBut What I want is something more like:\n\n```\n> s_leafy\n[1] 5 5 5 5 5 5 5 5 5 5 38 38 38 38 38 38 38 38 38 ... 28 28 28 28 28 28 28 28 28 28\n\n```\n\nMy reason for doing this is merely so that I can append this vector to a data frame along with all of the randomly generated trees - I need 2000 of them, so doing this by hand ain't quite practical.\n\nAll I have really been able to deduce from my previous attempts to solve this problem is that generally speaking while loops should be used instead of for loops, and many people have talked about using expand.grid, but I don't think that the latter is particularly useful in this case.\n\nThanks for reading, I hope my problem isn't too trivial (although I wouldn't be surprised if it were).", "response_j": "Apologies if I don't quite understand the question, but what about:\n\n```\nsm_leaves <- sample(3:50, 25, replace=FALSE)\ns_leafy <- rep(sm_leaves, each=10)\n\n```"}, {"id": "11230", "prompt": "The following query returns \n\n```\nselect to_char( trunc(sysdate) - numtoyminterval(level - 1, 'month'), 'mon-yy') as month from dual connect by level <= 12\n\n```\n\nlast 12 months according to today's date(i.e. 2-Jan-18).\n\n[![enter image description here](https://i.stack.imgur.com/Sd9ZQ.png)](https://i.stack.imgur.com/Sd9ZQ.png)\n\nSay if today's date is 29-DEC-17 it gives oracle sql error: \n**ORA-01839: date not valid for month specified**\n(since on subtracting there would be a date in the result as **'29-FEB-17'** which is not possible). So on specific dates this error would pop-up. How do you suggest to overcome this?", "response_j": "`char` is `signed` on your platform.\n\nIf you use `unsigned char` for your types for `c2` and `c1` then the implicit promotion to `int` for each term in your expression will have the effect you are after."}, {"id": "11310", "prompt": "Background:\n\n* I have a short list of strings.\n* The number of strings is not always the same, but are nearly always of the order of a \u201chandful\u201d\n* In our database will store these strings in a 2nd normalised table\n* These strings are **never** changed once they are written to the database.\n\nWe wish to be able to match on these strings quickly in a query without the performance hit of doing lots of joins.\n\nSo I am thinking of storing a hash code of all these strings in the main table and including it in our index, so the joins are only processed by the database when the hash code matches.\n\nSo how do I get a good hashcode? I could:\n\n* Xor the hash codes of all the string together\n* Xor with multiply the result after each string (say by 31)\n* Cat all the string together then get the hashcode\n* Some other way\n\nSo what do people think?\n\n---\n\nIn the end I just concatenate the strings and compute the hashcode for the concatenation, as it is simple and worked well enough.\n\n*(If you care we are using .NET and SqlServer)*\n\n---\n\n**Bug!, Bug!**\n\n[Quoting from Guidelines and rules for GetHashCode](http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/) by Eric Lippert \n\n> \n> The documentation for\n> System.String.GetHashCode notes\n> specifically that two identical\n> strings can have different hash codes\n> in different versions of the CLR, and\n> in fact they do. Don't store string\n> hashes in databases and expect them to\n> be the same forever, because they\n> won't be.\n> \n> \n> \n\nSo String.GetHashcode() should not be used for this.", "response_j": "A SQL-based solution could be based on the checksum and checksum\\_agg functions. If I'm following it right, you have something like:\n\n```\nMyTable\n MyTableId\n HashCode\n\nMyChildTable\n MyTableId (foreign key into MyTable)\n String\n\n```\n\nwith the various strings for a given item (MyTableId) stored in MyChildTable. To calculate and store a checksum reflecting these (never-to-be-changed) strings, something like this should work:\n\n```\nUPDATE MyTable\n set HashCode = checksum_agg(checksum(string))\n from MyTable mt\n inner join MyChildTable ct\n on ct.MyTableId = mt.MyTableId\n where mt.MyTableId = @OnlyForThisOne\n\n```\n\nI believe this is order-independant, so strings \"The quick brown\" would produce the same checksum as \"brown The quick\"."}, {"id": "11363", "prompt": "So I found this effect and I'm trying to modify it to be loaded inside a DIV `myeffect`, for example:\n\n```\n\n \n \n
\n \n\n\n```\n\nI tried changing some variables but I'm not a JavaScript expert and I can't get it to work inside a DIC. The effect covers the whole screen from top to bottom.\n\nThe code is on Codepen and can be found here: \n\nHelp is welcome.", "response_j": "Hope this helps\n\n```js\nvar speeds = [];\r\nvar count = 1;\r\nvar colors = ['#bf1e2e', '#ee4037', '#dc5323', '#e1861b', '#e1921e', '#f7ac40', '#f7e930', '#d1da22', '#8bc43f', '#38b349', '#008d42', '#006738', '#29b473', '#00a69c', '#26a9e1', '#1a75bb', '#2a388f', '#262161', '#652d90', '#8e2792', '#9e1f64', '#d91c5c', '#ed297b', '#d91c5c', '#db1e5e', '#bf1e2e', '#f6931e', '#f05a28', '#f6931e', '#fbaf41']\r\nvar width = parseInt($('html').css('width'), 10);\r\n\nvar random = function(mult, add) {\r\n return Math.floor((Math.random()*mult) + add);\r\n}; \r\n\nvar drop = function(n, height, color) {\r\n $('.myeffect').append('
');\r\n};\r\n\nvar createDrops = function(space) {\r\n for (var i=speeds.length; i < space/10; i++) {\r\n speeds.push(random(3000, 2000));\r\n drop(i, random(70, 30), colors[count]);\r\n\n if (count < colors.length-1) { count++; }\r\n else { count = 0; } \r\n }\r\n};\r\n\nvar animateDrops = function(startingN) {\r\n for (var i=startingN; i\r\n
\n```"}, {"id": "11423", "prompt": "I created the aks cluster with azure service principal id and i provided the contributer role according to the subscription and resource group.\n\nFor each and every time when i executed the pipeline the sign-in is asking and after i authenticated it is getting the data.\n\nAlso the \"kubectl get\" task is taking more than 30 min and is getting \"Kubectl Server Version: Could not find kubectl server version\"\n\n*To sign in, use a web browser to open the page and enter the code CRA2XssWEXUUA to authenticate*\n\nThanks in advance\n\n[![enter image description here](https://i.stack.imgur.com/wxXk9.png)](https://i.stack.imgur.com/wxXk9.png)", "response_j": "The easiest solution may be to flatten the different split characters to a single one:\n\n```py\nwith open(\"example.dat\", \"r\") as fh:\n lines = []\n for line in fh:\n lines.append( line.strip().replace(\"[\", \",\").replace(\"]\", \",\").split(\",\") )\n\n```"}, {"id": "12222", "prompt": "I am developing a taskmanager on Android 2.1.\nI want to reset date and time on clicking the reset button to current date and time.\nHelp me with the code..\n\n```\npublic void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.main);\nfinal EditText next = (EditText) findViewById(R.id.editText1);\nfinal Button sub = (Button) findViewById(R.id.button1);\nfinal Button res = (Button) findViewById(R.id.button2);\nfinal DatePicker dp= (DatePicker) findViewById(R.id.datePicker1);\nfinal TimePicker tp = (TimePicker) findViewById(R.id.timePicker1);\n\nres.setOnClickListener(new View.OnClickListener() { \n public void onClick(final View view) { \n next.setText(\"\");\n dp.refreshDrawableState();\n } \n }); \n}}\n\n```", "response_j": "```\n//get current time\nTime now = new Time();\nnow.setToNow();\n\n//update the TimePicker\ntp.setHour(now.hour);\ntp.setMinute(now.minute);\n\n//update the DatePicker\ndp.updateDate(now.year, now.month, now.monthDay);\n\n```"}, {"id": "12227", "prompt": "Is it possible to validate a field only when it exists?\n\nI'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put `email: Yup.string().Required()`, it causes that the validation run all the time even the field is not displayed.", "response_j": "I saw another related answer here, maybe this is a valid solution too?\n\n\n\nCopying code from there:\n\n```\nconst schema = yup.object({\n phone: yup.string().when('$exist', {\n is: exist => exist,\n then: yup.string().required(),\n otherwise: yup.string()\n })\n})\n\n```"}, {"id": "12340", "prompt": "I have a mysql query.\n\nThe idea is to select the records between a date range. The dates are stored as unix timestamps. With the query below, I end up with far more records than I should (out of the date range).\n\nI have picked my brain and I cant see where the query is going wrong. The other fields look correct, its just that I am out of the desired date range.\n\n```\nSELECT\n mdl_user_info_data.data,\n mdl_user.firstname, \n mdl_user.lastname, \n mdl_grade_grades.itemid, \n mdl_grade_items.itemname,\n mdl_quiz.fcpd,\n mdl_user_info_data.id,\n mdl_grade_grades.timecreated AS DATE\n FROM mdl_grade_grades\n INNER JOIN mdl_user ON mdl_grade_grades.userid = mdl_user.id\n INNER JOIN mdl_grade_items ON mdl_grade_grades.itemid = mdl_grade_items.id\n INNER JOIN mdl_quiz ON mdl_grade_items.courseid = mdl_quiz.course\n INNER JOIN mdl_user_info_data ON mdl_user.id = mdl_user_info_data.userid\n INNER JOIN mdl_course ON mdl_grade_items.courseid = mdl_course.id\n WHERE mdl_grade_grades.timecreated BETWEEN (FROM_UNIXTIME(1371704400) AND FROM_UNIXTIME(1371790800))\n AND mdl_user_info_data.fieldid = 1\n AND mdl_grade_items.itemname IS NOT NULL\n AND mdl_course.category = 27\n OR mdl_grade_items.itemname LIKE '%asa%'\n GROUP BY mdl_user.firstname, mdl_user.lastname, mdl_grade_grades.timecreated\n\n```", "response_j": "AFAIK, the svc is useless if you are not working with IIS. Outside of IIS, the so called self hosted approach, needs you to write a something like this, where HelloWorldWcfServiceMessage is your type implementing the service contract. Additionaly, don't forget to configure an endpoint for the server and to make sure you are allowed to open a service on the configured port. The following code you can use in windows service or in a console program (better for testing and debugging). Hope that helps and I got your question right.\n\n```\n...\nthis.serviceHost = new ServiceHost(typeof(HelloWorldWcfServiceMessage));\nthis.serviceHost.Open();\n...\n\npublic class HelloWorldWcfServiceMessage : IHelloWorldWcfServiceMessage\n{\n\n}\n\n[ServiceContract(Namespace = \"http://HelloWorldServiceNamespace\", Name = \"PublicHelloWorldWCFService\")]\npublic interface IHelloWorldWcfServiceMessage\n{\n [OperationContract]\n string HelloWorldMessage(string name);\n}\n\n```"}, {"id": "12377", "prompt": "Every time I try to run the create.sql file I have, it says there is a syntax error near \"buy\\_price\". The rest of the tables work fine, though.\n\n```\ncreate table Item (itemID string PRIMARY KEY, \n name string, \n currently string, \n buy_price string, \n first_bid string, \n started string, \n ends string, \n userID string references User, \n description string, \n constraint ch_buy_price check buy_price >= first_bid,\n constraint );\n\n```\n\nAny help would be appreciated.", "response_j": "The check constraint needs to be enclosed in parentheses:\n\n```\ncreate table item \n(\n itemid string primary key,\n name string,\n currently_ string,\n buy_price string,\n first_bid string,\n started string,\n ends string,\n userid string references user,\n description string,\n constraint chk_buy_price check (buy_price >= first_bid) --<< here\n);\n\n```\n\nYou also have an additional `constraint` at the end which needs to be removed."}, {"id": "12446", "prompt": "I'm studying for my AIRAT (Instructor Written) in Canada using Nizus, but I've always had trouble answering the questions about takeoff distances at 27\u00a0\u00baC when given [a chart](https://i.imgur.com/9HnYWR3.png) with 20\u00a0\u00baC and 30\u00a0\u00baC, even since the start of PPL. I want to understand it properly so I can effectively teach my students who have troubles with it.\n\nThe question is a two-parter, first calculating a takeoff distance with the following values:\n\n| Parameter | Value |\n| --- | --- |\n| Airport Temp | 30\u00a0\u00baC |\n| Airport Elevation | 3000'\u00a0AMSL |\n| Altimeter | 30.92\u00a0inHg |\n| Wind | 10\u00a0kt tailwind |\n| Flaps | 10\u00ba |\n| Runway | Dry grass |\n\nWith a pressure altitude of 2089', the nearest values are the 2000' and 3000'. I used the 2000' line of the chart.\n\nAt 2000' at 20\u00a0\u00baC the ground roll is 1080' and the total to clear a 50' obstacle is 1895'. \n\nAt 30\u00a0\u00baC it's 1155' and 2030'.\n\nThe chart says it's configured as follows: 2300\u00a0lbs, flaps 10, full power prior to brake release on a paved level dry runway with no wind. The notes state: \n\n*Headwind subtract 10% per 9kts* \n\n*Tailwind add 10% every 2kts up to 10kts* \n\n*Dry, Grass Runway or Gravel add 15% to ground roll.*\n\nAt 30\u00a0\u00baC I calculate my takeoff distance being **3305'**.\n\n---\n\nThe second part asks by how much the takeoff distance will decrease if the temperature drops to 27\u00a0\u00baC.\n\nI'm doing something wrong here as I calculate it to be 3250', with a distance change of 55', but that isn't an available answer.\n\nHow do I get the proper numbers to use at 27\u00a0\u00baC?", "response_j": "I am getting a takeoff distance of 3,502' for a takeoff over 50 FT on a **grass strip** with a **10-kt tailwind**.\n\n> \n> 2,030' \\* 1.5 \\* 1.15 = 3,502'\n> \n> \n> \n\nTo interpolate you will need to figure out the percentage between the two temperatures.\n\n> \n> (27-20) / (30-20) = 70%\n> \n> \n> \n\nWe take the difference between the chart values for 20 and 30 degrees\n\n> \n> 3,502' - 3,267' = 235'\n> \n> \n> \n\nMultiply this value by the percentage\n\n> \n> 235 \\* .7 = 164.5'\n> \n> \n> \n\nSince we subtracted the 27 from the lower value we will add in this number ot the lower chart value\n\n> \n> 3,267 + 164.5 = 3,432\n> \n> \n> \n\nThis is a difference of 70 feet."}, {"id": "12768", "prompt": "I am studying python, and although I think I get the whole concept and notion of Python, today I stumbled upon a piece of code that I did not fully understand:\n\nSay I have a class that is supposed to define Circles but lacks a body:\n\n```\nclass Circle():\n pass\n\n```\n\nSince I have not defined any attributes, how can I do this:\n\n```\nmy_circle = Circle()\nmy_circle.radius = 12\n\n```\n\nThe weird part is that Python accepts the above statement. I don't understand why Python doesn't raise an `undefined name error`. I do understand that via *dynamic typing* I just bind variables to objects whenever I want, but shouldn't an attribute `radius` exist in the `Circle` class to allow me to do this?\n\n**EDIT**: Lots of wonderful information in your answers! **Thank you everyone for all those fantastic answers!** It's a pity I only get to mark one as an answer.", "response_j": "It creates a `radius` data member of `my_circle`.\n\nIf you had asked it for `my_circle.radius` it would have thrown an exception:\n\n```\n>>> print my_circle.radius # AttributeError\n\n```\n\nInterestingly, this does not change the class; just that one instance. So:\n\n```\n>>> my_circle = Circle()\n>>> my_circle.radius = 5\n>>> my_other_circle = Circle()\n>>> print my_other_circle.radius # AttributeError\n\n```"}, {"id": "13435", "prompt": "I am using Laravel 5.6\n\nI have 2 tables. User Table and Role Table in migration folder. Also installed Laravel Passport\n\nWhen I ran this command `php artisan migrate`, I saw the auth tables created first and then role table and user table.\n\nCan I run role and user table first because I want to put reference constraints in auth table?", "response_j": "I don't know the exact stuff Laravel Passport does, but in general the Migrator classes are ran in alphabetic order. Given the fact that they are prefixed with the generation timestamp, it should be enough just renaming the role migrator, to having a timstamp before the user migrator.\n\nWhen you do this, don't forget to regenerate the autoload files."}, {"id": "13597", "prompt": "In my database i have a column name called `IsStaff` which has a return value as a bit. So staff in a company can have a illness(1) or that staff had no illness(0). How would i write a sql query that can count all the numbers of 1's and 0's between a specific date's and represent it in a jquery table. This is what i have done:\n\n```\n public List Method(string Date1, string Date2)\n {\n DateTime d = Convert.ToDateTime(Date1);\n string date1 = d.ToLongDateString();\n\n DateTime dd = Convert.ToDateTime(Date2);\n string date2 = dd.ToLongDateString();\n\n List LBD = new List();\n SqlConnection conn = new SqlConnection etc...\n SqlCommand command = new SqlCommand(@\"SELECT * From TableName \n WHERE Cast([Time] AS DATE) > @Time \n AND CAST([Time] AS DATE) < @Time2 \n ORDER BY Time Desc\", conn);\n command.Parameters.AddWithValue(\"@Time\", date1);\n command.Parameters.AddWithValue(\"@Time2\", date2);\n\n conn.Open();\n SqlDatadata data = command.Executedata();\n while (data.Read())\n {\n Staff l = new Staff();\n l.IsStaff = data[\"IsStaff\"].ToString();\n l.Name = data[\"Name\"].ToString();\n ........\n LBD.Add(l);\n }\n conn.Close();\n return LBD;\n }\n\n```\n\n> \n> i can successfully get the data between two dates but how do i get total number of time a specific staff is been ill?\n> \n> \n> \n\n```\nfunction Table(data) {\n var table = '';\n var rowID = 0;\n for (var staff in data) {\n\n var row = '';\n row += '';\n row += '';\n row += ''\n rowID++;\n table += row;\n }\n\n table += '
NameSum of ill staffsum of none ill staff
' + data[staff].Name+ '' + data[staff].IsStaff + '' + data[staff].IsStaff + '
';\n $('#displayTable').html(table);\n\n }\n\n```\n\nThis is my dynamic generated table, first column is 'Name' which displays all the staff, second column is 'Sum of ill staff' that should display a staff who been ill for a specific date and final column is 'sum of none ill staff' that should display a staff who been not ill\n**Q1** - what would be my sql query for counting a number of staff?\n**Q2** - how do i add all 1's up and display it on my table?", "response_j": "Why don\u00b4t you compute the values in the SQL?\n\n```\n SqlCommand command = new SqlCommand(@\"SELECT StaffID, Name, sum(IsStaff), \n sum(case when IsStaff = 1 then 0 else 1 end) \n From TableName \n WHERE Cast([Time] AS DATE) > @Time \n AND CAST([Time] AS DATE) < @Time2 \n GROUP BY StaffID, Name\n ORDER BY Time Desc\", conn);\n\n```\n\nor use Linq to get the values computed from the list of Staff."}, {"id": "13730", "prompt": "I created some public method in controller which does some work.\n\n```\n def current_service\n service_name = params[:controller].gsub('api/v1/', '').gsub(%r{/.+}, '')\n end\n\n```\n\nI would like to test this method using RSpec but I dont't know how can I stub params. How should I do that?", "response_j": "If this is a controller spec, you should be able to do something like this:\n\n```\nallow(controller).to receive(:params).and_return({controller: 'a value'})\n\n```\n\nAlternatively, move the `params[:controller]` statement to a separate method and stub that in your spec."}, {"id": "13872", "prompt": "I am trying to connect to Salesforce using node js / jsforce library and use promises. Unfortunately one of the methods is executing prior to getting connection.\n\ni have method A : makeconnection which returns the connection\ni have method B : which loads data from Salesforce based on the connection reference from method A\nI have method C : which gets dependencies from Salesforce based on connection from method A\n\nI would like the following order to be executed A ==> B ==> C\n\nUnfortunately C seems to run first followed by A and B so the connection is null and it fails\n\nroughly this is the code\n\n```\nlet jsforce = require(\"jsforce\");\nconst sfdcSoup = require(\"sfdc-soup\");\nconst fs = require(\"fs\");\nlet _ = require(\"lodash\");\nlet trgarr = [];\nlet clsarr = [];\nlet entityarr = [];\n\nfunction makeConnection() {\n\n return new Promise((resolve,reject) => {\n const conn = new jsforce.Connection({\n loginUrl: \"https://test.salesforce.com\",\n instanceUrl: \"salesforce.com\",\n serverUrl: \"xxx\",\n version: \"50.0\"\n });\n\n conn.login(username, password, function (err, userInfo) {\n if (err) {\n return console.error(err);\n }\n\n // console.log(conn.accessToken);\n //console.log(conn.instanceUrl);\n\n //console.log(\"User ID: \" + userInfo.id);\n //console.log(\"Org ID: \" + userInfo.organizationId);\n console.log(\"logged in\");\n }); \n resolve(conn);\n });\n}\n\nfunction loadClasses(conn) {\n\n return new Promise((resolve,reject) => {\n const querystr =\n \"select apiVersion,name,body from apexClass where NamespacePrefix = null\";\n\n let query = conn\n .query(querystr)\n .on(\"record\", function (rec) {\n clsarr.push(rec);\n })\n .on(\"end\", function () {\n console.log(\"number of class is \" + clsarr.length);\n console.log(\"loaded all classes\");\n }); \n resolve(conn,clsarr);\n });\n}\n\nasync function getDependencies(conn) {\n\n return new Promise((resolve,reject) => {\n\n let entryPoint = {\n name: \"xxx\",\n type: \"CustomField\",\n id: yyy\n };\n\n let connection = {\n token: conn.accessToken,\n url: \"abc.com\",\n apiVersion: \"50.0\"\n };\n\n let usageApi = sfdcSoup.usageApi(connection, entryPoint);\n\n usageApi.getUsage().then((response) => {\n console.log(response.stats);\n console.log(response.csv);\n\n });\n\n });\n\n}\nasync function run() {\n makeConnection().then(conn => loadClasses(conn)).then(conn=>getDependencies(conn));\n}\n\nrun();\n\n```\n\nI keep getting an error that says **UnhandledPromiseRejectionWarning: Error: Access token and URL are required on the connection object**\n\nThe reason is connection needs to be obtained from method A and sent to Method C , which is not happening. Can you please guide where i might be wrong?\n\nAlso why is method C getting executed before A and B. **why does my promise chaining not work as promised**?\n\nI am running the code in Vscode and using Node 14", "response_j": "Here is your fix :\n\n```\n
\n \n
\n
{{gender}}
\n\n```\n\nAnd here is your data :\n\n```\ndata: {\n gender: \"M\",\n genders: [\n {\n code: \"F\",\n description: \"Female\"\n }, \n {\n code: \"M\",\n description: \"Male\"\n }\n ]\n}\n\n```\n\nThere is no need to use click event for store it's value to Model.\nNote : maybe in template selector, html can't render in DOM until you render it manually."}, {"id": "13892", "prompt": "I need to run tests in different environments : `DEV`, `STAGING`, `PRODUCTION`.\nAnd needless to say, the environment variables/secrets for the above environments would obviously be different.\n\nI quick solution would be to have an env file for each environment like `dev.env`, `staging.env` & `prod.env`\n\nBut according to the docs of popular dotEnv npm package and 12 Factor app, it is not recommended to have multiple `.env` files in your repo.\n\nPlease give me a practical solution of managing env vars for multiple environments.\n\n* \n* ", "response_j": "If I understand correctly what they're writing here:\n\n**Should I have multiple .env files?**\n\n> \n> No. We strongly recommend against having a \"main\" .env file and an \"environment\" .env file like .env.test. Your config should vary between deploys, and you should not be sharing values between environments.\n> \n> \n> \n\nThis doesn't mean that you shouldn't have multiple env files, but rather that you shouldn't have one `main.env` file with all the default configuration and additional env files (one per environment) that inherit from `main.env` and override certain values.\n\nThe reason why it's not recommended is that with such a configuration it's difficult to understand \"where a specific value is coming from?\" (from which one of the following: main-env-file, specific-env-file, env-variable, code-default and etc).\n\nThat said, if you create multiple env files without such a \"main\" this means that you'll need to duplicate many of the values all over the different env files, which is better because of explicitness, but has the downside of duplication/verbosity.\n\nConfiguration is not trivial IMO and while you have only a small project it doesn't matter much how you choose to implement, but if we're talking about something more critical like a company's product, then there are many solutions available out there, some are open-source and free, some cost money, but it's worth doing your research and figure out which one provides you the benefits that are more meaningful to your use-case.\n\nSome of the more popular tools are: [Puppet](https://puppet.com/), [Ansible](https://www.ansible.com/), and [Chef](https://www.chef.io/products/chef-infra)."}, {"id": "14150", "prompt": "```\n// RecursiveBinarySearch.cpp : Defines the entry point for the console application.\n//\n\n#include \"stdafx.h\"\n#define N 9\n\nint RecursiveBinarySearch(int A, int low, int high, int x);\n\nint main()\n{\n int A[N];\n int index = 0;\n //Put \n A[0] = 2;\n A[1] = 6;\n A[2] = 13;\n A[3] = 21;\n A[4] = 36;\n A[5] = 47;\n A[6] = 63;\n A[7] = 81;\n A[8] = 97;\n\n printf(\"Elements in Array A\\n\");\n\n while (index <= 8) {\n printf(\"%d \", A[index]);\n index++;\n }\n\n printf(\"\\nLocation(index) of element 63\\n\");\n\n printf(\"%d\", RecursiveBinarySearch(A, 0, 8, 63));\n\n return 0;\n}\n\nint RecursiveBinarySearch(int A, int low, int high, int x) {\n\n //Base Condition\n if (low > high)\n return -1;\n\n int mid = low + (high - low) / 2;\n\n if (x == A[mid])\n return mid;\n else if (x < A[mid])\n return RecursiveBinarySearch(A, low, mid - 1, x);\n else\n return RecursiveBinarySearch(A, mid + 1, high, x);\n\n}\n\n```\n\nHere's first problem.\nVisual studio says \nint A[9]\nargument of type \"int\\*\" is incompatible with parameter of type \"int\"\n\nHere's second problem.\nint mid\nexpression must have pointer-to-object type\n\nI don't know well about pointer so i want to know why this code can't be compiled and how to use pointer in this code.", "response_j": "Better remove all assignements `A[0] = ..., A[1] = ...` alltogether and write:\n\n```\nint A[] = {2,6,13,21,36,47,63,81,97}\n\n```\n\nAnd replace\n\n```\nwhile (index <= 8)\n\n```\n\nby:\n\n```\nwhile (index < sizeof(A)/sizeof(A[0]))\n\n```\n\n`sizeof(A) / sizeof(A[0])` is the number of elements if the array `A`. `sizeof(A)` is the size in bytes of the whole array, and `sizeof(A[0])` is the size of one elements of the array in bytes.\n\n---\n\nBut the real problem is here:\n\nReplace:\n\n```\nint RecursiveBinarySearch(int A, int low, int high, int x)\n\n```\n\nby\n\n```\nint RecursiveBinarySearch(int A[], int low, int high, int x)\n\n```\n\nThere may be more errors though."}, {"id": "14604", "prompt": "I know this question has been asked before. I checked through multiple answers on this site,\nfor example:\n\n[Wordpress loop with different bootstrap columns](https://stackoverflow.com/questions/54568904/wordpress-loop-with-different-bootstrap-columns)\n\n\n\n... but I cannot work out how to integrate answers with my code (assuming that is possible).\n\nI want to display a list of Categories and their related posts on a page.\n\nThe code I'm using works fine BUT displays the results in a single column down the page: \n\n[![enter image description here](https://i.stack.imgur.com/ukuUZ.jpg)](https://i.stack.imgur.com/ukuUZ.jpg)\n\nI want to split the display into 2 columns, like in the image below, if possible:\n\n[![enter image description here](https://i.stack.imgur.com/dRfHK.jpg)](https://i.stack.imgur.com/dRfHK.jpg)\n\nThe code I'm using (currently placed in a new page template) is as follows:\n\n```\n' . $category->name . '';\necho '
';\n// WP_Query arguments\n$args = array(\n 'cat' => $category->term_id,\n 'order' => 'ASC',\n 'orderby' => 'title',\n);\n\n// The Query\n$query = new WP_Query( $args );\n// The Loop\nif ( $query->have_posts() ) {\nwhile ( $query->have_posts() ) {\n$query->the_post();\n?>\n\n

\">

\n';\n// Restore original Post Data\nwp_reset_postdata();\n} // End foreach\n\nget_footer(); \n?>\n\n```\n\nWondering if anyone can help me to get this code to display loop results in 2 columns. \n\nMany thanks.\n\n**UPDATE TO QUESTION**\n\nKarl, thanks for your answer. Your script works, but with a small problem:\n\nThe Categories/Related Posts display in 2 columns but a 'gap/space' appears in the middle of the display of data (see image below):\n\n[![enter image description here](https://i.stack.imgur.com/BWjin.jpg)](https://i.stack.imgur.com/BWjin.jpg) \n\nI added to your code slightly so I could display a custom field I inserted into each post. I'm not sure if this has caused the problem.\n\nAltered code (changes are immediately after $query->the\\_post();):\n\n```\n\n\n
\n\n\";\n$counter = 0;\nforeach ( $categories as $category ) {\nif($counter % 4 == 0 && $counter !=0){\n echo \"
\";\n}\n// Display category name\necho '

' . $category->name . '

';\necho '
';\n// WP_Query arguments\n$args = array(\n'cat' => $category->term_id,\n'order' => 'ASC',\n'orderby' => 'title',\n);\n// The Query\n$query = new WP_Query( $args );\n// The Loop\nif ( $query->have_posts() ) {\nwhile ( $query->have_posts() ) {\n$query->the_post();\n\n$customfieldvalue = get_post_meta($post->ID, \"PDF\", true);\n\n?>\n

\" target=\"_blank\">

\n\n';\n// Restore original Post Data\nwp_reset_postdata();\n$counter++;\nif($counter % 4 == 0){\necho \"
\";\n}\n} // End foreach\nif($counter % 4 != 0){\necho \"
\";\n}\nget_footer(); \n?>\n\n```", "response_j": "I've used bootstrap classes (row, col-6). Checked the size of categories array and used 2 variables - one as a counter and the other one to check if the column is first or second.\n\n```\n';\n }\n echo'
';\n // Display category name\n echo '

' . $category->name . '

';\n echo '
';\n // WP_Query arguments\n $args = array(\n 'cat' => $category->term_id,\n 'order' => 'ASC',\n 'orderby' => 'title',\n );\n\n // The Query\n $query = new WP_Query( $args );\n // The Loop\n if ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n ?>\n\n

\">

\n
';\n\n if($n == 1){\n if($j == $catSize){\n echo '
\n
';\n }\n else{\n $n = 2;\n }\n }\n else{\n echo '
';\n $n =1;\n }\n $j++;\n }\n\n// Restore original Post Data\nwp_reset_postdata();\n} // End foreach\n\nget_footer(); \n?>\n\n```"}, {"id": "15027", "prompt": "At the moment, I am working on a project that requires me to add three videos to the homepage, but loading them all at once will reduce the load time considerably.\n\nAlso i want to use `