id stringlengths 3 6 | prompt stringlengths 100 55.1k | response_j stringlengths 30 18.4k |
|---|---|---|
242 | **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.
**Example**: Suppose I aim to reduce the K variables ... | From the author himself (<https://lvdmaaten.github.io/tsne/>):
>
> Once I have a t-SNE map, how can I embed incoming test points in that
> map?
>
>
> t-SNE learns a non-parametric mapping, which means that it does not
> learn an explicit function that maps data from the input space to the
> map. Therefore, it is... |
754 | Is $S$ linearly dependent on $\textsf V = \mathcal{F}(\Bbb R,\Bbb R)$ and $S = \{t, e^t ,\sin(t)\}$.
How to prove that a set of functions are linearly dependent? | Suppose we have some scalars $a\_0,a\_1,a\_2$ in $\Bbb R$ such that
$$a\_0t+a\_1e^t+a\_2\sin t =0 \tag{1}$$
for all real number $t$. Making $t=0$ this gives us $a\_1=0$. Returning to $(1)$, we have
$$a\_0t+a\_2\sin t =0 \tag{2}$$
Now, make $t=\pi$ and then $a\_0\pi=0$, which means $a\_0=0$. |
761 | I'm trying to implement simple ScopedExit class. Here's the code:
```
#include <iostream>
#include <functional>
template<class R, class... Args>
class ScopedExit
{
public:
ScopedExit(std::function<R(Args...)> exitFunction)
{
exitFunc_ = exitFunction;
}
~ScopedExit()
{
exitFunc_()... | >
> 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 can see no reason whatsoever to pass arguments to `exitFunc_` at call time in the destructor. Whatever you do, you'll have to pro... |
1282 | Bellow is a PHP script.
I tried to implement the Observer pattern (without MVC structure)... only basic.
The error which is encountered has been specified in a comment.
First I tried to add User objects to the UsersLibrary repository. There was a error such as User::update() does not exists or something.
Why is that... | Your `User` class is not implementing `interface IObserver` and therefore is not forced to have the method `update()`.
You have to instantiate a `new User()` in order to add it to the `UsersLibrary`:
```
$library = new UsersLibrary();
$user = new User(1, "Demo");
$library->add($user);
```
Also, you are mixing **Use... |
1347 | 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.
Anything helps, thank you!
```
import pandas... | The easiest way to do that is to use a list. Each element of the list is a dataframe
```
def get_files():
directory_path = input('Enter directory path: ')
filenames = glob.glob(directory_path + '/*.xlsx')
number_of_files = len(filenames)
df_list = []
for f in filenames:
data = pd.read_excel... |
1668 | 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.
Suppose you have a python script, `testfile.py` as such:
```
print("Hello world")
for i in range(3):
print(f"i is: {i}")
```
Now, I want a different pyth... | [`code.InteractiveConsole.interact`](https://docs.python.org/3/library/code.html#code.InteractiveConsole.interact) does exactly what is asked. |
1743 | 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".
An example provided is shown below in a "with sharing" class:
>
> myAttachments = [SELECT name, id, parentid, Crea... | I contacted Salesforce's Support team and they provided [this article](https://support.microsoft.com/en-us/kb/2994633) as a temporary fix.
They also mentioned:
>
> "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 rep... |
1859 | 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.
For example (trivial function):
```
dumdum ... | 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 s... |
1893 | 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 wor... | 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 admi... |
2237 | I have Json Data through which I'm doing this .
```
fun getFact(context: Context) = viewModelScope.launch{
try {
val format = Json {
ignoreUnknownKeys = true
prettyPrint = true
isLenient = true
}
val factJson = context.assets.open("Facts.json").buffered... | 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:
```
when (val result = viewModel.uiState.collectAsStat... |
2329 | Using Jquery How can I select an option by either its value or text in 1 statement?
```
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
```
I can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement?
```
$('select optio... | 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 af... |
2575 | 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:
```
import win32com.client as win32
win32c = win32.constants
import sys
import itertools
tablecount = itertools.count(1)
def addpivot(wb,sourcedata,title,filters=... | 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.
I hope this helps someone not to waste half a day on ... |
3186 | 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.
Here's the current form type:
```
class PositionType extends AbstractType
{
private $om;
... | This is fairly easy to achieve. You can build an option that depends on another option.
[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)
Basically you will do:
```
$resolver
->se... |
3266 | 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.
However, at some point, there will be a final relay in charge of delivering the client'... | 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 anonymizin... |
3284 | Here is my problem:
I 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.
I 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.
Any ideas?
Regards an... | To create a image from container execute the command below:
>
> `docker commit container_id imagename`
>
>
> |
3444 | 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)
```
#include <LiquidCrystal.h>
int inches = 0;
int cm = 0;
// initialize the library w... | Accepted answer is not an accessible solution.
----------------------------------------------
I 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.
The answer below fixes some ... |
3578 | Can anybody help in knowing whether IFC entity type names are case sensitive or case insensitive.
For example: Can we replace `IFCPERSON` with `IfcPerson` (camel case) or `ifcperson` (small) in an \*.ifc file? | How about applying the following convention in every single context:
Simply assume that they are case sensitive and work accordingly.
If you always do that, you will never have a problem.
If you see different casing examples, and all of them work, you can assume it is not case sensitive.
Otherwise, you will always ... |
3850 | I'm trying to use a plotly example in Python 3, but getting a syntax error in this line:
```
return map(lambda (x, y, an): (x, y), cornersWithAngles)
```
I 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 ... | 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.
You might check your synthesis tool to see if they provide any way of specifying parameter overrides for the top-level synthesis instance. |
3859 | I hosted one `DotNetNUke Application` to my production server, and locally it works perfectly. But, when browsing it redirects to the error page.
How do I set the `default.aspx` as my application default page? I am getting the error as below:
```
DotNetNuke Error
---------------------------------------------------... | That's very easy - build a folder tree based on GUID values parts.
For 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 level... |
4641 | Lets say, I have Product and Score tables.
```
Product
-------
id
name
Score
-----
id
ProductId
ScoreValue
```
I 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?
here is mine which selects unexpected rows
```
SELECT ... | Give this a try,
```
WITH records
AS
(
SELECT a.ID, a.Name, AVG(b.ScoreValue) avg_score,
DENSE_RANK() OVER (ORDER BY AVG(b.ScoreValue) DESC) rn
FROM Product a
INNER JOIN Score b
ON a.ID = b.ProductID
GROUP BY a.ID, a.Name
)
SELECT ID, Name, Avg_Score
FROM r... |
5027 | I'm convinced someone else must have had this same issue before but I just can't find anything.
Given a table of data:
```
DECLARE @Table TABLE
(
[COL_NAME] nvarchar(30) NOT NULL,
[COL_AGE] int NOT NULL
);
INSERT INTO @Table
SELECT N'Column 1', 4 UNION ALL
SELECT N'Col2', 2 UNION ALL
SELECT N'Col 3', 56 UNIO... | I just used a quick CROSS APPLY to get the length of the buffer you want to use:
```
select
N'''' + LEFT(
[COL_NAME] + SPACE( t2.MLEN )
, t2.MLEN
) + N''''
from @Table
CROSS APPLY ( SELECT MAX(LEN([COL_NAME])) MLEN FROM @Table ) t2
``` |
5176 | I trying to deploy an app to Heroku, but when I push my config.ru file I've got errors.
Follow Heroku's log:
```
2013-01-16T21:04:14+00:00 heroku[web.1]: Starting process with command `bundle exec rackup config.ru -p 29160`
2013-01-16T21:04:16+00:00 app[web.1]: from /app/vendor/bundle/ruby/1.9.1/gems/rack-1.4.4/li... | Try this:
```
<A.*HREF\s*=\s*(?:"|')([^"']*)(?:"|').*>(.*)<\/A>
```
Group1 and Group2 will give you the desired result. |
5396 | 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.
[Example of the problem](https://codepen.io/... | The problem is that by default vertical alignment of **inline elements** – **baseline**,
The text inside element affects it and pushes div to the bottom.
Use `vertical-align: top` to solve issue. |
5614 | I'm having some trouble with a problem in linear algebra:
Let $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).
Given that $AB=0$:
1. Prove there is a non-trivia... | Solved it.
1. 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 a... |
5615 | I have a gridview. its data source is a datatable that is loaded from the database. In this gridview, i have a template column.
```
<asp:TemplateField HeaderText="Product Type" SortExpression="ProductID">
<ItemStyle CssClass="MP-table-tb-display-item" />
... | use this instead
```
<asp:hyperlink Target="_blank" NavigateUrl='<%# Eval("SourceURL") %>' Visible = '<%# Eval("SourceURL") == null ? false : true %>' >
```
Similarly you could use the `<a>` tag to control its visiblity. The if condition would go in Style attribue and not in href attribute. Something like this
`... |
5730 | my code broke somewhere along the way, and crashes when using the navigation bar buttons.
Error message:
`*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView newMemoViewController:didAddMemo:]: unrecognized selector sent to instance 0x5b55a60'`
When debugging, the program doe... | You're probably setting the delegate of `NewMemoViewController` to a `UIView` object instead of an object that implements the `NewMemoDelegate` protocol.
The 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... |
5828 | 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**.
**DB SCHEMA:**
```
CAR_TABLE
---------
CarId
ModelName
CAR_PARTS_TABLE
---------------
CarId
PartId
PAR... | ```
Part partAlias=null;
Session.QueryOver<Car>().JoinQueryOver(x=>x.Parts,()=>partAlias)
.WhereRestrictionOn(()=>partAlias.Id).IsIn(partIds) //partIds should be implement an ICollection
.List<Car>();
```
Hope that helps. |
7116 | ```
public Void traverseQuickestRoute(){ // Void return-type from interface
findShortCutThroughWoods()
.map(WoodsShortCut::getTerrainDifficulty)
.ifPresent(this::walkThroughForestPath) // return in this case
if(isBikePresent()){
return cycleQuickestRoute()
}
....
}
```
Is ther... | `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.
Thus, the answer is a rather trivial: Nope.
You have to think of the stream 'pipeline' as the thing you're worki... |
7738 | So i have `.cont` that's centered in using position absolute and is height 80% of body.
Inside it there are two divs. One is fixed height. And other one needs to expand to rest of parent, `.cont`.
So How do i make it expand to parent.
One other requirement is that content in both of these needs to be vertically and... | 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:
Fiddle - <http://jsfiddle.net/24jocwu5/2/>
```
* {margin: 0; padding: 0;}
html, body {
height: 100%;
background-color: #... |
8181 | 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:
`
```
constructor(props) {
super(props);`
```
I mean I get that it's like super in python, but why the weird s... | Josh,
Sorry 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.
* All types that compose your function (either in a single or multiple .csx files) are compiled into a single assembly. So the error... |
8369 | I have a twist on a common question I've seen in here, and I'm puzzled.
What 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.
For examp... | 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) |
8880 | 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:
```
wmic idecontroller
```
However when I run that command, the output that I recieve looks like this:
```
Availability Captio... | Here you go. Batch doesn't have arrays per se, but you can duplicate an array like this:
```
@echo off
setlocal enabledelayedexpansion
set cnt=0
for /f "tokens=2 delims==" %%a in ('wmic idecontroller get description /value^| Find "="') do (
set /a cnt+=1
set Ide[!cnt!]=%%a
)
for /L %%a in (1,1,%cnt%) do echo !Id... |
9658 | 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.
Below is the JSON query that I'm trying.
```
{
"dimensions": [
"Employee.name",
"Employee.company"
],
"timeDimensions": [],
"measures": [],
... | API support for logical operators isn't shipped yet. Meanwhile there're several workarounds:
1. Define dimension that mimics **OR** behavior. In your case it's
```js
cube(`Employee`, {
// ...
dimensions: {
companyAndName: {
sql: `CONCAT(${company}, ' ', ${name})`,
type: `string`
}
}
});
```
2. D... |
9810 | Anyone point out the issue?
Keep getting "The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."
```
public IEnumerable<Appointment> FindAllAppointmentsWithReminders()
{
DateTime reminderDate = DateTime.Today.Date;
... | Remove all the `.Date` from your method but this:
```
DateTime reminderDate = DateTime.Today.Date;
```
EntityFramework 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 `DateTi... |
10924 | I would like to get the value for of a hiddenfield if a checkbox is checked on my gridview
my gridview:
```
<asp:GridView ID="gv_enfant" runat="server" AutoGenerateColumns="False" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataSourceID="SqlDataSource1"
... | Late answer, but if it still helps (or for anyone else) you should be able to do the following with SQL 2008.
```
DECLARE @point GEOMETRY = GEOMETRY::STPointFromText('POINT(0 0)', 0);
DECLARE @line GEOMETRY = GEOMETRY::STLineFromText('POINT(10 10, 20 20)', 0);
SELECT STIntersection(@point.STBuffer(@point.STDistance(@... |
11052 | 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... | Apologies if I don't quite understand the question, but what about:
```
sm_leaves <- sample(3:50, 25, replace=FALSE)
s_leafy <- rep(sm_leaves, each=10)
``` |
11230 | The following query returns
```
select to_char( trunc(sysdate) - numtoyminterval(level - 1, 'month'), 'mon-yy') as month from dual connect by level <= 12
```
last 12 months according to today's date(i.e. 2-Jan-18).
[](https://i.stack.imgur.com/Sd9... | `char` is `signed` on your platform.
If 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. |
11310 | Background:
* I have a short list of strings.
* The number of strings is not always the same, but are nearly always of the order of a “handful”
* In our database will store these strings in a 2nd normalised table
* These strings are **never** changed once they are written to the database.
We wish to be able to match ... | A SQL-based solution could be based on the checksum and checksum\_agg functions. If I'm following it right, you have something like:
```
MyTable
MyTableId
HashCode
MyChildTable
MyTableId (foreign key into MyTable)
String
```
with the various strings for a given item (MyTableId) stored in MyChildTable. To c... |
11363 | So I found this effect and I'm trying to modify it to be loaded inside a DIV `myeffect`, for example:
```
<html>
<head></head>
<body>
<div class="myeffect"></div>
</body>
</html>
```
I tried changing some variables but I'm not a JavaScript expert and I can't get it to work inside a DIC. The effec... | Hope this helps
```js
var speeds = [];
var count = 1;
var colors = ['#bf1e2e', '#ee4037', '#dc5323', '#e1861b', '#e1921e', '#f7ac40', '#f7e930', '#d1da22', '#8bc43f', '#38b349', '#008d42', '#006738', '#29b473', '#00a69c', '#26a9e1', '#1a75bb', '#2a388f', '#262161', '#652d90', '#8e2792', '#9e1f64', '#d91c5c', '#ed297... |
11423 | I created the aks cluster with azure service principal id and i provided the contributer role according to the subscription and resource group.
For each and every time when i executed the pipeline the sign-in is asking and after i authenticated it is getting the data.
Also the "kubectl get" task is taking more than 3... | The easiest solution may be to flatten the different split characters to a single one:
```py
with open("example.dat", "r") as fh:
lines = []
for line in fh:
lines.append( line.strip().replace("[", ",").replace("]", ",").split(",") )
``` |
12222 | I am developing a taskmanager on Android 2.1.
I want to reset date and time on clicking the reset button to current date and time.
Help me with the code..
```
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText next = (EditText) findViewBy... | ```
//get current time
Time now = new Time();
now.setToNow();
//update the TimePicker
tp.setHour(now.hour);
tp.setMinute(now.minute);
//update the DatePicker
dp.updateDate(now.year, now.month, now.monthDay);
``` |
12227 | Is it possible to validate a field only when it exists?
I'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 ... | I saw another related answer here, maybe this is a valid solution too?
<https://github.com/jquense/yup/issues/1114>
Copying code from there:
```
const schema = yup.object({
phone: yup.string().when('$exist', {
is: exist => exist,
then: yup.string().required(),
otherwise: yup.string()
... |
12340 | I have a mysql query.
The 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).
I have picked my brain and I cant see where the query is going wrong. The other fields look correct, its ju... | 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 yo... |
12377 | 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.
```
create table Item (itemID string PRIMARY KEY,
name string,
currently string,
buy_price string,
first_bid string,
started string,
ends string... | The check constraint needs to be enclosed in parentheses:
```
create table item
(
itemid string primary key,
name string,
currently_ string,
buy_price string,
first_bid string,
started string,
ends string,
userid string references user,
description ... |
12446 | 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 ºC when given [a chart](https://i.imgur.com/9HnYWR3.png) with 20 ºC and 30 ºC, even since the start of PPL. I want to understand it properly so I can effectively teach ... | I am getting a takeoff distance of 3,502' for a takeoff over 50 FT on a **grass strip** with a **10-kt tailwind**.
>
> 2,030' \* 1.5 \* 1.15 = 3,502'
>
>
>
To interpolate you will need to figure out the percentage between the two temperatures.
>
> (27-20) / (30-20) = 70%
>
>
>
We take the difference between... |
12768 | 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:
Say I have a class that is supposed to define Circles but lacks a body:
```
class Circle():
pass
```
Since I have not defined any attributes, how can I ... | It creates a `radius` data member of `my_circle`.
If you had asked it for `my_circle.radius` it would have thrown an exception:
```
>>> print my_circle.radius # AttributeError
```
Interestingly, this does not change the class; just that one instance. So:
```
>>> my_circle = Circle()
>>> my_circle.radius = 5
>>> my... |
13435 | I am using Laravel 5.6
I have 2 tables. User Table and Role Table in migration folder. Also installed Laravel Passport
When I ran this command `php artisan migrate`, I saw the auth tables created first and then role table and user table.
Can I run role and user table first because I want to put reference constraints... | 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.
When you do this, don't forget to... |
13597 | 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 ha... | Why don´t you compute the values in the SQL?
```
SqlCommand command = new SqlCommand(@"SELECT StaffID, Name, sum(IsStaff),
sum(case when IsStaff = 1 then 0 else 1 end)
From TableName
... |
13730 | I created some public method in controller which does some work.
```
def current_service
service_name = params[:controller].gsub('api/v1/', '').gsub(%r{/.+}, '')
end
```
I would like to test this method using RSpec but I dont't know how can I stub params. How should I do that? | If this is a controller spec, you should be able to do something like this:
```
allow(controller).to receive(:params).and_return({controller: 'a value'})
```
Alternatively, move the `params[:controller]` statement to a separate method and stub that in your spec. |
13872 | 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.
i have method A : makeconnection which returns the connection
i have method B : which loads data from Salesforce based on the connection reference from metho... | Here is your fix :
```
<div>
<label class="radio" v-for="singleGender in genders">
<input type="radio" v-model="gender" v-bind:value="singleGender.code">
{{singleGender.description}}
</label>
</div>
<div>{{gender}}</div>
```
And here is your data :
```
data: {
gender: "M",
genders: [
{
code: "... |
13892 | I need to run tests in different environments : `DEV`, `STAGING`, `PRODUCTION`.
And needless to say, the environment variables/secrets for the above environments would obviously be different.
I quick solution would be to have an env file for each environment like `dev.env`, `staging.env` & `prod.env`
But according to... | If I understand correctly what they're writing here:
**Should I have multiple .env files?**
>
> 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.
>
>
>
This... |
14150 | ```
// RecursiveBinarySearch.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define N 9
int RecursiveBinarySearch(int A, int low, int high, int x);
int main()
{
int A[N];
int index = 0;
//Put
A[0] = 2;
A[1] = 6;
A[2] = 13;
A[3] = 21;
A[4] = 36;
... | Better remove all assignements `A[0] = ..., A[1] = ...` alltogether and write:
```
int A[] = {2,6,13,21,36,47,63,81,97}
```
And replace
```
while (index <= 8)
```
by:
```
while (index < sizeof(A)/sizeof(A[0]))
```
`sizeof(A) / sizeof(A[0])` is the number of elements if the array `A`. `sizeof(A)` is the size in... |
14604 | I know this question has been asked before. I checked through multiple answers on this site,
for example:
[Wordpress loop with different bootstrap columns](https://stackoverflow.com/questions/54568904/wordpress-loop-with-different-bootstrap-columns)
<https://wordpress.stackexchange.com/questions/222278/how-to-separat... | 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.
```
<?php
/*
* Template Name: Alphabetical List
*/
get_header();
// Grab all the categories from the database that have posts.
$catego... |
15027 | 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.
Also i want to use `<video/>` tag instead of using `<iframe/>` because i want that autoplay functionality.
What's the best way to do this in React? Using N... | You can use [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) and do it as below. For React all you have to do is to add the below code in an `useEffect` with empty dependency.
```js
const video = document.querySelector("video");
function handleIntersection(entries) ... |
15133 | I have a service that fetches some client data from my server:
```
app.factory('clientDataService', function ($http) {
var clientDataObject = {};
var cdsService = {
fetch: function (cid) {
//$http returns a promise, which has a then function, which also returns a promise
var pro... | clientDataService.clientDataObject is not part of your controller's scope, so you can't watch for changes on that object.
You need to inject the $rootScope into your service then broadcast the changes to the controllers scopes.
```
app.factory('clientDataService', function ($rootScope, $http) {
var clientDataObjec... |
15140 | Trying to create a socketio link between flask server and reactjs client. It shows this error
"Access to XMLHttpRequest at '<http://127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=MrcruFC>' from origin '<http://localhost:3000>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on... | You can add an option for creating SocketIO.
```
socketio = SocketIO(app=app, cors_allowed_origins='*')
``` |
15348 | I am making a "Treasure hunt" trails app. A user can go to a location and when they reach that location an action will happen. To monitor the users location I am using Gelocation.watchposition() from "react-native-geolocation-service".
The point of interest (trailLocation) is got from our API and I set the "trailLocat... | The data in your function is outdated - what's often referred to as a "stale closure". When you write `Geolocation.watchPosition((data) => newPositionHandler(data), ...`, the function is created with the state that exists at the time. When the function runs, this data has become outdated.
You can read more about solut... |
15627 | I am an international student in a interdisciplinary PhD in the social sciences.
1. My supervisor has about 60 students and does not do any advising beyond a few personal favorites.
2. My second supervisor considers me a student of the first, resents the fact that he is the expert on the subject, and as a result won't... | It is not uncommon that a German professor does not give advise to their PhD students. Neither is it uncommon that the 2nd referee does not want to read your thesis. In Germany, whether your dissertation is good enough or not is mainly decided by the first advisor. If they say it's ok, then it's ok. Your advisor theirs... |
15648 | I want to write unique initials before listing an array of names, so given
const names = ["Bill", "Jack", "john"], I would like to print something like:
```
<ul>
<li>B
<ul>
<li>Bill</li>
</ul>
</li>
<li>J
<ul>
<li>John</li>
<li>jack</li>
<... | Here we go:
```
const names = ['Bill', 'Jack', 'john', 'Alex'];
const groupedNames = names.reduce((accumulator, name) => {
// first char of name, uppercased
const firstLetter = name[0].toUpperCase();
// check if data for key exist
const namesList = accumulator[firstLetter] || [];
// check if name... |
15816 | I'm trying to display a static image located in the same folder as my Html file but it seems I can't get the right path for it to display correctly. The application I'm developing is an atlassian plugin that also includes a java backend to get Data from the Database and I'm displaying it on the frontend using HTML and ... | ```
s=df.mask((df-df.apply(lambda x: x.std() )).gt(5))#mask where condition applies
s=s.assign(A=s.A.fillna(s.A.max()),B=s.B.fillna(s.B.max())).sort_index(axis = 0)#fill with max per column and resort frame
A B
0 1.0 2.0
1 1.0 6.0
2 2.0 8.0
3 1.0 8.0
4 2.0 1.0
``` |
16024 | I'm running a pretty time-consuming method in a thread, and one of the things it does, is if there is no image available it sets a grid named Background's background to a solid color. Here's how that snippet looks:
```
SolidColorBrush scb = new SolidColorBrush();
scb.Color = Color.FromRgb(21, 21, 21);
Dispatcher.Begin... | `SolidColorBrush` is a dependency object - and you're creating it in the non-UI thread, then trying to use it in the UI thread. Try this instead:
```
Action action = () =>
{
SolidColorBrush scb = new SolidColorBrush(Color.FromRgb(21, 21, 21));
Background.Background = scb;
};
Dispatcher.BeginInvoke(action);
``... |
16119 | I have a script where I keep time of when I start and finish. This code works on Linux, but not on my MacOS Sierra v 10.12.6
```
start=`date +"%a %b %d %Y %r"`
end=`date +"%a %b %d %Y %r"`
elapsed_time=`date -d @$(( $(date -d "$end" +%s) - $(date -d "$start" +%s) )) -u +'%H:%M:%S'`
```
The error I get is:
```
usag... | **Yes**, you definitely **can track moving surfaces and moving objects** in `ARCore`.
If you track static surface using `ARCore` – the resulted features are mainly suitable for so-called `Camera Tracking`. If you track moving object/surface – the resulted features are mostly suitable for `Object Tracking`.
You also... |
16180 | I'm currently building a food application which has users select a range of options (perishable, non-perishable ) and (snack, produce or meal) via a set of radio buttons. I'm currently using node.js and sqlite 3 to query a database to determine which entries to return to the user after they search the database.
I wan... | How about (insert as many `row.names` as you want rows in the output `data.frame`):
```
data = data.frame(row.names = '1')
data[paste0('a', 1:10)] = .614
data[paste0('c', 1:10)] = -6.198
data[paste0('d', 1:10)] = 35.952
```
Or (column names won't be exactly right; thanks @Frank for simplifying my approach here)
```... |
16316 | I need to query Sql Server and get an ID that identifies the machine on which SQL Server is installed. An ID that works well also in some complex scenarios like failover clusters, or similar architectures.
I need this for license check, i bind my licence key to a ID, currently i am creting "my id" using a combination ... | >
> et an ID that identifies the machine on which SQL Server is installed. An ID that works well
> also in some complex scenarios like failover clusters, or similar architectures.
>
>
>
So waht do you want? Identify the MACHINE or identify the CLUSTER and handle enterprise senarios?
In general this is not pooss... |
16640 | I'm trying to build a RecyclerView filled with a card view items. For each item I need 2 small images that I load from URL. Everything works fine only if I load sample image from Picasso website ([http://i.imgur.com/DvpvklR.png](https://i.imgur.com/DvpvklR.png)). Every other picture I try to load doesn't show up.
Her... | For loops in R all run in the same scope, which means a variable defined in the loop will be shared by all iterations. This is an issue if you create a function in each loop iteration that accesses this variable, and assume that it'll be unique for each iteration.
Here's a simple demo:
```
counter <- 0; funcs <- lis... |
16768 | I have run into a couple of problems while trying to convert an existing JDBC application to use HSQLDB version 2.2.9 (Currently the codebase runs successfully on MySQL, ORACLE and SQLServer, but an embedded database seemed like a good option too).
I will ask the questions one at a time and separately (although they a... | As I also commented before, this sounds like a bug in the HSQLDB JDBC implementation. The JDBC 4.1 spec (section 15.2.4.2) says:
>
> After the method `deleteRow` has been called, the cursor will be positioned before the next valid row. If the deleted row is the last row, the cursor will be positioned after the last r... |
16797 | I have following UDF used to convert time stored as a string into a timestamp.
```
val hmsToTimeStampUdf = udf((dt: String) => {
if (dt == null) null else {
val formatter = DateTimeFormat.forPattern("HH:mm:ss")
try {
new Timestamp(formatter.parseDateTime(dt).getMillis)
} catch {
... | Instead of throwing a `RuntimeException` that kills your .csv parsing, maybe a better approach would be to have UDF returning a tuple (well-formed, corrupted) value. Then, you can easily segregate good/bad rows by selecting `is null`/`is not null` subsets.
```
def safeConvert(dt: String) : (Timestamp,String) = {
if... |
17176 | using mobile detection (js or php), is it possible to display top navi made for mobile only?
also i see a lot of mobile detection in php - where is it supposed to be placed?
```
{php}
function isMobileBrowser($user_agent = '') {
foreach (array('iPhone','Android','Windows CE', 'PPC', 'Smartphone', 'IEMobile', 'Opera ... | Have you tried changing the query to:
```
mysql_query("UPDATE `upcoming` SET `title` = '$title', `date` = '$date', `repeat` = '$repeat', `location` = '$location', `location_link` = '$location_link', `group` = '$group', `group_link` = '$group_link', `notes` = '$notes', `enabled` = '$enabled' WHERE `id` = '$key' LIMIT 1... |
17224 | My Spring boot application packaged as ROOT.war on tomcat9 using Java 11 appears to load successfully but fails to map the controllers. I can view every page by going right to the .jsp but my controller's map the URL's without .jsp. If I go to the mapped URL I get the standard 404 page.
This app works locally but expr... | Yes, you can do that. It's nothing inherently wrong with it. However, it can make it impossible to recover from a failed allocation. If you're planning to exit the program if the allocation fails, it (usually) does not matter.
So this is perfectly fine:
```
ptr = realloc(ptr, newsize);
if(!ptr) exit(EXIT_FAILURE);
`... |
17349 | Is the following always true?
$$
\arctan(f(x))\leq f(x),\ \ \text{where}\ \ |f(x)|<1\ \ \forall x\in\mathbb{R}
$$
For example, is it correct to say that
$$
\arctan\left(\frac{\sin x}{\sqrt{x+1}}\right)\le\frac{\sin x}{\sqrt{x+1}}\ \ \forall x\in\mathbb{R},
$$
since $\arctan t=t-\frac{t^3}{3}+\frac{t^5}{5}-\dots$, wher... | If $0\leq f(x) <1$, yes, of course. Since $\frac{d}{dy}\arctan y=\frac{1}{1+y^2}\leq1$ (and $\arctan(0)=0$), you'll have
$$ \arctan y \leq y, \quad\text{for }\ y\geq0. $$
Clearly, the situation is reversed if $y<0$, because both functions are negative. You can say that $|\arctan f(x)|\leq|f(x)|$ with no restrictions on... |
18415 | This question has already been asked but was never answered properly. After clearance with @Seth I am now asking it again. This will allow me to respond and possibly modify the question a lot easier. The original question can be found here:
[Map Ctrl and Alt to mouse thumb buttons](https://askubuntu.com/questions/1621... | I spent a lot of time trying to make that binding work. I eventually found a solution, which is complicated but works well and doesn't imply third party software.
I share it here hoping it will help people. Besides, I know this is not perfect in terms of security, so any constructive feedback is more than welcome.
The... |
18430 | I'm looking for an answer to the following question. (An answer to a slightly different question would be good as well, since it could be useful for the same purpose.)
>
> Given a set *C* consisting of *n*
> subsets of {1, 2, ..., *n*}, each of
> size *k*, does there exist some small A
> $\subset$ {1, 2, ..., *n*}... | I believe, reading the abstract, that the paper "Transversal numbers of uniform hypergraphs", Graphs and Combinatorics 6, no. 1, 1990 by Noga Alon answers your question in the affirmative, for some definition of ``your question''. Namely, the worst case is that $A$ has to have size about $2\log k/k$ times $n$, and this... |
18505 | (Similar question related to SQL Server : [**SO Link**](https://stackoverflow.com/questions/2624713/how-do-i-insert-multiple-rows-without-repeating-the-insert-into-dbo-blah-part))
I know in Sql Server 2008 or above, you can insert multiple rows doing the following:
```
INSERT INTO MyTable (Name, ID)
VALUES ('First',1... | Sybase doen't have insert syntax as SQL Server. What's wrong with showed below classic method?
```
INSERT INTO MyTable (Name, ID) VALUES ('First',1)
INSERT INTO MyTable (Name, ID) VALUES ('Second',2)
INSERT INTO MyTable (Name, ID) VALUES ('Third',3)
go
``` |
19047 | I want to open image / video in modal popup so I have a button on click I can show image. but when I have both image and video its difficult that how can I check that tags in jQuery.
My html code for zoom image in popup
```
<div>
<img src="image/zoom-icon.png" id="zoomImg" >
<div class="bigthumb">
<im... | You can use [`.is()`](http://api.jquery.com/is/)
>
> Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments
>
>
>
```
if($(this).is('img')){
//Do something
}
``` |
19316 | I want to remove an index in a table whose access in php never uses the indexed column. Index takes up extra space and I am trying to trim it. It's a table of phone numbers. A phone number is linked to a user profile's id. So it has 3 columns. `id` (index), `number` and `person`. I was wondering if removing the index w... | In the case you show, only the `person` column would benefit from an index.
Indexes help in basically four cases:
* **Row restriction**, that is finding the rows by value instead of examining every row in the table.
+ **Joining** is a subset of row restriction, i.e. each distinct value in the first table looks up m... |
19969 | So yesterday I was developing some sort of offline functionality. Therefore, I added an ApiService that returns Observables.
Currently, I fetch my access\_token for jwt-Authentication and then use this token to generate Headers for my API-Request. After a successful request, I save the result to my storage. This works... | it helped me
```
yum update -y libstdc++.x86_64
yum install libstdc++.i686
``` |
20730 | For example, this is the code that I am using:
```
String commandString = "UPDATE Members SET UserName = @newName , AdminLevel = @userLevel WHERE UserID = @userid";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnectionstring"].ConnectionString))
{
SqlCommand cmd = new ... | That code looks fine. Parameterisation is the way to go, as opposed to concatenating user-supplied values in an adhoc SQL statement which can open you up to sql injection attacks. This can also help with execution plan reuse.
The only thing I'd add, is I prefer to explicitly define the datatype and sizes of the parame... |
21229 | I am having issues trying to run Virtual Box; which are the "`appropiate headers"`??
```
WARNING: The character device /dev/vboxdrv does not exist.
Please install the virtualbox-dkms package and the appropriate
headers, most likely linux-headers-generic.
You will not be able to start VMs until this pro... | Did you try:
```
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install --reinstall virtualbox-dkms
```
Hope this will help. |
End of preview. Expand in Data Studio
No dataset card yet
- Downloads last month
- 4