question stringlengths 66 13.6k | response_j stringlengths 40 27.8k | response_k stringlengths 16 13.3k |
|---|---|---|
I have this code:
`$myVariable = someRanDomFunction($blah)`
The problem is that `someRanDomFunction()` might return an array, an object, an empty array, boolean value or NULL.
What if the best way to check that `$myVariable` has some data?
right now i'm doing this:
`!empty($myVariable )`
Will it cover all cases?
... | ```
var_dump(empty(NULL)); // returns bool(true)
```
empty is enough. If you say a boolean is no data, check also for !is\_bool. (`empty(false)` returns also `true`)
Or better, use only `if ($result)`; this should be enough.
Or what do you call "some data"?
UPDATE: What you need:
>
> php > var\_dump(!empty([]));... | Simply doing an implicit boolean check will exclude `false`, `array()`, and `null`.
```
if ($myVariable) {
//will execute as long as myVariable isn't an empty array, false, null, or 0 / '0'
}
```
`!empty()` does exactly the same thing, with added suppression of warnings about undefined variables / array indices.... |
I'm using jQueryUI and have a modal dialog setup. The designer wants the close button to look like this:

I currently have it set up like this:

The icon is not quite right, ignore... | set class ui-dialog css property overflow as visilble. Hope that helps. | Try to give the different value of `border-radius` and `height` value.
it could be the reason border-radius value is just half of the height. so change the `height` value.
For example
```
.ui-dialog .ui-dialog-titlebar-close {
border-radius: 17px;
height: 50px; /*change from 33 to 50px*/
margin: -10px 0 0;
p... |
My Django models are organized as follows.
```
class Animal(models.Model):
first_name = models.CharField(max_length=128, unique=True)
class Meta:
abstract = True
class Cat(Animal):
def meow(self):
return "mreooooow"
class Dog(Animal):
def bark(self):
return "AARF!"
class EvilMonkey(Animal):
... | You may want to go the route of [multi-table-inheritance](https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance). This would let you make queries on the base model. | From the docs:
*Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. **This model will then not be used to create any database table.** Instead, when it is used as a base class for other models, ... |
we got the following vectors:
$$v\_1, v\_2, w\_1, w\_3 \in V$$
$V$ is a vector space so that $\DeclareMathOperator{Sp}{Sp}\Sp\{v\_1,v\_2\} = \Sp\{w\_1,w\_2\}$
it's also defined that $\{v\_1,w\_2\}$ is linear independent.
1. Prove that the group $\{v\_1,v\_2\}$ is also a linear independent.
I thought about proving it... | Let $[F]$ be the area of a figure $F$.
Since $\angle{WYA}=30^\circ,\angle{AYZ}=60^\circ$, one has
$$\begin{align}a+b&=[YWA]\\&=[\text{sector}\ YWA]-\left([\text{sector}\ ZYA]-[\triangle{ZYA}]\right)\\&=(2\sqrt 3)^2\pi\times\frac{30}{360}-\left((2\sqrt 3)^2\pi\times\frac{60}{360}-\frac{\sqrt 3}{4}\times(2\sqrt 3)^2\rig... | Base on the following simple principle:-
$n(A \cap B) = n(A) + n(B) – n(A \cup B)$,
the said region can be found by a series a additions and subtrations of regions whose areas can easily be found. Example:-

For further example, see my answer in [F... |
I want to use perl regular expressions on the vim command line. For example, to capitalize the words on the current line, you could type:
```
:s/(\w+)/\u$1/g
``` | You can filter any line or range of lines through an external command in vim, using !. E.g., you can do:
`:.!perl -pe "s/(\w+)/\u\1/g"`
which will filter the current line through that perl command. ( Here `:` to get into command line mode, and the `.` which follows mean the current line; you can also specify a line r... | Use the [eregex.vim](http://www.vim.org/scripts/script.php?script_id=3282) plugin. It's very useful and I have had no problems with it. |
How would you test a developer that claims to have \*nix shell experience (just to be clear, we don't want to test if someone can develop on \*nix, only that they know their way around the command line).
I was thinking about making them solve a problem of getting information out of log files, which would involve some ... | From my experience with my numerous colleagues since I started to work, nobody wants to fake Unix knowledge: either they "*know their way around the command line*" or they simply say "no way!".
Just ask if the candidate is willing to work on a Unix workstation and let him tell you how far he can go through bash. He wi... | It depends on what level of experience you want them to have. IF this isn't for someone who will develop for \*nix systems, and also not for \*nix system admins, but just for regular developers that sometimes need to do some work on a \*nix system, how much experience do they actually need?
Anything such a developer ... |
I have data that looks like this:
```
country source
0 UK Ads
1 US Seo
2 US Seo
3 China Seo
4 US Seo
5 US Seo
6 China Seo
7 US Ads
```
For each country I want to get the ratio of each source. I did a groupby on country and source and got the table below w... | You could do something like for debugging such errors.
```
process.on('uncaughtException', function(err) {
console.log(err.stack);
throw err;
});
```
You could also increase your stack trace size limit and/or stack size.
```
node --stack_trace_limit=200 app.js //defaults to 10
node --stack-size=1024 app.js // d... | Stack Trace does not contain your file because this type of error is created server connection issue like:
**Host Timeout**
```
[ 'code' ]
e.code => ECONNRESET
```
**Console output**
```
{ Error: socket hang up
at createHangUpError (_http_client.js:250:15)
at TLSSocket.socketCloseListener (_http_client.js... |
I'm trying like that (also at <https://gist.github.com/1703994>):
```html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?1.27.2"></script>
<script type="tex... | Simply call the `.on` method as a getter for the registered value (i.e. your handler function), then call the result of that:
```
g.select("path").on("click")();
```
It gets a little more complicated if your handler uses the bound data and/or event fields, or if you've got multiple event listeners bound (e.g "click.... | I came this thread looking for a d3 mousemove event for angular unit testing.
@natevw answer
```
g.select("path").on("click")();
```
helped a lot on mouseover event. But, applying that to mousemove was giving an e.source null error.
The work around was to set the d3 event programmatically.
```
d3.event = docume... |
This code does not work. Please tell what the error is....
```
class Error(Exception):
def __init__(self,mssg):
self.mssg = mssg
class InputError(Error):
def __init__(self,val):
super("Input Error")
print val
```
Now I write in other part of my program
```
a = raw_input("Enter a num... | The problem is that you're using [`super()`](http://docs.python.org/library/functions.html#super) incorrectly. The proper way is:
```
class InputError(Error):
def __init__(self, val):
super(InputError, self).__init__(val)
print val
``` | [`super()`](http://docs.python.org/library/functions.html#super) is used to access methods of a superclass that have been overridden in the subclass, not to instantiate the superclass with arguments.
What you appear to be trying to do is something like:
```
class InputError(Error):
def __init__(self,val):
... |
Can you make devices that produce and use electricity like power supplies, motors, light bulbs, etc. in a society without metal? Not just metal isn't in the device, you can't even use metal in the production process.
Edit: There is enough trace metals for human biology to work, but not enough for metallurgy.
Could sta... | Graphite conducts and is a natural mineral. So does charcoal to some degree, and eventually graphene and nanotubes.
I think they would work with biological materials and discover ways to treat and preserve tissues that act as electric components, and then mimic them with more synthetic forms.
Look at the experiment w... | Electricity and magnetism are both present in biology (eg, see [Biomagnetism](https://en.wikipedia.org/wiki/Biomagnetism) and [Bioelectromagnetics](https://en.wikipedia.org/wiki/Bioelectromagnetics)) .
Organic computers (brains) and machinery (muscles) and energy storage (food/electrolytes) are all around us.
Non-met... |
this is my HTML
```
<div id="remove">Username</div>
```
and this is my JS code
```
function slice() {
var t = document.getElementById("remove");
t.textContent = t.textContent.slice(0, -3);
}
slice();
```
Username load from foreach
```
{foreach from=$last_user item=s}
{$s.date}
{$s.username}
{/foreach}
```
This... | The only secure way to make sure the client can't see a particular piece of information is to never send it to the client in the first place. Otherwise, there will always be a way for the client to examine the raw payloads of the network requests and figure out the information they aren't supposed to know.
You'll need... | JS doesn't change the source, it can only change the DOM, so what you can do is to keep the element empty and add a value to it using js, but don't forget that js runs on the client's side so its better here to send the string from the server without the last 3 characters. |
I have a table : Name
When I do a : **SELECT \* FROM Name**, it give the results as :
```
Name
======
aaa
bbb
ccc
sss
```
I want the result to be like in one row only :
```
Name
====
aaa bbb ccc sss
```
How can I get this? | Try this one -
```
DECLARE @temp TABLE
(
col NVARCHAR(50)
)
INSERT INTO @temp (col)
VALUES
('aaa'),
('bbb'),
('ccc'),
('sss')
SELECT str_string = (
SELECT col + ' '
FROM @temp
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
```
Or try this -
```
DECLARE @string NVARCHAR(MAX)... | May be over-egging the pudding for your requirement but a CLR aggregate function for concatenating rows into single values is a very handy thing to have in your toolbox. Something like below. Runs much faster than xml in my experience, and supports GROUP BY etc so is quite powerful. Only works in SQL2k8 or above and wi... |
I want to bring the `user_id: 1` ones under the users with the codes I give below, but the results are always empty.
I am not getting any errors, but I do not fully understand where I am making mistakes :/
\*In addition;
What is `bson.M{}` What is `bson.D{}`. I did not fully understand what the differences are betwe... | ---
Solution:
---------
To add examples you have to decorate the action method with SwaggerOperationFilter:
```
[SwaggerOperationFilter(typeof(OperationFilter))]
Upload(IFormFile file, [FromForm]IEnumerable<MetadataValue> list)
[...]
internal class UploadOperationFilter : IOperationFilter
{
public void Apply(Ope... | Following the answer provided by ***rperwinski***, if you are using ***Newtonsoft.Json*** instead of ***System.Text.Json***, you should replace:
Inside the *IOperationFilter*
```
var options = new JsonSerializerSettings();
options.Converters.Add(new StringEnumConverter());
options.Formatting == Formatting.Indented;
... |
In an effort to reduce the likelihood that I'll get mouse-related RSI in my (dominant) right hand, I've taken to using an additional second mouse with my left.
I'd like to flip the left and right mouse buttons on *just* the left-hand mouse, but the **Switch primary and secondary buttons** option in the Mouse Propertie... | The following program worked for me, try it out, hope will be helpful for you! Best of luck!
[EitherMouse 0.4](http://www.autohotkey.com/forum/topic48238.html) - auto switch mouse buttons on second mouse | Unless your mouse has some proprietary drivers/apps that let you reconfigure the buttons to whatever you want, you can't do it from Windows alone. As you already found, the Windows Mouse properties window applies to all plugged-in and recognized pointing devices. Collectively they will share one cursor and set of behav... |
I've written a small program in C++ that prompts the user for input, the user gives a number, then the computer displays the number reversed.
For example: 17 becomes 71. 123 becomes 321.
This is the program:
```
#include <iostream>
#include <string> //for later use.
using namespace std;
int rev(int x)
{
int r ... | While probably not in the intended spirit, the simple answer is that if you're only going to display it in reverse, you can cheat and just work with a string:
```
std::string input;
std::cin >> input;
std::cout << std::string(input.rbegin(), input.rend());
``` | You're not actually using the value that `rev` returns. You're just using the value `nr` which you pass to rev, and since you don't pass by reference, rev isn't being affected locally.
What you want to say is:
```
int nr;
cout << "Give a number: ";
cin >> nr;
int result = rev(nr);
cout << result;
return 0;
``` |
I accidentally killed my `ssh-agent`, how do I restart it without having to reconnect ?
I tried this but it does not work :
```bsh
$ eval $(ssh-agent -s)
Agent pid 8055
```
Then, I open a new Gnome terminal with CTRL+SHIFT+N from the previous terminal window and type :
```bsh
$ ssh-add
Could not open a connection... | **This doesn't work as you supposed. ssh-agent overwrites the configuration.**
TO FIX THIS---
*Find agent:*
```
eval "$(ssh-agent -s)"
```
Agent pid 9546
*Kill PID:*
```
kill -9 9546
```
THEN YOU CHECK
```
ssh git@gitlab.com-test
ssh git@gitlab.com
```
It should work now. | Try restart using the following command:
```
sudo service ssh restart
```
The private/public RSA SSH keys are located in ~/.ssh/id\_rsa and ~/.ssh/id\_rsa.pub, respectively. You can transfer the public key to another machine to connect to it through public key authentication. This can be done via ssh-copy-id like so... |
I have a tab view in my activity,
Currently I am doing a UI update in my fragments `onCreateView` but I don't think this is the correct place.
Is there a method I can overload which will be called when my tab gains view? So that when my user clicks on or scrolls to my tab, I can then poll my server and update my view... | Problem 1: know which tab has focus
Solution: setOnPageChangeListener on your ViewPager. With the received index, you know which tab is active.
Problem 2: how to execute a method from the active page (fragment)
Solution:
1. create a public method in your viewpager adapter: onNewTabSelected(int index)
2. create you... | You can update your view in each SectionFragment by using:
```
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) { }
else { }
}
```
@see: [How to determine when Fragment becomes visible in ViewPager](https://stackoverflow.... |
I'm looking for a laymen's introduction to computer hardware and organization. Here are some of the topics I would like to cover.
>
> 1. Brief intro to electronics.
> 2. Gates and state machines, intro to register transfer and timing.
> 3. Basic CPU design. Control.
> 4. Microprogrammed CPU design.
> 5. Cache system... | As mentioned already Code: The Hidden Language of Computer Hardware and Software is a great book that covers the fundamentals.
Here are a couple of other books:
[Computer Architecture: A Quantitative Approach](https://rads.stackoverflow.com/amzn/click/com/1558605967)
[The Essentials of Computer Organization and Arch... | For computer architecture, this books is really good
[Parallel Computer Organization and Design](http://www.cambridge.org/ca/academic/subjects/engineering/computer-engineering/parallel-computer-organization-and-design) |
I'm relatively new to C# working on a project currently where I want to exclude an item that is edited from an exception. In this scenario a user can edit an appointment including the appointment, however; there can not be overlapping appointments. When I run my program and edit the appointment, the exception is checki... | How about this:
```py
from itertools import chain
def get_grids(grid):
x, y = len(grid), len(grid[0])
assert (x, y) == (9, 9)
size = 3
out = []
for i in range(0, x, size):
rows = [*zip(*grid[i: i + size])]
for j in range(0, y, size):
out.append([*chain(*zip(*rows[... | If you are using numpy you can use reshape and swap axes to transform a 9x9 into a 3x3 matrix containing 3x3 sub-matricies.
```
A = np.array([
[0,0,0,3,0,1,6,0,2],
[0,2,0,0,0,0,7,1,0],
[0,0,8,0,7,0,0,0,0],
[2,4,0,5,3,8,1,9,0],
... |
I need to change the icon color according to the movie rating.
I made a function that receives the value of the classification and returns a value for the className inside the svg. However, all icons turn red. Someone help me to solve this problem.
**Conditions for changing color.**
**Rating: 0 to 100**
0 - white
2... | You have wrong condition here:
```
else if (note >= 20 || note <= 40) {
return "red";
```
instead of `||` should be `&&`.
But if you want to implement ranges, you should also correct other conditions:
```
const setVote = (note) => {
console.log("NOTE", note);
if (note <20) { // 0-19
return... | I found the error, it should be **===**. Look:
```
const setVote = (note) => {
console.log("NOTE", note);
if (note === 0) {
return "white";
} else if (note === 20 || note === 40) {
return "red";
} else if (note === 60) {
return "orange";
... |
I have two functions and i want to call one function when the radio button is checked as an employee and the other when the radio button is checked as a user.
```
employee.form.send = function() {
employee.validator.checkForm();
if (employee.validator.valid()) {
employee.form.submit();
}
};
invite.f... | The easiest way would be to create a key/value dataset and join with the original data
```
keyval <- data.frame(a = c(0, 0.001, 1, 4, 4.001, 8.001),
b = c('x', 'D', 'C', 'B', 'B', 'A'), stringsAsFactors= FALSE)
library(data.table)
setDT(df1)[keyval, b := b, on = .(a)]
df1
# a b
#1: 0.000 x
#2: 4.000 B
#3: ... | Try as.factor (x, levels=c (whatever levels and values separated by comma)) |
I am trying to execute reverse tcp command on a android device connected remotely(using `adb connect <ip-address>`). But I am getting following error while executing:
```
adb -s 192.168.0.101 reverse tcp:8081 tcp:8081
error: more than one device/emulator
```
but I have only one device connected.
```
adb devices
Li... | I just came across this, and while none of the answers worked I eventually got it working repeatably. Following these steps should get you wirelessly debugging your React Native app on your real Android device.
I ran `adb kill-server && adb start-server` first. I'm not sure if that's strictly necessary.
1. Connect yo... | ```
adb kill-server
adb start-server
adb reverse tcp:8081 tcp:8081
``` |
I have an MVC application using Razor. I have a partial view that uses a jquery script. The jquery script only works when it is referenced in the partial view and not in the \_layout view. When using firebug, I cannot see the script when it is referenced in the partial view. Is there a way to reference all scripts in t... | Look into using Robot's getPixelColor method:
```
color = robot.getPixelColor(coord.x, coord.y);
```
e.g.,
```
import java.awt.AWTException;
import java.awt.Color;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
public class PixelColor {
private static final long SLEEP_DELAY = 400L;
... | To get the pixel color where the mouse pointer is, you have to get the mouse position in every
iteration of the loop, and then use the method `getPixelColor`of robot.
```
while(true)
{
pointer = MouseInfo.getPointerInfo();
coord = pointer.getLocation();
System.out.print(coord.x + " " + coord.y);
Syste... |
There must be something simple I am missing. I'm trying to get the index of the element but keep getting -1.
HTML:
```
<div id="rating_boxes">
<img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" />
<img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" />
<img src="/img/ratingbox.gi... | `index()` returns the index of the given element with a list of elements, not within a parent element. To find the index of the clicked image, you need to find all the images, not the *parent* of all the images.
You want something like this:
```
// Find all the images in our parent, and then find our index with that ... | If you want to know the position of the rating box, a more robust way is to use:
```
var index = $(this).prevAll('img').size();
```
I.e., calculate the number of img elements before this element. The index method requires you to first select the parent element, then all img elements inside. This is a tad faster. |
Is it correct to write my classes like this? In question is the method `getPrice()` in the `Item` class. Every Item needs to have a `getPrice()`. But I can't actually return something. So I fire the `this.getPrice()` with gets me the Price of the `ProductItem`. Is there a more solid / better designed solution?
```
cla... | It sounds like `Item` should be an abstract class then, with `getPrice()` being an abstract method:
```
public abstract class Item {
private final String description;
public Item(String description) {
this.description = description;
}
public abstract double getPrice();
public String getD... | `double getPrice(){return this.getPrice();}` is basically an infinite loop.
You should set that price first.
```
class Item {
String description;
double price;
public Item(String description) {
this.description = description;
}
public void setPrice(double price) {
this.price = pric... |
I am trying to change the "show more" text depending on the state. This isn't working:
```
<div id="description">
text goes here
</div>
<div id="more-less-container">
<a href="#" id="more-less">expand / collapse</a>
</div>
<script>
... | Use `$('#more-less').text('show more');` instead of innerHTML.
jQuery wraps DOM Elements into jQuery objects, if you would want to use the `innerHTML` property, you could use the `.html()` function instead - but `.text()` is better as it will html-escape the content.
The alternative, to really access `innerHTML` pro... | innerHTML is a DOM function, for jQuery use .html() since you're manipulating a jQuery object
```
$('#more-less').html('show less');
``` |
I used to think those are random events but someone over at [physics.stackexchange.com](https://physics.stackexchange.com/a/77002/29481) insists that randomness means something else so I am at a loss here. Can someone help me out?
What do you call an event that happens without a cause? | Well, there is always the word **causeless**: so you could simply say a **causeless event**. A rough synonym is **fortuitous**.
You could potentially say a **random event** or **chance event**.
The commentators on the physics forum are correct: as a scientific term, that isn't the technical meaning of **random**. But... | Depending on context also consider [***self-generated***](http://dictionary.reference.com/browse/self-generated?s=t)
>
> ***self-generated*** adjective
> 1. happening or arising without apparent external cause; "spontaneous laughter"; "spontaneous combustion"; "a spontaneous abortion" [syn: spontaneous] [ant: induce... |
This is probably a really simple question however Google isn't my friend today.
I have something like this but it says call to undefined function
```php
<?php
class myClass{
function doSomething($str){
//Something is done here
}
function doAnother($str){
return doSo... | Try the following:
```
return $this->doSomething($str);
``` | Try:
```
return $this->doSomething($str);
```
Have a look at this as well: <http://php.net/manual/en/language.oop5.php> |
I have an UITextView in my iPhone app which is editable.
New button is created inside the UITextView whenever user select a specific function.
As the button is always placed on the left side in the text view, I need to position the cursor on the right side of the button so that user can see what they are typing.
I ... | Try something like this:
```
dispatch_async(dispatch_get_main_queue(), ^{
inView.selectedRange = NSMakeRange(3, 0);
});
```
This will cause selectedRange to be executed on the main thread at the beginning of the next runloop. | change `selectedRange` of your textView. for example to place cursor at position 3:
`[textView setSelectedRange:NSMakeRange(3, 0)];`
In your case, added some spaces on the textView contents might helps. and observer `textview
's textDidChanged event` to prevent these space will be deleted by user. |
I am trying to implement searching in my Meteor app. I don't exactly understand how it ties together. At this point, I have this following code:
html:
```
<form class="navbar-search pull-left">
<input type="text" class="search-query" placeholder="Search">
</form>
```
js:
```
Template.menubar.events({
'keyup in... | What is probably happening is your form is being submitted when you hit enter. Try an `preventDefault()`. Probably something like this would work:
```
Template.menubar.events({
'keyup input.search-query': function (evt) {
console.log("Keyup value: " + evt.which);
if (evt.which === 13) {
console.log... | In case anyone got here trying to implement the search function as well, I recommend the following:
```
meteor add matteodem:easy-search
```
On client and server:
```
Players = new Meteor.Collection('players');
// name is the field of the documents to search over
Players.initEasySearch('name');
```
On the client,... |
```
var i = -1;
$('.rightBtn a').click(function(){
--i; // this part works..
if(i == -z){
$(".homeSlider").css("margin-left", 0);
$('.homeSlider').animate({
marginLeft: '-='+$(window).width()
}, function(){
var i = -1; // this is wher... | You're returning `i` without there being anything to receive it. Set the value, don't return it.
Basically you're passing `i` back to the HTML. HTML is stupid. It doesn't know what to do with it. | To summarize, there are lots of things wrong here:
1. The `.animate()` function is asynchronous so it returns BEFORE the completion function runs so the completion function has no effect on the return value from your click function.
2. The return value from the click function is used to decide whether click propagatio... |
My application's main Activity is a TabActivity and it contains an OptionsMenu. I define some other Activities (which go into a tab) and I would like to define a menu in each of these activities and have its menu merged with the main one. Is it possible? | Yes, this is possible. Basically you just inflate multiple xml files into the same options menu. Items are added to the menu in order of inflation.
Just overwrite `onCreateOptionsMenu(Menu menu)` for your `TabActivity`, inflating the xml file containing the main options. Then overwrite it for each of your inner tab ac... | Are you creating the menus dynamically or in separate XMLs?
if Dynamically you can just set it up as
```
public void createMenu()
{
//Main Menu here
switch(tab)
{
case '1': //add tab 1 menu
break;
case '2': //add tab 2 menu
break;
}
}
``` |
On my laptop, turning on autorepeat (`xset r on`) does not work. When checking the output of `xev`, it seems that the reason why autorepeat fails is because another key is being pressed intermittently (although I am not pressing anything), which cancels autorepeating the currently held down key. When no keys are being ... | It turns out that disabling PEAQ WMI hotkeys fixes it. I disabled PEAQ WMI hotkeys through first checking `xinput list`, to find the id:
```
user@hostname.com:~$ xinput list
⎡ Virtual core pointer id=2 [master pointer (3)]
⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer... | I have the same issue on elementaryOS after latest kernel update. I posted about it [here](https://unix.stackexchange.com/questions/416327/system-keeps-registering-key-presses-i-do-not-press). Using one of the answers, `sudo modprobe -r peaq_wmi`, solved the problem for me.
EDIT: Adding `xinput --disable 17` into .xi... |
This is my JavaScript code to find elements with desired `.text()` but it's not working.
```
var divCollection = getElementByClass("titletrack");
for (var i=0; i<divCollection.length; i++) {
if(divCollection[i].text() == title) {
findMeText = divCollection[i].text();
alert(findMeText);
}
}
``` | [WORKING FIDDLE](http://jsfiddle.net/pgPgR/1/)
Hope this is what you had in mind. This may look complicated and im sure there is a simpler way of doing it. But it works.
```
var divCollection = document.getElementsByClassName("titletrack");
for (var i = 0; i < divCollection[0].childElementCount; i++) {
if (divCo... | Try this:
```
var divCollection = document.getElementsByClassName('titletrack');
```
That is, getElementsByClassName instead of getElementByClass.
Something like this would finish the deal:
```
var str = '';
var strSearchingFor = 'foo';
for(var i=0; i < divCollection .length; i++)
{
str+= " " + divCollection[i... |
I have this following sentence:
>
> 横線――HPバーの名で呼ばれる青いそれは、俺の生命の残量を可視化したものだ。
>
>
>
There are a few questions I came up with about this sentence:
1. The first part of the sentence is: `横線――HPバーの名で呼ばれる青いそれ`, my question is how can this sentence be parsed? How does the long `――` change the meaning/parsing of the s... | To add to @dainichi's answer, `横線` is probably better translated as "horizontal line", not "side line".
Also, the `ーー` could probably be replaced easily by `すなわち` or `言い換えて`. "That horizontal line, that is/in other words, that blue thing called the 'HP Bar', ..." | The horizontal line -the blue one called HP bar- visualizes my remaining life. |
I have done a series of logistic regressions for various outcomes, and have been using the `rms` package to calculate Nagelkerke R^2 without any problems until now...
When I try and use it in a regression with a binary outcome for obesity (=1) or 'normal' weight (=0), I get a message saying there is an error in my for... | I encountered similar problems and I found a solution [here](http://r.789695.n4.nabble.com/Help-understanding-why-glm-and-lrm-fit-runs-with-my-data-but-lrm-does-not-td4745387.html). The problem could be that the MLE does not converge in a number of steps. I added `maxit=1000` in the arguments and it worked. | Solution
========
The alternative method of calculating R^2 suggested by tmfmnk worked without any problems.
I have pasted it here in case it helps others. Thank you everyone for your replies.
```
# Install the DescTools package and open the library
install.packages("DescTools")
library(DescTools)
# Run the ... |
In the following code, I want to set the opacity only for the background color of the `li` (not the text). However, it is important NOT to use the `rgba` for the background.
I'm trying following, but it sets the opacity for the link text as well.
**HTML:**
```
<ul>
<li><a href="#">Hello World</a></li>
</ul>
``... | Old question, but new answer! :)
Fortunately, the new versions of Chrome and Firefox support **8 digit colors**. That's really cool, especially when you're developing and testing software.
For example:
```
background-color: #ff0000; (Red)
```
If you want a opacity of 0.5, you can do this:
```
background-color: ... | The opacity is applied at the content and all children. You can't set a different opacity for the children.
However if you don't want to use rgba you can use a png with opacity that you want.
And setting a png to your `li` in the background is the best solution in this case |
What is the right way to use a class defined in one file and extend it another, in node.js?
Currently I have:
```
'use strict'
class BasePageHandler {
constructor(app, settings, context) {
}
}
return module.exports;
```
In the 'child' class file I have:
```
'use strict'
var BasePageHandler = require (... | You need to correctly export your class in`BasePageHandler.js` file:
```
module.exports = BasePageHandler;
``` | The accepted answer is technically fine, but really if you're using ES6 then you should go all in and use [ES6 export/import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export).
```
/*jshint esversion: 6 */
class BasePageHandler {
constructor(app, settings, context) {
}
}
ex... |
```
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller
{
public function __construct()
{
parent::__construct();
//Model for fetching users in database
$this->load->model('user', '', TRUE);
}
public function i... | Try this one,
```
SELECT a.product_ID,
COALESCE(b.user_id,0) `user_id`
FROM products a
LEFT JOIN liked_items b
ON a.product_ID = b.product_ID
```
Sometimes `liked_items.user_id` can be possibly `NULL` so instead of displaying `NULL` in the result list, it can be changed using `COALES... | If you're using MS SQL Server you can use IsNull like so:
```
SELECT p.product_id, IsNull(li.user_id, 0)
FROM products p
LEFT JOIN liked_items li
ON (p.product_id = li.product_id);
```
If not, Joao or John's answer will do just fine. |
I am setting up SVN on a Red Hat Linux machine. My scenario is that I have two projects in the same directory:
* `/var/www/svn/proj1`
* `/var/www/svn/proj2`
My subversion.conf has the following configurations:
```
<Location /svn/proj1>
DAV svn
SVNPath /var/www/svn/proj1
AuthzSVNAccessFile /etc/svn_proj1-... | Confused. Confused. Confused...
But, I'm easily confused...
You have two projects. The first one you use:
```
SVNPath /var/www/svn/proj1
```
and the second you use:
```
SVNParentPath /var/www/svn/proj2
```
Why is one `SVNPath` and the other `SVNParentPath`? There's a difference. You specify `SVNPath` when you r... | The `Location` and `SVNParentPath` directive should have the same trailing slash rule: either with or without.
So it should be:
```
<Location /svn/proj2/> <--- Here trailing slash (or not)
[..]
SVNPath /var/www/svn/proj2/ <--- Here same like Location
[...]
</Location>
``` |
After looking Snowflake documentation, I found function called `array_intersection(array_1, array_2)` which will return common values between two array, but I need to display array with values which is not present in any one of the array.
**Example 1:**
Let's say I have following two arrays in my table
```
array_1 ... | I'm not sure you need a sequence like the other answer. This works pretty cleanly:
```
with myTable as (
select array_construct('a', 'b', 'c', 'd', 'e') as a1
,array_construct('a', 'f', 'c', 'g', 'e') as a2
)
SELECT array_agg(coalesce(a1.value,a2.value)) WITHIN GROUP (ORDER BY coalesce(a1.value,a2.value)) as newar... | Snowflake could achieve the desired effect with usage of SQL and array functions:
* [ARRAY\_CAT](https://docs.snowflake.com/en/sql-reference/functions/array_cat.html)
* [ARRAY\_EXCEPT](https://docs.snowflake.com/en/sql-reference/functions/array_except.html)
Query:
```
SELECT arr1, arr2,
ARRAY_EXCEPT(arr1, arr2... |
I'm writing a version of the Unix `expand` utility that replaces tabs with spaces in a file. To do this, I'm reading in each character and testing if it is a tab character. If it is, it replaces the tab with the given amount of spaces, otherwise the character gets printed.
My main method goes like
```
int main(int ar... | 1. You're calling `putchar` on a string (`" "`), but it wants a `char` argument (`' '`). (Actually an `int`, but only passing a `char` is safe.)
2. The segfault is probably due to the `fclose` on `fp`, which may be `NULL`. You should check the return value from `fopen`. The reason you only notice after `parse_file` is ... | In C string literals are of type `char *`, a pointer to some area containing string characters.
`" "` is a string literal, not a character. Use `' '` when you need a single character |
Let $(a\_{n})\_{n}$ be a sequence of non zero real numbers such that the series $$\sum\_{n=1}^{\infty} a{\_{n}}$$ converges absolutely. Let $f:\mathbf{R}\rightarrow\mathbf{R}$ be a function with the property that $$\lim\_{x\to 0} f(x)/x$$ exists and is finite. Show that $$\sum\_{n=1}^{\infty} f(a{\_{n}})$$ converges ab... | Note that the convergence of $\sum\_{n=1}^{\infty} a{\_{n}}$ implies
$$\lim\_{n\to\infty}a\_n= 0$$
Hence $$\lim\_{x\to 0} f(x)/x= \lim\_{n\to \infty} f(a\_n)/a\_n= l$$
for $\varepsilon= |l|+1>0$ there exists N such that for $n>N$ we have
$$||f(a\_n)/a\_n|-|l||\le|f(a\_n)/a\_n-l|<|l|+1\implies |f(a\_n)|\le (2|l|+1)... | Hint: Denote the limit of $f(x)/x$ as $L$ whenever $x\rightarrow 0$. Try to argue that $\left|f(a\_{n})\right|<(|L|+1)|a\_{n}|$ for large $n$. |
I want to get data from DB and add string to theme and put them in another query . When I run code I've got this error :
>
> Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or
> access violation: 1064 You have an error in your SQL syntax; check the
> manual that corresponds to your MySQL server ve... | Try this:
```
def functionOne(textFile):
textFileVar = open(textFile, 'r')
def splitKeyword(argument):
keywordList = []
for line in argument:
keywordList.append(line.strip().split(','))
return keywordList
output = splitKeyword(textFileVar)
print(output[1][0])
... | keywordlist is a local variable to the function splitKeyword which return it so you can directly use this function and reduce the code.
```
def functionOne(textFile):
textFileVar = open(textFile, 'r')
def splitKeyword(argument):
keywordList = []
for line in argument:
keywordList.app... |
I have been using "usleep" to stop a thread during some milliseconds and I have checked that is stopping more time than expected.
I am sure I am doing something wrong, I am not an expert in Swift, but I don't understand it because it is very easy to check. For example:
```
DispatchQueue.global(qos: .background).async... | A couple of thoughts:
1. The responsiveness to `usleep` is a function of the [Quality of Service](https://developer.apple.com/documentation/dispatch/dispatchqos.qosclass) of the queue. For example, doing thirty 20ms `usleep` calls on the five queue types, resulting in the following average and standard deviations (mea... | I, too, get times around 120 ms when sleeping a thread on a background queue:
```
import Foundation
DispatchQueue.global(qos: .background).async {
let timeStart = Date()
usleep(20 * 1000) // 20 ms
let timeEnd = Date()
let timeDif = timeEnd.timeIntervalSince(timeStart) * 1000
print("start: \(timeSt... |
I have the following code:
```
<div style='width: 200px; border: 1px solid black;'>
<div style='display: inline-block; width: 70px; border: 1px solid green;'>
asdfasdf<br />asdf
</div>
<div style='display: inline-block; width: 70px; border: 1px solid green;'>
asdfasdf<br />were
</div>
</div>
```
This... | `display: inline-block;
*zoom: 1;
*display: inline;`
you can add inline-block for other browser but for IE you can add style with \*. it only works in ie | Changing the doc type worked for IE
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
``` |
Hi guys I am trying to get a basic emulator running to display Hello World but the emulator appears but the phone never switches on. Please help me.
```
D:\Installed_Softwares\AndroidSDK\tools\emulator.exe -netdelay none -netspeed full -avd Nexus_5_API_24_2
ERROR: resizing partition e2fsck failed with exit code 9... | `glClear` affects the output buffers. So it is part of rendering. If you want to clear as part of your rendering, put `glClear` inside your `render` function.
You have it inside `update`. I suspect that whomever is calling `render` and `update` (LWJGL, presumably?) doesn't guarantee any particular ordering to them. So... | It is not very clear in my question, but the answer is that I cleared the screen, swapped buffers, rendered, etc. Which doesn't work.
```
glClear(...);
glfwSwapBuffers(...);
...render...
```
This is how it is currently, and this doesn't work.
```
glClear(...);
...render...
glfwSwapBuffers(...);
```
This is how I ... |
I have this route in a laravel 4 app:
```
Route::controller('about','AboutController');
```
When I go to `http://website/about/imprint` I get the imprint, but when I go to `http://website/about/imprint/12345` , (which is not used in the controller) I get the imprint as well. It does not throw an error.
Is this a pr... | >
> **Swift 3**
>
>
>
```
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
selectedCell.contentView.backgroundColor = UIColor.darkGray
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexP... | Swift 4
```
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let selectedCell = tableView.cellForRow(at: indexPath)! as! LeftMenuCell
selectedCell.contentView.backgroundColor = UIColor.blue
}
```
If you want to unselect the previous cell, also you can use the different logic f... |
I am using Entity Framework Code First in my ASP.NET MVC application. One of my classes has several columns that are added together. I am storing these columns as computed columns in the tables by running an alter table script in the database initializer. Let's say the class looks like:
```
public class Bond
{
... | This is [definitely not supported](http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/a6d182bd-5027-4793-bfd9-ef88a44ec6bc) - defining `Computed` option on custom property will throw exception. Code first = logic in code. If you need custom computed properties use database first. The only databa... | I'm doing computed columns in CF (WinForms) like that (I don't know if it's the best):
This is one Entity:
```
public class Result
{
public int ResultId { get; set; }
public int StudentId { get; set; }
public Student Student { get; set; }
public float Arabic { get; set; }
public float English { ge... |
Alright, this has been on my mind for a while now. I'm in the process of creating a reusable corporate namespace(class library) for all common middle-tier objects. This assembly can then be referenced by any of our developers during the development phase of their project. Here's my question. Is it more acceptable to cr... | As a general rule, I use to separate assemblies if they are not explicit coupled. For example if you have a low level Networking API, and other API for FTP related operations, probably the later depends upon the former; but for the API user, your developers; there is no need to have both in a single assembly; maybe one... | I dont think their is a right answer for this but I tend to use a common naming approach for all of our libraries.
I have a library that handles a lot of the middle-tier functionality, sort of like common tasks that most apps would use.
Web.CreditCard
Web.CreditCard.Authorization
Web.CreditCard.Charge
Web.Cr... |
I need to calculate checksums of quite large files (gigabytes). This can be accomplished using the following method:
```
private byte[] calcHash(string file)
{
System.Security.Cryptography.HashAlgorithm ha = System.Security.Cryptography.MD5.Create();
FileStream fs = new FileStream(file, FileMod... | I like the answer above but for the sake of completeness, and being a more general solution, refer to the `CryptoStream` class. If you are already handling streams, it is easy to wrap your stream in a `CryptoStream`, passing a `HashAlgorithm` as the `ICryptoTransform` parameter.
```
var file = new FileStream("foo.txt"... | Hash algorithms are expected to handle this situation and are typically implemented with 3 functions:
`hash_init()` - Called to allocate resources and begin the hash.
`hash_update()` - Called with new data as it arrives.
`hash_final()` - Complete the calculation and free resources.
Look at <http://www.openssl... |
React hooks makes it possible to use all React features such as component state and lifecycle methods without class declarations (just function components). This reduces boilerplate, duplication and negotiates the use of bug-prone `this` keyword. Further it makes it easy to isolate and share common state-management log... | Sending a message **to** a device require that you call the Firebase Cloud Messaging API and specify the FCM Server Key. As its name implies, this key should only be used on a trusted environment, such as your development machine, a server that you control, or an environment like Cloud Functions. The reason this is req... | According to [firebase\_messaging readme](https://pub.dev/packages/firebase_messaging) page, in the last section, you can not send a cloud message using the flutter `firebase_messaging` library read the [Sending Message](https://pub.dev/packages/firebase_messaging#sending-messages).
To subscribe a user to a topic:
``... |
I have 3 tables guest\_user\_info,pg\_company,user\_profile.
In guest\_user\_info have 2 columns:
```
g_uid | company_id
```
In pg\_company have 2 columns:
```
company_id | user_id
```
In user\_profile have 2 columns:
```
id |user_email
```
Here i want to get `user_email` from `user_profile.i` have `g_uid` va... | >
> Is there a way in CSS to check if the `btn-primary` class exists inside of `stepwizard__step` and if it does, to change the color of `stepwizard__step-text` to red?
>
>
>
Yes, but only if `stepwizard__step-text` comes *after* the `btn-primary`. This is because rules only go down the DOM tree, never to parent e... | You can do this:
```css
.btn-primary+p.stepwizard__step-text {
color: red;
}
```
```html
<div class="stepwizard__step">
<a class="btn btn-primary stepwizard_btn">1</a>
<p class="stepwizard__step-text">Payment</p>
</div>
```
Hope it works for your use! |
I'm trying to join multiple tables in q
```
a b c
key | valuea key | valueb key | valuec
1 | xa 1 | xb 2 | xc
2 | ya 2 | yb 4 | wc
3 | za
```
The expected result is
```
key | value... | I also have this problem because the version of Facebook's SDK I am using is not updated. So if you are using it too, just try to use the updated version of Facebook's SDK v3.21.1, and that warning is solved. | I had this issue, I am using ffmpeg lib and .so files, I resolved issue by below steps:
First, I use Android Studio. So, if you're using Eclipse, try to find your own way.
The cause of the issue is the libavformat.so file which is using OpenSSL 1.0.2d. We need to update it. But, just updating libavformat.so will cause... |
I've spilled 5-10 mL of liquid on my Macbook Pro (13 inch, early 2015) some hours ago. I purchased this laptop a few months ago. It has 16 GB of RAM and 512 GB storage, though this is probably irrelevant. The liquid came in contact with the trackpad (including the edges of it). I did not turn it off. Rather, I ran the ... | OK, having wrecked a couple of Macbooks myself because someone spilled liquid into them, I'll tell you what to expect:
First, power it off and remove the battery if you can (but I don't think you can with your model) and prop it up so any liquid can run out. Give it about a day for the liquid to dry.
Or better yet, g... | If you spill water on your MacBook or MacBook Pro - if you have an air purifier, target it to the keyboard/screen where the liquid is until it's dry.
I put my MacBook Pro in an upside-down v-shape over a towel and then positioned my air purifier a few inches away from the keyboard/screen - in 5-10 mins my computer was... |
I have a df where column 'elements' looks like this:
[](https://i.stack.imgur.com/13p35.png)
How can I split each word using this as separator "|" then send each word as key avoiding duplicates?
I used this but it's not working:
```
for row in df... | If `id` is the only column name in common, you can take advantage of the `USING` clause:
```
spark.sql("select * from tbl1 join tbl2 using (id) ")
```
The `using` clause matches columns that have the same name in both tables. When using `select *`, the column appears only once. | ```scala
val joined = spark
.sql("select * from tbl1")
.join(
spark.sql("select * from tbl2"),
Seq("id"),
"inner" // optional
)
```
`joined` should have only one `id` column. Tested with Spark 2.4.8 |
I built a basic Windows Form app. I want to make it so that my program deletes itself after a date of my choosing.
Specifically, when someone clicks on the .exe to run it, and if it's after a certain date, the .exe is deleted. Is this possible? If yes, how do I do this?
I think my code would look something like this... | This works, runs a commandline operation to delete yourself.
```
Process.Start( new ProcessStartInfo()
{
Arguments = "/C choice /C Y /N /D Y /T 3 & Del \"" + Application.ExecutablePath +"\"",
WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, FileName = "cmd.exe"
});
``` | It cannot delete itself while it is running, because its executable and library files will be locked. You could write a second program that takes in a process ID as an argument, waits for that process to die, and then deletes the first program. Embed that as a resource in your main application, then extract it to `%TEM... |
I try to add a little triangle as the current page indicator under the list item of my navbar with class "active" using ::after.
However,
1. The alignment of the triangle may not be center for all list items due to the length differences.

... | I found an answer to this [here](https://gist.github.com/cerisier/118c06d1a0147d1fb898218b57ba82a3/) such that my initialization script now looks like this:
```
#!/bin/bash
# Install tools
apt-get -y install python3 python-dev build-essential python3-pip
easy_install3 -U pip
# Install requirements
pip3 install --upg... | You can also use the Conda init action to setup Python 3 and optionally install pip/conda packages: <https://github.com/GoogleCloudPlatform/dataproc-initialization-actions/tree/master/conda>.
Something like:
`gcloud dataproc clusters create foo --initialization-actions \
gs://dataproc-initialization-actions/conda/boo... |
I wanted to know if I can pass back individual parameters from a php script to be stored in dfferent JS variables on the page I'm working on, while also returning generated html code from the php script along with those parameters.
Basically I would like to return some data like this from php using ajax:
```
$valid =... | Add the data to an array and `json_encode` then:
```
$ret = array();
$ret["valid"] = "true";
$ret["access"] = "false";
$ret["htmlcontent"] ="lorem ipsum<br/>some more text<b>bold</b>";
echo json_encode($ret);
```
And in your client side:
```
$.ajax({
url:"your_script.php",
success:function(resp) {
... | Just let PHP print them directly as JS variables. It also saves your client one HTTP request.
```
<script>
var valid = <?= $valid ?>;
var access = <?= $access ?>;
var htmlcontent = <?= json_encode($htmlcontent) ?>;
</script>
``` |
I am attempting to list the List's items but I get repeatedly displayed the first row of the List. The List should contain three different product rows. Instead, ListView shows the same, first row three times.
I create list like this:
```
List<ProductsNumber> ProductsNumberList = new List<ProductsNumber>();
... | There are many ways you can achieve this.
I would just give you the direct solution (as I'm sure someone else will), but I think there's a lot of benefit in figuring it out yourself with the right guidance, especially given that you are "new", as you claim. :)
**Here is one approach you can take**:
Create a "store... | Solved with the following:
```
var superbag = function(sup, sub) {
sup.sort();
sub.sort();
var i, j;
for (i=0,j=0; i<sup.length && j<sub.length;) {
if (sup[i] < sub[j]) {
++i;
} else if (sup[i] == sub[j]) {
++i; ++j;
} else {
// sub[j] not in sup, so sub not subbag
return ... |
I'm having some problems with JRTPLIB c++ win32 version, compiling in visual studio2010.(http://research.edm.uhasselt.be/~jori/page/index.php?n=CS.Jrtplib). I've emailed the author but have yet to received a reply. The problem I am experiencing is this:
```
error C1083: Cannot open include file: 'rtpconfig_unix.h': No... | Include ws2\_32.lib in your project. Had the same problem.
(And remove if you already include it, wsock32.lib and winsock.h header file to avoid colissions) | What are the redefinition errors?
If they are from winsock, removing winsock2.h from your includes might help. |
I have a view on angular just like this:
[](https://i.stack.imgur.com/JimWN.png)
And this is my dashboard.component.ts:
```
export class DashboardComponent implements OnInit {
tablePresetColumns;
tablePresetData;
ngOnInit() {
this.tablePreset... | You can use the below
```
<td *ngFor="let cell of row"
[ngStyle]="{'color': (cell.content === 'Busy') ? 'green' : (cell.content === 'overload') ? 'red' : (cell.content === 'idle') ? 'yellow' : ''}">{{cell.content}}
</td>
```
The condition should be on `cell.content` but not on `row.content` | ```
<table class="table" [ngClass]="modes">
<thead *ngIf="columns">
<tr>
<th *ngFor="let col of columns"> {{col.content}} </th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of data">
<td [ngClass]="cell.content.toLowerCase()" *ngFor="let cell of row"> {{cell.con... |
i am using magento 1.5 and have strange problem in the category edit and product edit page in
admin, the subcategory tree for one category is not showing i have write the custom code to find the subcategory for that particular category and its not showing any subcategory using that code, but when i have checked in the... | I can assure you that Zachary Schuessler solution works perfectly in 1.7.0.2.
I am just posting so it can help future questions.
1- I got this problem after i removed alot of products from a under Root category using "Catalog/Manage Categories" and deselecting the products in "Category Products" Tab.
2- The pattern c... | Here is an SQL statement to update all the children counts if they become out of sync from moving categories around. Had this issue occur for us when the server crashed halfway through moving a category inside another one.
```
UPDATE catalog_category_entity a
INNER JOIN
(SELECT parent_id, count(entity_id) tot... |
Different Data structures are used according to requirement but how would I know which data structure should I use? I just want to know how to choose an appropriate data structure ? Thanks | This flowchart is for the STL in C++, but you could implement any of the data structures supported by the STL containers in C.
* List is a linked list
* Vector is a dynamic array
* Deque is something like a list of dynamic arrays -- sort of splits the difference.
* Queue and Priority queue are like they say (usually q... | Not what you are looking for, but it **depends**.
It depends on the data that you are storing, any constraints on accessing that data, do you need to be able to look things up really fast? Does it need to maintain any kind of sort on the data? Will you be sorting it later?
Even when you choose a data structure (Linke... |
I've been thinking about batch reads and writes in a RESTful environment, and I think I've come to the realization that I have broader questions about HTTP caching. (Below I use commas (",") to delimit multiple record IDs, but that detail is not particular to the discussion.)
I started with this problem:
1. Single `G... | HTTP protocol supports a request type called "If-Modified-Since" which basically allows the caching server to ask the web-server if the item has changed. HTTP protocol also supports "Cache-Control" headers inside of HTTP server responses which tell cache servers what to do with the content (such as never cache this, or... | In re: [SoapBox](https://stackoverflow.com/questions/433195/im-confused-about-http-caching#433206)'s answer:
1. I think `If-Modified-Since` is the two-stage `GET` I suggested at the end of my question. It seems like an OK solution where the content is large (i.e. where the cost of doubling the number of requests, and ... |
I understand that react doesn't update state immediately then can someone tell me how i can log this state synchronously as my state is not a boolean and this answer didn't help me [setState doesn't update the state immediately](https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately).... | `setState` takes a callback as its second argument.
```
handleNext() {
this.setState(prevState => ({
value: prevState.value + 1
}),() => console.log('updated', this.state.value));
}
``` | You code is fine, try printing `this.state.value` in your render function.
Example:
```
class A extends Component {
constructor(props) {
super(props);
this.state = {
value: 1,
};
}
handleNext() {
this.setState(prevState => ({
value: prevState.value + 1,
}));
}
handlePrev() ... |
Here's a problem. I have my models:
```
class Collection < ActiveRecord::Base
has_many :collection_ownerships
has_many :items
has_many :users, :through => :collection_ownerships
validates :title, presence: true, length: { maximum: 25 }
validates :description, length: { maximum: 100 }
end... | The error is probably that you are sending through a blocked port. The default port for `sendmail` is 25. If you are at a place where you don't control the servers, try asking a tech guy what server you need to set it as. Here's the command to do so. Add it before the `sendmail()` command
`sendmail_options(smtpPort="2... | Try using mailR (<https://cran.r-project.org/web/packages/mailR/index.html>) that supports SMTP authentication. |
I'm using this terrible API for a client. It packages HTML/JS to an iPad app.
I'm using iScroll but it interferes with the built-in scrolling mechanism. They've provided some code to disable their scrolling, but it only works when loaded after all other scripts have loaded (so the API says).
My code structure
```
<h... | You can use [JQuery.getScript](http://api.jquery.com/jQuery.getScript/) and in the success function get other scripts.
It should look something like this:
```
$.getScript('scriptss1.js', function() {
$.getScript('scriptss2.js', function() {
$.getScript('scripts3.js', function() {
});
... | another option would be to add the defer attribute
```
<script src="scripts1.js" defer="defer"></script>
<script src="scripts2.js" defer="defer"></script>
<script src="scripts3.js" defer="defer"></script>
```
see <http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#attr-script-defer> |
I am creating a form and for what ever reason, when using a `bindOnLoad` with a remote CFC, my default value doesn't seem to appear.
Here is the cfselect:
```
<cfselect name="edcs"
id="edcs"
multiple="false"
bind="cfc:Components.requestSearch.getEDCs()"
bindonload="true"
... | I've run across this issue with CFSELECTs and binding CFCs. I have also been unable to add an `<option></option>` tag with a bound CFSELECT. The best way would be to create the query and force the result to have the desired input on the top. For example:
```
SELECT distinct
rtrim(edc_nm) as edc_nm_display,
rt... | The query will need to return that value. Try adding it as a UNION statement. |
How do I fetch data from db using select query in a function?
Example
```
function ec_select_query($student, $row = '', $fields=array()) {
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
while($row = mysql_fetch_assoc($qry)){}
return $row;
}
``` | If you want to return all rows then first save it in an array in while loop then return this array.
```
function ec_select_query($student,$row='',$fields=array())
{
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
$result = array();
while($row = mysql_fetch_assoc($qry))
{
$result[] = ... | This code might help you :
```
function ec_select_query($student,$row='',$fields=array())
{
$q = "SELECT * FROM student";
$q = mysql_query($qry);
while($row = mysql_fetch_array($qry))
{
return $row;
}
}
``` |
In a iPython notebook, I have a while loop that listens to a Serial port and `print` the received data in real time.
What I want to achieve to only show the latest received data (i.e only one line showing the most recent data. no scrolling in the cell output area)
What I need(i think) is to clear the old cell output ... | You can use [`IPython.display.clear_output`](http://ipython.org/ipython-doc/dev/api/generated/IPython.display.html#IPython.display.clear_output) to clear the output of a cell.
```
from IPython.display import clear_output
for i in range(10):
clear_output(wait=True)
print("Hello World!")
```
At the end of thi... | **Simple**,
if you want to clear the output of that current cell only just use this at the end of that cell
```
from IPython.display import clear_output
clear_output(wait=False)
``` |
I'm writing a program in C, that is supposed to read arrays of doubles from files of arbitrary length. How to stop it at EOF? I've tried using feof, but then read the discussions:
[Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong)
[How does C h... | The return value of fscanf is -1 when you hit eof (or other problems) so try `while(fscanf(…) >= 0)` for your outer loop. (Whether you accept a zero return value or not depends on how you want to handle bad data -- as other posters have pointed out, you will get 0 if no numbers are converted.
I like using the 'greate... | During the scan, save the results of `fscanf()`
```
int cnt;
double d;
while ((cnt = fscanf("%f", &d)) == 1) {
more_space = realloc(A, (N+1)*sizeof(double));
if (more_space == NULL) Handle_MemoryError();
A = more_space;
A[N] = buff;
N++;
}
if (cnt == 0) Handle_BadDataError();
``` |
In our code in a lot of places, I keep seeing this...
```
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view":childView]))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat... | For sorry you can't use this , but you can try something like this
```
let rr = UIView()
rr.backgroundColor = UIColor.red
self.view.addSubview(rr)
rr.translatesAutoresizingMaskIntoConstraints = false
["H:|-100-[rr]-100-|","V:|-100-[rr]-100-|"].forEach{NSLayoutConstraint.activate(NSLayoutConstraint.constraints(with... | No, unfortunately the syntax doesn't permit this - see the grammar in [the docs](https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage.html)
Specifically, the line `<orientation> H|V` means that the value of `orientation`
can be `H` or `V` but not both.
... |
I am looking for a word or phrase for wanting someone to fail, but only to teach them a lesson.
It's not easy to explain. For example, when you tell a child, "Don't run down the hill or you will fall," but they continue anyway. To prevent them from doing this in the future on a bigger hill with a much more harsh outco... | ***once bitten, twice shy***
>
> Once hurt, one is doubly cautious in the future. This seemingly old observation, presumably alluding to an animal biting someone, was first recorded in 1894.
>
>
> [The American Heritage® Idioms Dictionary](http://idioms.thefreedictionary.com/Once+bitten,+twice+shy)
>
>
> Variatio... | What about "CORRECTIONAL SUFFERANCE"? I wish him to undergo this correctional sufferance so that he may not falter again. It is no reprisal but revisionary. |
End of preview. Expand in Data Studio
Ministack-preferences
Subset (1000 training samples and 1000 test samples) of the lvwerra/stack-exchange-paired dataset. The original dataset is really heavy and long to process, so hopefully this will help you to try RLHF a little faster.
- Downloads last month
- 9