INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to see mails sent by me in Evolution
I can't find a setting the makes Evolution display messages sent by me in thread view. I can find them in Sent folder, but I'd like them to be part of the normal threads. | You will need a couple of steps. Enable the threaded folder view with `Ctrl+T`. Then set "Include threads: all related" in the search folder configuration.
If you are using an SMTP server other than Gmail's you may need a further hack. You could bcc yourself at a plus extension of your Gmail address; something like "+threaded", then configure the external Evolution accounts to "Always bcc to" this address.
There is a detailed walk-through of this approach by Matt McCutchen on his blog. | stackexchange-unix | {
"answer_score": 3,
"question_score": 7,
"tags": "evolution"
} |
How to update rows in db and delete left overs where id = 1234
I have a data table with 3 columns. Datable table Named Usertable with columns labeled UserID, UserFavFood, UsersFavSport. Each column has many rows (+100). I would like to search the UserID where UserID = 1234, update rows that need to be updated, and delete the remainder/non updated rows where UserID = 1234. Is it faster to just delete all UserID=1234 and then repopulate it with new info or is there a way to update where UserID = 1234 and delete remaining rows that UserID = 1234?
I'm using PostgresSQL and I've tried deleting and reinserting but I am doing something wrong.
DELETE FROM Usertable WHERE UserID = '1234'
AND
INSERT into Usertable(UserID, UserFavFood, UsersFavSport)
VALUES('1234', 'Chicken', 'Baseball')
Is it possible to send the values in Lists of three? As in Values = ['1234', 'Chicken', 'baseball'],['1234', 'Cheese', 'Soccer']? | In Postgres 8.2 or later the `VALUES` clause can take multiple tuples:
INSERT INTO Usertable (UserID, UserFavFood, UsersFavSport)
VALUES
('1234', 'Chicken', 'Baseball'),
('1234', 'Cheese', 'Soccer');
Regarding executing the delete and insert together, you would have to use a transaction as far as I know. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "postgresql"
} |
Show unbound keys
I want to define some key bindings for my new found usage of helm, amazing mode btw, and I want to do it without overwriting the usage of other keys. I realize that the number of different key combinations is infinite, but is there some way to see all _undefined_ key bindings for say 1 level deep?
For example, I want to know what key bindings are available after hitting `C-c`, and then get a buffer with a listing of `C-c some_keys`.
Assuming this feature doesn't currently exist? | Check out the `free-keys` package, which gives you a function of the same name that shows you all your currently unused key-bindings.
`bind-key` is also a helpful tool which gives you a cleaner syntax for defining your own bindings, i.e.:
(bind-key "C-h C-k" 'free-keys)
`bind-key` also comes with a handy defun called `describe-personal-keybindings` to see all the key-bindings you've set as well as if and what bindings you've overridden. | stackexchange-emacs | {
"answer_score": 28,
"question_score": 35,
"tags": "key bindings"
} |
String aggregate using a variable
Is is okay to use a variable to concatenate a value from several rows ( as an implicit aggregate function )? It seems to work fine on my machine, but I haven't seen it recommended.
declare @v_str varchar(4000) = ''
select top 5 @v_str = @v_str + ',' + city_name from city_table order by city_name
print @v_str | From nvarchar concatenation / index / nvarchar(max) inexplicable behavior "The correct behavior for an aggregate concatenation query is undefined." | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sql server, tsql, aggregate functions, sql server 2014, string concatenation"
} |
Same window function in multiple fields in T-SQL: optimization?
I am using the very same windowing function in multiple WHEN in a T-SQL SELECT.
SELECT
ModuleUsage = CASE
WHEN Operation = 1 and OperationResult=1 and 1 != LAG(operation) OVER(
PARTITION BY moduleid, clientname
ORDER BY moduleid, clientname, timestamp, operation
)
THEN 1
WHEN Operation = 2 and OperationResult=3 and 1 = LAG(operation) OVER(
PARTITION BY moduleid, clientname
ORDER BY moduleid, clientname, timestamp, operation
)
THEN -1
ELSE 0
END
, *
FROM [dbo].[LicencesTracing]
Is it evaluated twice or does the query optimizer reuse the result the second time? Thanks in advance | Could we rewrite the query like below in order to have the function only one time?
-- window function <> 1
SELECT CASE WHEN LAG(operation) OVER(PARTITION BY moduleid, clientname ORDER BY moduleid, clientname, timestamp, operation) <> 1
THEN CASE WHEN Operation = 1 and OperationResult=1 THEN 1 ELSE 0 END
-- window function = 1
ELSE
CASE WHEN Operation = 2 and OperationResult=3 THEN -1 ELSE 0 END
END AS ModuleUsage
,*
FROM [dbo].[LicencesTracing];
And I thing using `IIF` will simplify the code:
SELECT CASE WHEN LAG(operation) OVER(PARTITION BY moduleid, clientname ORDER BY moduleid, clientname, timestamp, operation) <> 1
THEN IIF(Operation = 1 and OperationResult=1, 1, 0)
ELSE IIF(Operation = 2 and OperationResult=3, -1, 0)
END AS ModuleUsage
,*
FROM [dbo].[LicencesTracing]; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "sql server, tsql, query optimization, ranking"
} |
Migrating to MVC6 / EF7: PluralizingTableNameConvention
I'm migrating my MVC5 app to MVC6. Currently I'm using two conventions
public class RentABikeDbContext : DbContext
{
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
However it looks like in MVC6/EF7 there is no Conventions property on the new Microsoft.Data.Entity.ModelBuilder class. What is the proper EF7 way to specify conventions? | Entity Framework 7 does not have any built-in pluralization, so nothing to remove there, and Cascade delete is not yet implemented < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "asp.net core mvc, entity framework core"
} |
Docker private repo with multiple images
Can we host multiple images on single private repo ?
Like
1. ubuntu:12.04
2. ubuntu:14.04
So My private repo like MYREPO:ubuntu:12.04 and ubuntu:14.04 | Yes.
# Create a container
docker run --name image1 -it busybox echo Image1
# Commit container to new image
docker commit image1 amjibaly/stuff:image1
# Push to dockerhub repo
docker push amjibaly/stuff:image1
# Create a second container
docker run --name image2 -it busybox echo Image2
# Commit container to new image
docker commit image2 amjibaly/stuff:image2
# Push to same dockerhub repo with different tag
docker push amjibaly/stuff:image2 | stackexchange-stackoverflow | {
"answer_score": 26,
"question_score": 11,
"tags": "docker"
} |
ControlsFX RangeSlider Can't be disabled
I am using `ControlsFX 8.40.9` and latest JDK 1.8.0_51
I can't set the `RangeSlider` to disabled.
I am getting warning in log when setting `slider.setDisable(true);` :
> _Aug 05, 2015 5:40:45 PM javafx.scene.CssStyleHelper calculateValue WARNING: Could not resolve '-fx-disabled-opacity' while resolving lookups for '-fx-opacity' from rule '_.range-slider:disabled' in stylesheet jar:file:/C:/Users/dimitrim/Documents/NetBeansProjects/FlatDesignTest/dist/run546627019/lib/controlsfx-8.40.9.jar!/org/controlsfx/control/rangeslider.bss* | This was a bug that has been fixed in ControlsFx. See < for details | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "java, javafx, controlsfx"
} |
Voltage output of this circuit
LM1117-ADJ in question;
Is the output voltage 1.4V? Have I calculated correctly?
121/1000 + 1 = 1.12
1.12 * 1.25 = **1.4**

Excel12f(xlEventRegister, 0, 2, (LPXLOPER12)TempStr12(rgFuncs[i][0]), TempInt12(xleventCalculationEnded));
to
Excel12f(xlEventRegister, 0, 2, (LPXLOPER12)TempStr12(L"EventOnCalc"), TempInt12(xleventCalculationEnded));
2- create the event function :
__declspec(dllexport) void WINAPI EventOnCalc()
{
Excel12f(xlcAlert, 0, 1, TempStr12(L"On Calc event !"));
}
I tested and the EventOnCalc() event is fired. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "xll"
} |
Detecting Keypresses in the Turtle module in Python
I want it so my Up key moves the turtle and my S key cleans the screen. Also, the up key command works:
import turtle
from turtle import Turtle, Screen
screen = Screen()
jack = Turtle("turtle")
jack.color("red", "green")
jack.pensize(10)
jack.speed(0)
def clean(x,y):
jack.clear()
def move():
jack.forward(100)
turtle.listen()
turtle.onkey(clean,"S")
turtle.onkey(move,"Up")
screen.mainloop() | @jasonharper is correct about the capitalization issue (+1) but you clearly have other issues with this code as you import turtle two different ways. I.e. you're mixing turtle's _object-oriented_ API with its _functional_ API. Let's rewrite the code to just use the object-oriented API:
from turtle import Screen, Turtle
def move():
turtle.forward(100)
screen = Screen()
turtle = Turtle('turtle')
turtle.color('red', 'green')
turtle.pensize(10)
turtle.speed('fastest')
screen.onkey(turtle.clear, 's')
screen.onkey(move, 'Up')
screen.listen()
screen.mainloop()
I've changed variable names to make it clear which methods are _screen_ instance methods and which are _turtle_ instance methods. Your double import obscured this. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "python, turtle graphics, python turtle"
} |
Swift: calling function from another viewcontroller makes objects nil
I have two simple ViewController: the first one has a IBOutlet linked to a UIImageView and a function that sets the image alpha channel. The second controller has a button that, when it's trigged, should call the function to set the alpha channel.
Here my code:
class FirstViewController: UIViewController {
@IBOutlet imageView: UIImageView!
func changeAlphaChannel() {
imageView.alpha = 0.5
}
}
class SecondViewController: UIViewController {
let firstController = FirstViewController()
@IBAction func buttonPressed(sender: UIButton) {
firstController.changeAlphaChannel()
}
}
Calling `changeAlphaChannel()` inside FirstViewController works as aspected, but if I call it pressing the button, `imageView` becomes nil and the app crashes. How can I fix this? Thanks | Its crashing because your imageView is nil. Just initialising `firstController` with `FirstViewController()` will not do. You'll have to load that view controller from storyboard. You can do it this way
let storyboard: UIStoryboard = UIStoryboard.init(name: "StoryboardName", bundle: nil)
let firstViewController: FirstViewController = storyboard.instantiateViewControllerWithIdentifier("StoryboardIdentifier") as! FirstViewController
**UPDATE**
Now IBOutlets of firstViewController will be set only when firstViewController's view is instantiated, which in your case is not happening. What you have to do is first display view of firstViewController and then call your function. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 5,
"tags": "ios, swift"
} |
AS3 Reference subClass of subClass from parent without instantiating?
Can I access a static variable of a subClass' subClass? I don't want to instantiate it, just looking to get the variable because it has already been initialized by the subClass.
example:
package
{
public class A extends MovieClip {
private var classB:B = new B();
public function A() {
//**ACCESS B.C.MYVAR**
}
}
}
package
{
public class B extends MovieClip {
private var classC:C = new C();
}
}
package
{
public class C extends MovieClip {
public static var MYVAR = 1;
}
}
Thank you! | To access a **public static** var you can do so from anywhere within the same package via Class.property.
So to access MYVAR that's defined in Class C, you would use C.MYVAR.
You don't need to create an instance of a class to access static properties or functions within it - so long as they are public.
I don't recommend using **static** except for in rare cases such as a "utilities" class or something similar. A good example is the Math class that's inbuilt.
I mostly use static in a class that holds constants, like this example:
package
{
public class Elements
{
public static const FIRE:String = "FIRE_ELEMENT";
public static const WATER:String = "WATER_ELEMENT";
public static const ICE:String = "ICE_ELEMENT";
}
}
Then later I make use of this like so:
var myelement:String = Elements.WATER; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "flash, actionscript 3, subclass"
} |
SetState based on manipulated prop with hooks
How do I `setState` on a functional component with a manipulated prop with hooks before the page load?
On a class component I would do something like:
export default class Editable extends React.Component {
constructor(props) {
super(props)
const {clients} = this.props
this.state = {
columns: [
{title: 'test', field: 'test'},
{
title: 'test2',
field: 'test'
}
],
data: clients.map((client) => ({
test: client.test,
test2: client.test2,
}))
}
}
render() {
return
(...)
}
} | It can be done with `useState` \- this is only be used once. Keep in mind that you will need to use `useEffect` hook in order to change your state like you would have done with e.g. `componentWillReceiveProps`.
const initialColumns = [
{ title: "test", field: "test" },
{ title: "test2", field: "test" }
];
const Test = props => {
const [columns, setColumns] = useState(initialColumns);
const [data, setData] = useState(
props.clients.map(client => ({
test: client.test,
test2: client.test2
}))
);
return (...)
};
Just have a look at the console logging in Test.js here: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "reactjs"
} |
Can I remove BootCamp HFS+ driver
So, I have an iMac 27" Late 2012, and I have just installed Windows 10 Home 64Bit through BootCamp. BootCamp comes along with several "support software", useful drivers made for Windows and Apple hardware. I have recently noticed that one of the drivers mounts and makes read-and-writeable drives that are formatted in HFS+, including my Mac drive (which appears read-only) and an external HDD I make backups to. Since I'm afraid of Windows Ransomware, I'd like to remove any access to HFS+ drivers from Windows side of things. Is there any way to remove (or at least disable) the driver that enables HFS+? | AFAIK the Apple HFS+ drivers are read-only. You may have installed another read/write driver like Paragon.
To remove Apple HFS+ Driver:
1. Browse to C:\Windows\System32\drivers\
2. Move AppleHFS.sys & AppleMNT.sys to the Recycle Bin
3. Create a _Remove_AppleHFS.reg_ file with a text editor like NotePad and the following content:
Windows Registry Editor Version 5.00
[-HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\AppleHFS]
[-HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\AppleMNT]
You may have to add a trailing empty line.
Merging a reg file with the registry should work as following:
* Click on Start and then Run...
* Type in regedit, and then press OK
* In regedit, click on File, and then Import
* Enter the filename or otherwise locate the ".reg" file you want to enter, and press OK
* The contents of that ".reg" file will be entered into the registry.
4. Restart | stackexchange-apple | {
"answer_score": 7,
"question_score": 4,
"tags": "bootcamp, driver, hfs+"
} |
Short Story of Aliens Sailing/Mining on a Gas Giant who Attach to Females like Anglerfish
A couple years ago I read a short story set on/in a gas giant. The main character and narrator is an alien who flies a one man ship. He and the other males fly around and gather supplies and ultimately bring them back to the females. The females are giant flying whale/manta ray like creatures. If the males perform well, then they get to mate. This entails attaching to the stomach of a female and eventually getting absorbed like angler fish. The main character eventually finds a space craft (presumably human) and rescues it knowing it will give him the opportunity to mate. I can't find the story, and I would like to reread it. | I'm fairly sure you're describing The Deeps of the Sky by Elizabeth Bear (link goes to the full story).
Elements which match your description:
* Main character is an alien who flies a one-man ship
* He's gathering resources for a large female ship he hopes to mate with
* He finds a human craft and makes contact
* At the end, he gets to merge with the large female ship | stackexchange-scifi | {
"answer_score": 4,
"question_score": 10,
"tags": "story identification, short stories, aliens"
} |
Pan & Change Zoom to show Fusion Tables Query Results in Google Maps JavaScript API V3
I've created this map -- < \-- using Google Fusion Tables and Google Maps API. I'm attempting to modify the code so that the map will pan and zoom after executing the query. It seems that I need to use either the fitBounds function to display the bounds of the results, or something simpler like this:
// Change the center and zoom of the map
map.setCenter(results[0].geometry.location);
map.setZoom(10);
I'd prefer the second option so that I can set a consistent zoom level for each query. Any pointers or references for completing this are much appreciated. | **Add a spatial search to your code:**
FUSION TABLES allows **ST_INTERSECT** to be performed full reference: < (see `<spatial_condition>` )
// OPTIONAL: find the new map bounds, and run a spatial query to return
// Fusion Tables results within those bounds.
sw = map.getBounds().getSouthWest();
ne = map.getBounds().getNorthEast();
layer.setOptions({
query: {
select: 'lat',
from: tableid,
where: "ST_INTERSECTS(lat, RECTANGLE(LATLNG(" + sw.lat() + "," + sw.lng() + "), LATLNG(" + ne.lat() + "," + ne.lng() + ")))"
}
});
Full code: < (view source) | stackexchange-gis | {
"answer_score": 1,
"question_score": 3,
"tags": "google maps, google fusion tables"
} |
Closing Cursor Android
I'm creating an app and in an activity i have a listview with several items. when i click in an item, i start a new activity with the id of the item clicked. after the click, i close the db and the cursor in onStop. i do it in onStop because if i close the in onPause the user can see the listview becoming empty before the new activity starts. it actualy works pretty well, the problem is that i'm testing when the user presses the on/off button that suspends the device. if this happens i get the error that the cursor wasn't close. to close the cursor right. i would have to close the cursor in onPause, but if i close the cursor in onPause, the user see's the listview becoming empty.
What should i do? | So you are populating the data to list view
How is it that your list goes empty, are you clearing the data in your list?
You should close the db connection once you are done with your query/update/... action thats because there's not abundant connections available
Android is designed to close the db connections automatically once the application is exited, but when there's scarce of connection this is the problem
Once again verify why your list goes empty | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "android, android activity, android cursor"
} |
Does a lock icon show the user is logged in or needs to log in
I am working on a device where the admin can require the user to log into the device into order to use it. The developers originally used a closed lock to show that a user is is "locked out". !Developer Version
For some reason, for me, it makes more sense for a user that the locked icon is that they are securely in the system. However, I cannot put my finger around why "securely logged in" is a closed lock when most devices use a padlock to show you are locked out.
!Alternative Version
I ended up with an alternative with a user-based icon, but now I am really curious: when a user is securely logged in, is the padlock open or closed?
Edit: thanks for the responses. It all makes a lot more sense now. | Typically the locked padlock is used to indicate to the user that an action/item is secure.
For example in your web browser:
!enter image description here
Alternatively a locked padlock can be used to show that information is not accessible and requires login or other form of security to access.
For example the padlock icon is used on Mac OS to show that you need to provide authentication to make changes, but only in conjunction with a text label:
!mac padlock locked icon
An open padlock is then displayed to show that changes can be made:
!enter image description here
I would be very careful before using a padlock to denote logged in/out status. | stackexchange-ux | {
"answer_score": 0,
"question_score": 0,
"tags": "icons, login"
} |
How to zoom image on mouseover at some XY coordinate?
I display set of images(small). I need to show the larger image(300*300) at some XY co-ordinate when mouseover event occurs on an image while mousout larger image has to disappear . Please give some solution. | You thus actually want an image map. Since I've never used this I can't tell the details from top of head, but the link should help you further. You can for example make use of HTML `<map>` and `<area>` elements, or go ahead with a pure CSS approach.
There is no standard JSF component which can represent the `<map>` and `<area>` elements. The Sun JSF tutorial however (by coincidence) covers a custom component example with which you can represent them using pure JSF. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, html, jsf"
} |
csv value seperator is not working properly
csv_file = open("text.csv","w",encoding="utf-8_sig")
csv_file.write("Name,Author,Link,Price")
So result should be A column- Name B column- Author... But those all are at A column like this Name,Author,Link,Price. I am writing with pycharm, I checked CSV format value seperator is comma. And yeah row seperator ("\n") is working.
!CSV format | So I have just changed value seperator to semicolon wrote "Name;Author;Link;Price" and it worked. Because macOS uses ; as default delimeter | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -3,
"tags": "python, csv"
} |
Nested routing in webapp2
I am trying to create a URL routing that goes like:
/view/ _database_ / _table_
Where _database_ and _table_ is parameterized
that maps to a handler like
class ViewTable:
def get(self, database, table):
#get table schema
I was wondering how I can route this?
I tried this but it doesn't work:
application = webapp.WSGIApplication([('/view/(.*)/(.*)', ViewTable), ], debug=True) | The problem is the regex you are using to set up the routing (they are greedy, so the `/` matches `.*`. A better way to set it up would be:
application = webapp.WSGIApplication([
(r'/view/<database:[^/]*>/<table:[^/]*>', ViewTable),
], debug=True)
Even better, though, would be to use a regular expression that captures exactly the characters that what your database and table names can capture. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "python, google app engine, webapp2"
} |
Formula for Mapping three values
Hello there i need a formular for the following mapping and i dont want tables, thats the reason of the bit tag ;)
2 -> 1
1 -> -1
0 -> 0
or
2 -> -1
1 -> 1
0 -> 0 | With `(val>>1)-(val & 1)` you get your first result:
0 -> 0
1 -> -1
2 -> 1
The alternative result can be got with `(val & 1)-(val>>1)`:
0 -> 0
1 -> 1
2 -> -1 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -8,
"tags": "c, algorithm, math, bit manipulation"
} |
JSF page redirect with https then it will give ssl expire error in mozila
when i redirect JSF page through the https then it will move to that page but at that time it gives me error about ssl expire in mozila... | you will have to make new Keystore file because old one is expired..Go through this 3 easy steps..
<
SSL have limited validity for authenticate keystore file.
After created new keystore file just accept confirmation in Mozila for confirmation of valid user. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "jsf, ssl, https, mozilla"
} |
Запиь свойства в обьект JS
Нужно сделать проверку для обьекта и записать в него свойство. Если обьект существует то записываем в него свойство, если такого обьекта нет, то создаем обьект и записываем в созданый обьект свойство, как можно реализовать такоую проверку лаконично?
if(json.pupilFields)
json.pupilFields[field] = staticItems[field]
else {
json.pupilFields = {}
json.pupilFields[field] = staticItems[field]
} | var obj;
(obj = obj || {}).prop = 123;
console.log(obj);
Это
if(json.pupilFields)
json.pupilFields[field] = staticItems[field];
else {
json.pupilFields = {};
json.pupilFields[field] = staticItems[field];
}
можно переписать как
(json.pupilFields = json.pupilFields || {})[field] = staticItems[field]; | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript"
} |
Interpretation of field quantization
In the book on Quantum Field Theory by Peskin and Schroeder, it is explained how the field is promoted to an operator, now my question is that in Quantum Mechanics, operators act on kets, what does this field operator act on? | There is a Hilbert space also for quantum fields and the field operator acts on the vectors ("kets") of that Hilbert space. From this perspective there is no difference between quantum mechanics and QFT. | stackexchange-physics | {
"answer_score": 4,
"question_score": 1,
"tags": "quantum field theory, hilbert space, operators, second quantization, quantum states"
} |
Meaning of notation with two letters inside of parentheses [binomial coefficient]
What does the notation in the red box mean?
$$\Huge e^{\displaystyle \large \sum_{k=0}^n \bbox[2px,border:2px solid red]{\color{black} { {n \choose k}}}~\omega^k}$$ | $n\choose{k}$ is a 'binomial coefficient'. Sometimes read '$n$ choose $k$. It represents the number of ways of choosing $k$ items from $n$ distinct items where the order of choice is unimportant.
The value is ${{n}\choose {k}}=\frac{n!}{k!(n-k)!}$
$n$ and $k$ are nonnegative integers with $k\le n$. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "notation, math history"
} |
Possible to evaluate GLM in Python/scikit-learn using the Poisson, Gamma, or Tweedie distributions as the family for the error distribution?
Trying to learn some Python and Sklearn, but for my work I need to run regressions that use error distributions from the Poisson, Gamma, and especially Tweedie families.
I don't see anything in the documentation about them, but they are in several parts of the R distribution, so I was wondering if anyone has seen implementations anywhere for Python. It would be extra cool if you can point me towards SGD implementations of the Tweedie distribution! | Update (Jan 2023) - sklearn has Tweedie, Poisson, and gamma GLMs as of v 0.23 in May 2020.
* * *
There is movement to implement generalized linear models with Poisson, gamma, and Tweedie error distributions in scikit-learn.
Statsmodels has implementations of generalized linear models with Poisson, Tweedie, and gamma error distributions.
While I'm updating this answer, Spark ML also (experimentally) supports Poisson, Tweedie, and gamma distributions. | stackexchange-stats | {
"answer_score": 13,
"question_score": 13,
"tags": "generalized linear model, python, scikit learn, gradient descent, tweedie distribution"
} |
Problem with building the front-end-template
I am trying to install and use the React front end template for Substrate as per this tutorial, but when I run `yarn install` or `yarn start` in the project's root directory I get this error:
/home/.../substrate-front-end-template/.yarn/releases/yarn-berry.cjs:2
module.exports=(()=>{var e=
*blah blah blah*
SyntaxError: Unexpected reserved word
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
I am using yarn v.1.22.11 and node v.8.10.0. How can I fix this issue? | Check versions of Yarn and NodeJS. On those versions on my end all works fine:
tomek@rhei-box:~/workspaces/substrate-front-end-template$ node -v
v12.22.4
tomek@rhei-box:~/workspaces/substrate-front-end-template$ yarn -v
2.4.0
In case you are on Linux-like machine check nvm tool in order to be able to change fast versions of NodeJS. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "substrate"
} |
Epochs or Loss Convergence
I was training a Deep Neural Network using transfer learning and the loss value as of now is close to 1.7. I am using a dataset of 31,000 images and I do apply data augmentation techniques to help the model generalize better. However, I had confusion regarding epochs and loss values. Should I be training the model for say 50 epochs for good accuracy or would it be better if I trained until the loss value is as low as possible which will be very close to zero. Which one is recommended to get the best accuracy? Will more epochs cause the model to perform better than the lowest loss value? Any help would be greatly appreciated. Thanks in advance! | I think it is better to use early stopping method.Too many epochs will lead to overfitting the model.Early stopping allows you to stop the training once the model performance stops improving on a hold out validation dataset.
refer this link to the concept
< | stackexchange-datascience | {
"answer_score": 1,
"question_score": 0,
"tags": "neural network, deep learning, loss function, epochs"
} |
Factorization of $a^p-b^p \; ; p\in \text{prime}$
Is there a method for figuring out a factorization of $a^p - b ^p$ where $p$ is prime? This may be stupid, but I couldn't find the answer with Google. | You can use $$a^p - b^p = (a - b)(a^{p-1} + a^{p-2}b + a^{p-3}b^2 + \ldots + a^2 b^{p-3} + ab^{p - 2} + b^{p-1}).$$ | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "algebra precalculus"
} |
Setting an element's height to the height available in the viewport?
My element's height increases depending on what the user does with it. If I give it a wrapper div, and give that div an explicit pixel height and `overflow:auto`, it works as I would want it to (when the element becomes bigger than the height of its parent, it doesn't increase the size of the parent). I want the wrapper div to be as big as the space available on the page, but not allow it to expand beyond that. Giving it `height:100%` doesn't work, it just gets bigger. Giving it `height:100vh` also doesn't work because there are other elements on the page and so the size is too big.
I want the wrapper div to be able to expand until it becomes too big for the viewport (which `height:100vh` would achieve if it were not for the other elements on the page).
Basically I'm looking for something like `height : amount of available space in the viewport`. | This is what I ended up doing:
var viewportHeight = $(window).height();
var offset = $('#gridWrapper').offset().top;
$('#gridWrapper').height(viewportHeight - offset);
I execute the same stuff again on resize. `gridWrapper` is the id of the wrapping div. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "html, css"
} |
Using declared variables as column names
I'm looking for a way to use a dynamic variable as a column name as well - for example if I hypothetically use the following to define a financial year:
DECLARE @currentfy NVARCHAR(6) --Current financial year
SET @currentfy = YEAR(GETDATE()) - CASE WHEN MONTH(GETDATE()) < 4 THEN 1 ELSE 0 END
I then want to be able to do something like this:
SELECT @currentfy AS @currentfy
SELECT @currentfy - 1 AS @currentfy_1
So that it looks like as if I had done this:
SELECT 2010 AS [2010]
SELECT 2009 AS [2009]
Is there a way to do this without using dynamic pivoting? (as my tables are large and I want to avoid pivoting if possible). | No, use dynamic pivoting or an extra column/resultset to describe the subsequent columns/resultset | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, sql server 2005, tsql"
} |
Hide "Store" and other apps from Remote Desktop (Windows Server 2012)
I'm setting up a new Windows Server 2012 for Remote Desktop users.
How can I hide the "Store" app (and other apps) from the users?
Thanks!
Mojo | This can be mamaged through Group Policy in Server 2012
IT Administrators can turn access to the Windows Store on or off in the following ways: • For specific machines • For specific users and groups
Technet has more info regarding this. This is one section | stackexchange-superuser | {
"answer_score": 0,
"question_score": 0,
"tags": "remote desktop, windows server 2012"
} |
Where cached data gets stored and how to query the data?
I want to use ASP.NET caching. I have two questions:
1. Where is the cached data stored when ASP.NET caching is used? Is it stored server-side or client-side? If by default it is server-side, how does it helps in performance?
2. How to query the cached data? I have a lot of cached data and I want to retrieve records on the basis of filters. Do I have to use LINQ for this? | Cached data is stored server side. It helps performance by keeping the cached data on the server in memory and easily accessible by the application. This performance improvement beats reading the data from files, database queries, etc.
The easiest way to "query" cached data is to reference the cached object by the key you cached it under, then treat it as it was when you first cached it. From this point, once your object is once again an object, you can reference the data as you see fit, optionally using LINQ or any other means that is appropriate from the cached object. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "asp.net, linq, caching"
} |
Why does the Emperor-Over-the-Sea play such a small role in the Chronicles of Narnia?
The Emperor-Over-the-Sea is referenced at several points during the series. The Stone Table, Deep Magic and the Deeper Magic were all set in motion by him, and he is the father of Aslan.
At the same time, he does not directly enter the series; he does not appear to be present in Aslan's Country during _The Silver Chair_ or the events of _The Voyage of the Dawn Treader_ , and doesn't appear to directly intervene. He doesn't even seem to be present at the creation of Narnia during _The Magician's Nephew_ or the Final Judgment in _The Last Battle_ \- the entire country was sang into existence by Aslan.
Given that C. S. Lewis was not a deist, why is this? Why was the Emperor-Over-the-Sea such a remote figure? | He is a hero of another story.
> In works of fiction, it often seems like the world revolves around the Main Characters, that nothing interesting happens unless one of them is in the middle of it. And sometimes that’s true; sometimes the main cast are so important that nothing big can happen without their involvement. But other times, it’s not that the Main Characters are the only ones that stories happen to; it’s that we only see the stories that happen to the Main Characters. It turns out the supporting characters have their own adventures going on off-screen, where they’re the stars and the Main Characters only make cameo appearances. These characters are the Heroes of Another Story: we may not see much of their adventures, but it adds something to the fictional world if we know these people continue to lead interesting lives even when the Main Characters aren’t around. | stackexchange-literature | {
"answer_score": 1,
"question_score": 7,
"tags": "c s lewis, the chronicles of narnia"
} |
How to run multiple terminal consoles at the same time?
I have connected to three raspberry pis using ubuntu.I run a shell file in all three consoles using "enter". Because of this it take few seconds delay to run each file. I want to know how to run the shell file in all three consoles at the same time. | Use `tmux` which a "terminal multiplexer" that you can install on your client, e.g. on ubuntu it's `apt-get install tmux`
It has a feature called "synchronized panes", for you each pane would be a shell opened to one of your raspberry pi devices
When you activate the synchronized panes, the same key inputs will go to all of the panes, the command is `:setw synchronize-panes`
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ubuntu, terminal, ubuntu 14.04"
} |
efficient function to find harmonic mean across different pandas dataframes
I have several dataframes with identical shape/types, but slightly different numeric values. I can easily produce a new dataframe with the mean of all input dataframes via:
df = pd.concat([input_dataframes])
df = df.groupby(df.index).mean()
I want to do the same with harmonic mean (probably the scipy.stats.hmean function). I have attempted to do this using:
.groupby(df.index).apply(scipy.stats.hmean)
But this alters the structure of the dataframe. Is there a better way to do this, or do I need to use a more lengthly/manual implementation?
To illustrate :
df_input1:
'a' 'b' 'c'
'x' 1 1 2
'y' 2 2 4
'z' 3 3 6
df_input2:
'a' 'b' 'c'
'x' 2 2 4
'y' 3 3 6
'z' 4 4 8
desired output (but w/ hmean):
'a' 'b' 'c'
'x' 1.5 1.5 3
'y' 2.5 2.5 5
'z' 3.5 3.5 7 | Create a pandas Panel, and apply the harmonic mean function over the 'item' axis.
Example with your dataframes `df1` and `df2`:
import pandas as pd
from scipy import stats
d = {'1':df1,'2':df2}
pan = pd.Panel(d)
pan.apply(axis='items',func=stats.hmean)
yields:
'a' 'b' 'c'
'x' 1.333333 1.333333 2.666667
'y' 2.400000 2.400000 4.800000
'z' 3.428571 3.428571 6.857143 | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 4,
"tags": "python, pandas, scipy"
} |
Running total in Microsoft SSMS
How to get running total in SSMS ?
select E.Employee,E.Month,E.Year,E.Salary,
SUM(E.Salary) over (partition by E.Year order by E.Employee) as Cum_Sal
from Employees E
group by E.Employee,E.Month,E.Year,E.Salary
order by E.Year
Output needed:
!enter image description here | Try this:
select E.Employee
,E.Month
,E.Year
,E.Salary
,SUM(E.Salary) OVER
(
partition by E.Year
order by CASE E.Month
WHEN 'Jan' THEN 1
WHEN 'Feb' THEN 2
WHEN 'Mar' THEN 3
WHEN 'Apr' THEN 4
WHEN 'May' THEN 5
WHEN 'Jun' THEN 6
WHEN 'Jul' THEN 7
WHEN 'Aug' THEN 8
WHEN 'Sep' THEN 9
WHEN 'Oct' THEN 10
WHEN 'Nov' THEN 11
WHEN 'Dec' THEN 12
END
) as Cum_Sal
from Employees E
order by E.Year | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "sql, sql server"
} |
Open parenthesis followed by j produces "crash" (slight overlap of glyphs)
Using the Termes font in a large dictionary project, the open parenthesis and lower case Roman j glyphs are often in contact, and my proofreader has asked me to fix the problem, which she calls a "crash". I've tried inserting a small space manually in these places, but I wonder if there's another solution. Italics are not involved, so I see that italic correction will not work, but perhaps there is something similar for inappropriate touching between ( and j?
The text is `raggedright`; I'd prefer not to make any substantial changes to the rest of the code.
Example:
\usepackage{tgtermes}
\usepackage[T1]{fontenc}
...
to inlay (\tiny{~}\normalsize jewels
to inlay (jewels
...
!enter image description here | The solution, provided by @egreg and @David Carlisle in comments, is to use
(\kern0.1em j
Works like a dream; actually exactly like a dream. Here's a comparison of the outputs; the manual kerning is second.
!enter image description here | stackexchange-tex | {
"answer_score": 2,
"question_score": 4,
"tags": "fonts, kerning"
} |
Preceding question mark in Regex?
I am working on some Elixir coding challenge that requires Regex solution and encountered this following code:
defmodule Solution do
def remove(some_string)
String.replace(some_string, ~r/!(?!!*$)/, "")
end
end
Solution.remove("!Hi!!!") #=> "Hi!!!"
Solution.remove("Hi!") #=> "Hi!"
Solution.remove("Hi") #=> "Hi"
It removes exclamation mark that are not at the end.
My question is, I do not understand what `/!(?!!*$)/` line does. I believe this part of Regex is not Elixir-specific. I know that `!*$` means that zero or more `!` at the end of the String. What does the entire regex do in plain English?
Additionally:
What does `?!`... do? (I thought `?` means zero or more, but why is it before an exclamation mark?)
Why is there an exclamation mark before the parentheses `!(`...? | It's negative look-ahead. Maybe check out < which explains it all very nicely. It's also been covered on this site, of course, but I'd imagine searching for '?!' doesn't always yield results: Understanding negative lookahead
So in plain English it's "!" **not** followed by "!*$", where these characters mean exactly what you wrote above. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "regex, elixir"
} |
how can I reload an update panel onclient side using javascript?
I have a gridview button that I programmatically created and I want to load an update panel on the client side with the sent data. I have a hidden value field that gets its data on the click of the gridview button and the dropdownlist in my updatepanel depends on that value. | while calling `__doPostBack` directly will work, it's not a perfect solution because the name of that function is strictly speaking an implementation detail of the .Net framework.
A better solution is to use `ClientScriptManager.GetPostBackEventReference`, which gives you a more resilient interface to the same functionality. Do note that `GetPostBackEventReference` and `GetCallBackEventReference` are not the same thing - the former causes a page reload (partial or full, depending on how your UpdatePanels are set up), while the latter doesn't. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "asp.net, javascript, vb.net, visual studio 2008, updatepanel"
} |
Reemplazar las contrabarras de un recurso compartido
necesito retornar en una petición el path de un fichero, el problema es que me viene codificado con los escapes: _\\\servidor\directorio\subdir\fichero.pdf_ y necesito mostrarlo de forma normal _\servidor\directorio\subdir\fichero.pdf_ Lo que me pareció mas logico:
path.Replace(@"\\",@"\").Replace(@"\\\\",@"\\");
No funciona He probado también con `regex.Unscape(path)` pero no lleva bien el cuádruple slash y peta. ¿Me podéis echar un cable por favor? | string path = @"\\servidor\\\\directorio\subdir\fichero.pdf";
string pathFinal = "";
var pathList = path.Split('\\').Where(c => !string.IsNullOrWhiteSpace(c));
foreach (var p in pathList)
{
pathFinal += p + "\\";
}
pathFinal = pathFinal.Remove(pathFinal.Length - 1);
Utilizamos la **función Split** para separar la cadena por el delimitador **'\'** , esta función devuelve una lista donde cada elemento de la lista seria una palabra o token, posteriormente usamos el **método extensor Where** , para seleccionar de esa lista los tokens que no están vacíos.
Después recorreríamos la lista con un **foreach** y vamos concatenando cada token separado por el caracter **'\'**.
Posteriormente eliminaríamos el ultimo caracter de la nueva cadena generada. | stackexchange-es_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, string"
} |
Function literal with multiple implicit arguments
How to define function literal with multiple implicit arguments in Scala? I've tried this way:
def create = authAction { (implicit request, user) ⇒ // Syntax error
Ok(html.user.create(registrationForm))
}
but it throws compilation error. | As stated in previous answer, you can only define a single implicit parameter for a function literal, but there is workaround.
Instead of multiple implicit arguments you can write function literal as taking multiple argument lists with one argument each. Then it is possible to mark each argument as implicit. Rewriting original snippet:
def create = authAction { implicit request ⇒ implicit user ⇒
Ok(html.user.create(registrationForm))
}
You can call it from `authAction` as `f(request)(user)`.
`implicit` keyword duplication is annoying, but at least it works. | stackexchange-stackoverflow | {
"answer_score": 17,
"question_score": 9,
"tags": "function, scala, syntax, arguments, syntax error"
} |
Graph API post to wall limitation
Is there any limitation to post to the Facebook wall using Graph API? Because after posting four messages using the Graph API, the fifth message cannot be posted. However, the sixth message can be posted. All the six posts are within a 10-minute timeframe. | There is no rate limit on the API officially, but Facebook can choose to limit your posts for any number of reasons.
Also, Facebook will not let you post the same message twice. Even if it came from a source other than your application. So, you can't post the same update that the user posted directly or came in via Twitter, if they have that set to sync.
If you are getting a specific error I will update my answer with more direct information. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "facebook graph api"
} |
Strange behavior array in object JavaScript
Why b.first[0] return "t" and how I can avoid this?
I need safe "q" in b.first[0]
var extend = function(o,p){
for(prop in p){
o[prop] = p[prop];
}
return o;
};
var a = {first:['q','w']};
var b = {};
extend(b,a);
document.write(a.first[0]); //q
document.write(b.first[0]); //q
a.first[0] = 't';
document.write(a.first[0]); // t
document.write(b.first[0]); // t ????????????????????? | This is an issue relating to the concept that extending b by a doesn't recreate the data from a. If some of the data is an object (like an Array), it instead just "points" to that array instead of creating a new, identical array. Essentially you're storing two pointers to the same array, so when you change one, you change the other.
Here is a answer which discusses the idea of "cloning" an object in Javascript in more detail.
< | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "javascript"
} |
Android bytecode analysis for method parameters
I want to analyze the Android bytecode, and find all instructions that are relevant to the method parameters (kind of slicing on the parameters). Can anybody provide some references for this? Any help would be greatly appreciated! | The Dalvik bytecode is described in detail by this document:
<
Possibly also of interest:
<
(These used to live in the dalvik/docs directory in the source tree, but were "promoted".)
You can use the `dexdump` command with `-d` to generate an instruction disassembly of a DEX file and just process that. Or you can process the DEX file yourself. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "android, parameters, bytecode, dalvik, dex"
} |
find always returns "/mnt/hgfs protocol error" (VMware, Debian 8.x)
I'm using VMware to run Debian 8.x. Regardless of if something is found or not, the command
find / -type d -name [Directory Name]
keeps returning
find: '/mnt/hgfs': protocol error".
:
post = get_object_or_404(Post, slug=slug)
if request.POST:
form = CommentForm(request.POST)
# do comment form processing here
return render(request, "post/post_detail.html", {
"object": post, "comment_form": form})
Is there any clean way to do this using class based views? Or just some way to decouple post display code from comment processing code? | One option would be to use the DetailView for the Post and a templatetag to display the comment form. Have the comment form submit to a Comment CreateView that redirects to the DetailView on success.
That said, it might get a little ugly if the form is invalid. In a pinch you can always call a DetailView or its methods from one of the CreateView methods. But IMO that introduces more coupling rather than less. Or you could have a separate utility function that you can call from the CreateView to display the Post if the comment form has errors.
Another option would be to use AJAX to process the comment form (in the separate CreateView) instead of a new page load.
In the end, regardless of language or framework, there's going to be a limit to how much one can decouple a view that needs to display one object type and create another. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 6,
"tags": "python, django, django class based views, django generic views"
} |
Blank statement when IF condition is true
How do I write nothing in `if` part if the condition is true?
For example:
if(true)
// I want to keep this space blank or want compiler to do nothing here
else
break;
How do I do this? | Typically, this is written by negating the condition:
if (not true)
break; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -4,
"tags": "c"
} |
Html Input to apex:inputfield
currently in my visualforce page I have an html input:
<input class="tb1" data-val="true" data-val-length="First Name should be less than 50 characters." data-val-length-max="50" data-val-regex="First name can only contain alphabets, hyphen and apostrophe." data-val-regex-pattern="^[a-zA-Z '-]+$" data-val-required="First Name is Required" id="FirstName" maxlength="50" name="FirstName" style="width:285px;" type="text" value="" />
</td>
I want to change this to
<apex:inputfield value="{!c.FirstName}"
but I don't want to lose the attributes listed in the html input such as data limit, or type, etc. The apex:inputfield's attributes are limited, and the error message for the required validation isn't the way I want it to look.
Is there any way I can incorporate both of these together? Thanks | Visualforce now supports pass-through attributes so adding a `html-` prefix to each of your attributes should work:
<apex:inputfield value="{!c.FirstName}" html-data-val="true" html-data-val-length="First ... | stackexchange-salesforce | {
"answer_score": 3,
"question_score": 3,
"tags": "apex, visualforce, html"
} |
Mimic Haskell with Python
Haskell provides the feature something like f = f1 . f2
How can I mimic that with Python?
For example, if I have to do the 'map' operation two times, is there any way to do something like map . map in Python?
x = ['1','2','3']
x = map(int,x)
x = map(lambda i:i+1, x) | I think you are looking for function composition in Python.
You can do this:
f = lambda x: f1(f2(x)) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "python"
} |
convergence of $\prod_{m=2}^\infty \frac {1}{1-m^{-s}}$
Is the product $$\prod_{m=2}^\infty \frac {1}{1-m^{-s}}$$ convergent for all real $s>1$$\space$ ? | Let $P_s = \prod_{m=2}^\infty {1 \over 1 - m^{-s}}$. Then $$\ln P_s = -\sum_{m=2}^\infty \ln(1 - m^{-s}) = \sum_{m=2}^\infty \sum_{n=1}^\infty {m^{-ns} \over n} = \sum_{n=1}^\infty {1 \over n}(\zeta(ns) - 1)$$ where $\zeta$ is the Riemann zeta function. For $s>1$ the terms in this series are all finite. Furthermore, for sufficiently large $N$ and integer $k>1$, the $(k+N)$-th term is bounded above by ${1 \over k}(\zeta(k)-1)$, and $\sum_{k=2}^\infty {1 \over k}(\zeta(k)-1) = 1 - \gamma$ where $\gamma$ is the Euler-Mascheroni constant. Therefore if $s>1$ this series converges, so $P_s$ converges. | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "analysis, convergence divergence, infinite product"
} |
norm of operator in Hilbert space and complex conjugate Banach space
Let $E$ and $F$ be complex Banach spaces. We denote by $\overline{E}$ the compex conjugate of $E$, that is, the vector space $E$ with the same norm but with the conjugate multiplication by a complex scalar. The identity map defines a natural antilinear isomorphism $ x\to \overline{x}$ from $E$ onto $\overline{E}$. Recall that if $S\colon E\to F$ is a linear map we can define $\overline{S}\colon \overline{E} \to \overline{F}$ by $\overline{S}(\overline{x})=\overline{S(x)}$.
Let $H$ be a complex Hilbert space. Let $T\colon H \to E$ be a bounded linear map. Do we have $$ \vert\vert T \vert\vert_{H \rightarrow E}^2=\vert\vert T\overline{T^*}\colon \overline{E^*} \rightarrow E\vert\vert\ ? $$ where $T^*\colon E^* \to H^*$ is the adjoint map. | This is true even in operator space setting. See proposition 7.2 in Introduction to operator space theory. G. Pisier | stackexchange-math | {
"answer_score": 0,
"question_score": 1,
"tags": "reference request, functional analysis, banach spaces, operator theory, hilbert spaces"
} |
PHP: Trying to get property of non-object
I am working on a function, what returns whether a table exists or not.
But it always notices:
Notice: Trying to get property of non-object [...] on line 10
in
1 function table_exists($table) {
2
3 // get the database
4 global $mysqli;
5
6 // look for tables named $table
7 $result = $mysqli->query("SHOW TABLES LIKE $table");
8
9 // if the result has more than 0 rows
10 if($result->num_rows > 0) {
11 return true;
12 } else {
13 return false;
14 }
15 }
the $mysqli var is set like this:
$mysqli = new mysqli(mysqli_host, mysqli_user, mysqli_password, mysqli_database);
How to solve that? | I left out the quotes.
$result = $mysqli->query("SHOW TABLES LIKE \"$table\"");
or
$result = $mysqli->query("SHOW TABLES LIKE '$table'");
or
$result = $mysqli->query("SHOW TABLES LIKE \"" . $table . "\"");
or
$result = $mysqli->query("SHOW TABLES LIKE '" . $table . "'");
thanks for your help. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "php, mysqli, mysql num rows"
} |
Hudson jobs won't call javac?
I have just set up Hudson on my server. For some reason, my build will not call javac to compile my builds...? I have set the path to the JDK in the Manage Hudson area, and it seems to recognise it (doesn't give me a warning). Is there something else I'm supposed to do?
Here's a sample console output of one of my jobs (note how javac isn't called at all):
> Started by user admin
>
> Checking out svn+ssh://myhost.com/Project1
>
> A /src/Program.java
>
> A build.xml
>
> U
>
> At revision 119
>
> no change for svn+ssh://myhost.com/Project1 since the previous build
>
> Finished: SUCCESS | You need to set the ant-target for your build. Since this is a netbeans project you should have ant target like: compile, default etc?
One or more of these build target must be set in your job on hudson under the configuration menu. I think the field is called "Targets"
Some information on configuring ant in hudson: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "continuous integration, hudson, java, javac"
} |
Is it possible to keep the headers but remove the hyphens of a sql output using sqlcmd
**Objective:**
I was able to remove the hyphens when executing a sql query through sqlcmd using
|findstr /v /c:"---"
The issue however, is I can't combine the above code with my "-o" variable as such:
sqlcmd -S INSTANCENAME -s ";" -Q "SET NOCOUNT ON; SELECT top 5 * FROM table" |findstr /v /c:"---" -o output.csv
Error message:
> FINDSTR: Cannot open output.csv
**Note: I need to keep my headers.** | Well, the `findstr` command does not feature an option `-o` to create an output file. However, you can use output redirection to write the result into a file, like this:
sqlcmd -S INSTANCENAME -s ";" -Q "SET NOCOUNT ON; SELECT top 5 * FROM table" | findstr /V /C:"---" > "output.csv"
Regard that this will overwrite the file `output.csv` if it already exists without notice. To append to the output file rather than to overwrite it, just replace `>` by `>>`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, sql server, cmd, sqlcmd"
} |
Passing a javascript variable to PHP to use with Google Charts
I know, I know, one is client side and one is server side. I had to use PHP to grab a few arrays of data and I'm passing this data in to Google Charts geomaps. E.g:
echo 'var data = google.visualization.arrayToDataTable([
["Country", "Popularity"],
';
foreach($countries as $key=>$val){
echo '["'.$key.'",'.$val.'],';
}
echo ']);
When a user clicks on one of the countries (using an event listener) on the map it puts this value into a variable:
var country = data.getValue(selectedItem.row, 0);
Now I need to pass this to the PHP array, so I can do something like:
if($country == country){
//do whatever
} | To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var country = data.getValue(selectedItem.row, 0);
$.post('file.php', {country: country}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, php"
} |
How to return an int type representation for a list of objects
When outputting a list of objects how can you return an **int** type representation for the objects?
I've tried this:
class Passport(object):
def __init__(self, my_id):
self.id = my_id
def __repr__(self):
return int(self.id)
list_of_objects = [
Passport(19181),
Passport(29191),
Passport(39191)
]
if id in list_of_objects:
print("true")
Where list_of_objects is a list of `Passport` instances. But this gives an error `__repr__ returned non-string (type int)`.
I could solve this problem using a string for both, but I'm wondering if type int is possible? | `__repr__` is _required_ to return a **string** representation of the object. Returning a different type is not a valid implementation of `__repr__`.
If you want a way to return some number, then add a custom method that does that.
Btw., note that implementing `__repr__` is not a way to make `id in list_of_objects` work. For that to work, you should implement `__hash__` and `__eq__`. But at that point, you should really think about if you want `5 == Passport(5)` to be true; probably not. So you should change the way your check works by explicitely looking at the `id` property instead.
Instead of `if id in list_of_objects`, you could do the following:
if any(lambda x: x.id == id, list_of_objects):
print('true') | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "python"
} |
Can I use Autofac DI in a WebAPI messageHandler?
I successfully wired Autofac in my ASP.NET WebAPI project, and now I am wondering how to be able to resolve services in my MessageHandlers.
As MessageHandlers have to be added at application startup, it's clear that I won't be able to resolve them in a request lifetime scope. No problem here.
However, I would like to find a way to get the current request lifetime scope during the execution of the SendAsync method of the MessageHandler, in order to be able to (for instance) perform token verification, logging in a repository, etc...
How should I do that? | You can use the `GetDependencyScope()` extension method on the `HttpRequestMessage` which gives you an `IDependencyScope` from where you can resolve any service that you want in you handler:
public class MyHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
IMyService myservice =
(IMyService)request.GetDependencyScope().GetService(typeof(IMyService));
// Do my stuff with myservice
return base.SendAsync(request, cancellationToken);
}
} | stackexchange-stackoverflow | {
"answer_score": 22,
"question_score": 13,
"tags": "asp.net web api, autofac"
} |
Unity: event for level reload
I am using OnLevelWasLoaded but this event is getting fired on any level load, be it the same level reload or next level load. Is there any event which gets fired only when the level is reloaded, and not fired when the level is loaded?
If not, how can I achieve this in Unity? | Just check if the new buildindex is the same as the last scene buildindex. OnLevelWasLoaded already gives you the build index of the new scene loaded. You can save lastlevel in a static variable in some class and access it from there. For example "MyClass":
void OnLevelWasLoaded(int level){
if (level != MyClass.lastlevel) return;
MyClass.lastlevel = level;
//your other code
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#, unity3d"
} |
WP Create User - Preventing repeated information
I am using the
<?php wp_create_user( $username, $password, $email ); ?>
function in a contact form to create a subscriber when the user enters infomation on the contact form, thus in the background adding their email address to the database and giving them an account for site access.
Does this way of doing it though not mean that if a user sends 3 messages from the contact form they end up with 3 accounts with the same email address, or will it check to see if the email address or user name already exists.
Any ideas? | The function `wp_create_user` calls `wp_insert_user` which check to see if `$username` and `$email` already exists and if so it returns a new WP_Error so you wont have duplicate users in your database and it wont send the new user email more then once, but i'm not sure if that is the best way to do that. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, email"
} |
Where can I find a "Melty Cheese Wheel"?
I'm going to Switzerland (Geneva), also to Paris, and Amsterdam, there's some place where can I find a "Melty Cheese Wheel"?
 restaurants that serve it all year round, like this:
<
Plenty of raclette/fondue places in Paris as well, just Google for "raclette Paris". | stackexchange-travel | {
"answer_score": 7,
"question_score": 7,
"tags": "food and drink, paris, switzerland, amsterdam"
} |
Create List of child objects from list of parent object
I would like to create list of child objects from list of parent object. Like If i have list of bookingroom which has one member room then i would like to create list of room from it.
eg. code:
Dim BookingRoomList As List(Of BookingRoom) = New List(Of BookingRoom)
Dim RoomList As List(Of Room) = New List(Of Room)
BookingRoomList = BookingRooms.FillGrid()
For Each BookingRoomInfo As BookingRoom In BookingRoomList
RoomList.Add(BookingRoomInfo.RoomInfo)
Next
Is there any short cut method instead of iterating over for earch? | You can use Linq and the `AddRange` method:
RoomList.AddRange(BookingRoomList.Select(Function(room) room.RoomInfo))
Apart from that, you can shorten the declarations considerably: `Dim x As T = New T()` is equivalent to `Dim x As New T()` and you should generally prefer the latter.
Furthermore, your instantiation of `BookingRoomList` is completely redundant (a logical error) because you overwrite the value later on.
Finally, you can initialise the room list _directly_ in the constructor call, or alternatively you can omit the constructor call entirely – the Linq expression already returns a fully-fledged collection. Which leaves us with:
Dim BookingRoomList As List(Of BookingRoom) = BookingRooms.FillGrid()
Dim RoomList = BookingRoomList.Select(Function(room) room.RoomInfo)).ToList()
And that’s it. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "vb.net, list, collections"
} |
Spark Scala - How to construct Scala Map from nested JSON?
I've a nested json data with nested fields that I want to extract and construct a Scala Map.
Heres the sample JSON:
"nested_field": [
{
"airport": "sfo",
"score": 1.0
},
{
"airport": "phx",
"score": 1.0
},
{
"airport": "sjc",
"score": 1.0
}
]
I want to use saveToES() and construct a Scala Map to index the field into ES index with mapping as below:
"nested_field": {
"properties": {
"score": {
"type": "double"
},
"airport": {
"type": "keyword",
"ignore_above": 1024
}
}
}
The json file is read into the dataframe using spark.read.json("example.json"). Whats the right way to construct the Scala Map in this case?
Thanks for any help! | You can do it using the below sample code
import org.json4s.DefaultFormats
import org.json4s.jackson.JsonMethods.parse
case class AirPortScores(airport: String, score: Double)
case class JsonRulesHandler(airports: List[AirPortScores])
val jsonString: String = """{"airports":[{"airport":"sfo","score":1},{"airport":"phx","score":1},{"airport":"sjc","score":1}]}"""
def loadJsonString(JsonString: String): JsonRulesHandler = {
implicit val formats: DefaultFormats.type = org.json4s.DefaultFormats
parse(JsonString).extract[JsonRulesHandler]
}
val parsedJson: JsonRulesHandler = loadJsonString(jsonString)
parsedJson.airports.foreach(println)//you can select parsedJson.airport or scores
//below ouput
AirPortScores(sfo,1.0)
AirPortScores(phx,1.0)
AirPortScores(sjc,1.0) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "scala, apache spark, elasticsearch hadoop"
} |
Retrieve the key value from a arrayObject
This is my array:
ArrayObject::__set_state(
array( 'data' =>
array (
'key1' => '573779',
'key2' => 'REF12345',
'key3' => '2010-07-12',
'key4' => '0000-00-00',
'key5' => '2010-07-12',
'key6' => '21654',
'key7' => '0',
'key8' => ArrayObject::__set_state(array( )),
'key9' => ArrayObject::__set_state(array( )),
'key10' => array ( ),
'key11' => array ( ),
)
)
I'm interested in finding out out how to retrieve any of the values for a key using SPL. Any of the keys can have arrays within arrays so I'm unsure how to obtain a value. I thought I may be able to use `->offsetGet('')` but this only retrieves from the top-most array. | ArrayObject implements ArrayAccess so you can simply access them with the regular Array Notation, e.g.
echo $arrayObject['key1'];
In addition, ArrayObjects are IteratorAggregates, so you can iterate over them with `foreach` and decorate them with any of the SPL iterators, including the RecursiveIteratorIterator | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, arrays, spl"
} |
How to make the yuicompressor jar file a singleton, or globally accessible?
I'd like to put the yuicompressor jar file in a single folder so that I can call
`java -jar yuicompressor-2.4.2.jar ...`
from anywhere on my system, with cygwin. For bash files I use I simply put them in a common folder, and added the folder's path to my windows user's PATH environment variable and the bash commands were found in cygwin.
when I `echo $PATH` I see the folder I put the yuicompressor jar into listed in the $PATH..
But when I try `java -jar yuicompressor-x.y.z.jar myfile.js -o myfile-min.js` (for example) I get the following error message:
> Unable to access jarfile yuicompressor-2.4.2.jar
Even when I try providing an absolute path to the jarfile I get the same error message..
How can I do this? | The `PATH` environment variable is a list of directories the shell will search through in an attempt to run a command.
`java.exe` **will not** search the directories on the `PATH` environment variable to try and locate the archive you are attempting to run. So running `java -jar yuicompressor-2.4.2.jar` from any directory other than the one containing the archive would be expected to fail.
What is the full command you are attempting when providing an absolute path? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "windows, yui, cygwin, yui compressor"
} |
Issue in displaying toast message in android
According to my requirement in android, if the user presses only "space" and clicks "post" button a toast should be displayed. So i have the code as below, but the toast doesnt get displayed. please can anybody tell why it is not displaying ?
mEditText.addTextChangedListener(mTextEditorWatcher);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String result =mEditText.getText().toString();
if(result.contains ("\\s"))
Toast.makeText(getApplicationContext(), "Space ", Toast.LENGTH_LONG).show();
}
});
} | Looks like you are trying to use regex with `String.contains` method. `String.contains` method works with `String`. It doesn't work with `regex`.
See this question for more details: How to use regex in String.contains() method in Java
By the way, you should not check for just one space. You should handle any number of spaces.
if(result.length()!=0 && result.trim().equals(""))
ShowToast(); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, android, button, toast"
} |
Can't split a line in Java
I am facing a problem that I don't know correctly split this line. I only need `RandomAdresas0 100 2018 1`.
String line = Files.readAllLines(Paths.get(failas2)).get(userInp);
System.out.println(line);
arr = line.split("[\\s\\-\\.\\'\\?\\,\\_\\@]+");;
Content in line:
[Pastatas{pastatoAdresas='RandomAdresas0',pastatoAukstuSkaicius=100,pastatoPastatymoData=2018, pastatoButuKiekis=1}] | You can try this code (basically extracting a string between two delimiters):
String ss = "[Pastatas{pastatoAdresas='RandomAdresas0',pastatoAukstuSkaicius=100,pastatoPastatymoData=2018, pastatoButuKiekis=1}]";
Pattern pattern = Pattern.compile("=(.*?)[,}]");
Matcher matcher = pattern.matcher(ss);
while (matcher.find()) {
System.out.println(matcher.group(1).replace("'", ""));
}
This output:
RandomAdresas0
100
2018 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "java, regex"
} |
how to pass argument to child function in js
function checkSalary(baseSalary, bonus, tax) {
console.log(baseSalary, bonus, tax)
function salary(baseSalary, bonus) {
console.log(baseSalary, bonus)
return baseSalary + bonus;
}
function salary_with_tax(tax) {
console.log(tax)
return salary() - tax;
}
}
console.log(checkSalary(5000, 3000, 100))
I want to check using salary() and salary_with_tax() but don't know how to pass the arguments. | You must call your inner functions at some point. Something like this:
I had to make some assumptions about what you want. I returned an object with the results of each inner function.
function checkSalary(baseSalary, bonus, tax) {
console.log(baseSalary, bonus, tax)
function salary(baseSalary, bonus) {
console.log(baseSalary, bonus)
return baseSalary + bonus;
}
function salary_with_tax(tax) {
console.log(tax)
return salary(baseSalary, bonus) - tax;
}
return {
salary: salary(baseSalary, bonus),
tax: salary_with_tax(tax)
}
}
console.log(checkSalary(5000, 3000, 100)) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript"
} |
why I am getting Class not found exception
I am using `DeferredTextImpl` Class and eclipse does not seems to complain about it but when I run my project I get run time exception `.... Class not found exception for DeferredTextImpl ..`
When I searched for the class file, I found it in `rt.jar` which should certainly be on the class path. I also checked the build path in project `properties->Java build path` and could see JRE System Library at the very bottom. when I expanded that. I could see `rt.jar`. which means it is on the class path, right ?
Why am I getting this error ? | Check the version of your Xerces jar for your runtime versus you compile time classes. Make sure have a Xerces2 jar at runtime. I doubt the the class in the rt.jar is the same class your application is looking for. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, classpath, classnotfoundexception"
} |
Summing up amounts if one row contains a key within another sheet
I have two sheets in one LibreOffice Calc document:
_Sheet1_ :
| Key | Amount |
|-----|---------|
| ABC | 1 |
| DEF | 2 |
| GHI | 3 |
_Sheet2_ :
| Keys |
|-------|
| ABC |
| XYZ |
| JKL |
| GHI |
Now I'd like to add the amounts in the rows of Sheet1 but _only_ where the key is contained anywhere in Sheet2. For the example above, the sum would be `4` (keys `ABC` with amount `1` and `GHI` with amount `3`).
I've been solving this with an "Advanced Filter" and `SUBTOTAL` but I'd really like a solution where I don't have to re-apply the filter when the sheets change. Any help would be greatly appreciated! | One approach would be to combine SUMPRODUCT with COUNTIF. I copied your example.
Sheet2:
*$B$2:$B$4)
SUMPRODUCT does an array-style calculation on the result of COUNTIF for each row on Sheet1 multiplied by the amount in column B. Assuming the keys on Sheet2 don't contain duplicates, the count will be `1` if Sheet2 contains the key, or `0` if not.
I recommend using explicit ranges rather than simple column references (i.e., A:A). You can pad the explicit ranges with blank rows to allow for any potential expansion you might need, and the formula will still work. However, it takes Calc forever to evaluate entire columns. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "libreoffice calc"
} |
How do i simplify css with multiple id's
i'm trying to clean this CSS up a bit, since i want to apply the same style to it but it's messy. is it possible to simplify this?
#collection.shop-gioventu-new-york .container .twelve.columns,
#index .container .twelve.columns,
#index-v2 .container .twelve.columns
{
width: 100% !important;
} | .fullWidth {width:100% !important}
In your html add the class="fullWidth" class to anything that needs this style.
<div id="collection" class="shop-gioventu-new-york container twelve columns fullWidth">...</div>
<div id="index" class="container twelve columns fullWidth">...</div>
<div id="index-v2" class="container twelve columns fullWidth">...</div>
'cleaning up' your css involves balancing between adding too many classes in your html or adding too many selectors in your css. You'll have to decide in this case what makes the most sense for your application. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -1,
"tags": "css"
} |
Is there any way to include only the part of JS library which require in a page?
I want to load only those JavaScript code which is necessary in a page.
If suppose one of my page require just `.click` event then why do I include whole jQuery file?
Is there any way to include only the part of JS library which require in a page? | You can build your own jQuery from source by using `grunt custom` and removing the modules you don't want.
For example, to build jQuery without the `css` module (and all those that depend on it), you could build using:
grunt custom:-css
If we wanted to get even more minimal, we could remove more modules:
grunt custom:-ajax,-css,-deprecated,-dimensions,-effects,-event/alias,-offset,-wrap | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "javascript, optimization"
} |
Ejecting from Expo
I have to eject from expo in my react native project, but I still want to maintain some functionalities provided by their libraries, like notifications. Is it possible?
Thanks in advance! | Starting with **SDK33 Expo** was changed to install its own modules separately as required. If you have installed and used the `notification` module using `expo install`, you can use it normally even with an `eject`.
Check whether a module is available on `MainApplication.java` for Android or `info.list` for ios. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "expo"
} |
Thesis statements or theses statements?
I am doing research for three different questions and I am going to present one single thesis statement for each question. Would I refer to all three statements as 'thesis statements' or as 'theses statements'?
Intuitively, I would choose the latter as both the total number of statements and questions are plural. Which one is correct though? | According to this site (< it's 'thesis statements' (plural only for statement). I think this link from Indiana University is more reliable: < Just look for 'thesis statements' at the pages. | stackexchange-english | {
"answer_score": 0,
"question_score": 1,
"tags": "word choice"
} |
Using this.added in Meteor
I'm trying to transform a publication, and this is my code:
Meteor.publish('appointments.waiting', function () {
var self = this,
count = 0;
Appointments.find().forEach(function (appointment) {
var patients = Patients.find({_id: appointment.patient_id}).fetch();
var first_name = patients[count].profile.first_name,
middle_name = patients[count].profile.middle_name,
surname = patients[count].profile.surname,
name = surname + ', ' + first_name + ' ' + middle_name;
self.added('appointments', appointment.names, name);
});
self.ready();
});
When I `console.log(name)`, I can see the name in full but I'm not quite sure how to use `this.added` to add the new data. How do I go about this? And if I do enter this new data, will it overwrite the older data?
If there's a better way to achieve this, I'd also like to know. | I believe what your code will do is to publish one, static set of appointments, and that should work. It cannot overwrite anything because it is creating something new (a new publication).
So as such I don't see anything wrong with your code. But if you are after a reactive publication that changes then `Appointments` changes, then you will need to use `observe` or `observeChanges` instead of `.forEach` \-- and then also start using `this.changed`, rather than only added (unless things never change), and `this.removed`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "meteor, meteor publications"
} |
transistor characteristics - Ube0 number meaning
i'm trying to guess meaning of value marked as Ube0 in datasheets. (datasheet adress: < the transistor I want to use is Tesla KF-508). I want to regulate secondary circuit by voltage divider on base. Does this value means that max allowed voltage on base is 7 volts and I must design voltage divider to not allow more than 7 volts and current no more than 2.2 mA ?? (computed from measured parameter h21e = 233, max current that I want trought collector = 0.5 A) | UBEO is the base to emitter voltage with unconnected or "open" collector terminal.
A bipolar junction transistor has three terminals, **b** ase, **c** ollector and **e** mitter. Whichever terminal is not connected for the rating is replaced with **o** pen when left unconnected. Hence similar identifiers for UCBO, UCEO.
UEBO = -UBEO = 7V means that the emitter voltage referenced to the base voltage can be 7V maximum. Often there is a "max" squeezed (UEBO,max) in to indicate it is a maximum rating.
If you exceed that voltage the base to emitter diode will break down (avalanche). When carefully used this mode of operation can be used as a white noise generator, when uncareful the transistor will be destroyed. | stackexchange-electronics | {
"answer_score": 2,
"question_score": 1,
"tags": "transistors, datasheet, voltage divider, maximum ratings"
} |
How to run redis keys commands on RDB file?
is it possible to run redis's `keys` comannd directly on rdb dump?
keys "locations*" /path/to/dump.rdb
If its not natively supported. Wondering if any third-party tool supports this feature? | To analyze and manipulate the contents of a Redis RDB file you should look into the extremely useful redis-rdb-tools. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "redis, nosql"
} |
Sistema para ler código de barras pelo celular em PHP, está funcionando. mas queria saber Como usar o $_GET Somente quando o usuário fizer a leitura
** , onde verifica se a variável foi iniciada.
Seu código ficaria algo como:
<?=isset($_GET['codigo']) ? $_GET['codigo'] : '';?>
Sendo false, não retorna um Warning. | stackexchange-pt_stackoverflow | {
"answer_score": -1,
"question_score": -2,
"tags": "php"
} |
Why is this authentication procedure using Rabin crypto not useful?
A friend asked me the following, pointing out that the method is not very useful (my problem is I do not see why it is not good):
* Consider a person A which chooses $n$ as the public key for the Rabin crypto-system.
* We want to be sure that we are communicating with person A so we send her a random item $r\equiv m^2 \mod n$.
* Person A receives $r$ and decodes it using the factorization of $n$ and finds a square rot $m_1$ of $r$.
* A then sends us $m_1$ and we check $r\equiv m_1^2 \mod n$.
Why is this not useful? | A is acting as a square-root oracle in that protocol. We can use that oracle to factor $n$ and break the scheme.
Suppose you are an attacker that wants to impersonate A. You:
* Pick a random $m$;
* Send $m^2$ to A;
* Compute $p = \gcd(m_1 - m, n)$, thus factoring $n$.
This works with probability $1/2$ for each attempt. | stackexchange-crypto | {
"answer_score": 9,
"question_score": 7,
"tags": "authentication, authenticated encryption, rabin cryptosystem"
} |
Looping over two arrays in javascript simultaneously
let masterList=[{id:1,name:'Abc'},{id:2,name:'Def'},{id:3,name:'Ghi'}];
let selectedList=[2,3];
The desired result is to have
//desiredList=[{id:2,name:'Def'},{id:3,name:'Ghi'}]
Currently what I am doing is
let parsedArray = [];
masterList.forEach(mItem => {
selectedList.forEach(sItem => {
if (mItem.id === sItem) {
parsedArray.push(mItem);
}
});
});
desiredList=parsedArray
I do not find this method efficient when iterating over large arrays, is there any logic, any inbuilt javascript operators using which I can achieve the same? | Turn the first array into an object indexed by `id` first, so you can look up the appropriate matching object in `O(1)` time, and then you can `.map` the `selectedList`:
const masterList=[{id:1,name:'Abc'},{id:2,name:'Def'},{id:3,name:'Ghi'}];
const selectedList=[2,3];
const masterById = masterList.reduce((a, obj) => {
a[obj.id] = obj;
return a;
}, {});
const desiredList = selectedList.map(id => masterById[id]);
console.log(desiredList); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, arrays, foreach"
} |
Variable length arguments c#
This is probably not possible, but here goes:
I want to create a struct where I can define the amount of arguments at declaration.
for example, now I am using:
KeyValuePair<T, T>
but KeyValuePair can only ever take a Key , and a Value .
Is it possible to make something like:
CustomValues<T, {T, {..}}>
I think this isn't possible, but maybe I just don't know enough C#. I'm also open to clever workarounds,
Thank you | No, this isn't possible, as showcased by `Func<T>`, `Func<T, TResult>`, `Func<T1, T2, TResult>`, etc. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 5,
"tags": "c#, generics"
} |
How to customise Google+ Log In button
I'm including FB and G+ SignUp in my app.
Only thing that I can't find an answer for is **how to customise GPPSignInButton**.
I made a regular UIButton and changed it's Class to GPPSignInButton.
Result was this:
!enter image description here
I have no idea what this blue area is, and how it ended up there, but I cannot change it by calling any of these methods
_gButton.backgroundColor = [UIColor redColor];
[_gButton setBackgroundColor:[UIColor redColor]];
[_gButton setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
I just need a google login button to be transparent button. How to achieve that? | You can have your own `UIButton`, connect it with an `IBAction` to your `UIViewController` and run the authentication process yourself, that's what the Sign in button does behind the scenes:
- (IBAction)signInWithGooglePlusButtonPressed:(UIButton *)sender {
GPPSignIn *googleSignIn = [GPPSignIn sharedInstance];
googleSignIn.shouldFetchGooglePlusUser = YES;
googleSignIn.shouldFetchGoogleUserEmail = YES;
googleSignIn.clientID = @"CLIENT_ID";
googleSignIn.scopes = @[ @"profile" ];
googleSignIn.delegate = self;
[googleSignIn authenticate];
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "ios, button, google plus"
} |
copy and paste files within android
so Im trying to make a file manager android app that allows me to copy and paste selected files. I found a useful method for doing this online but it doesnt seem to work for me. If you could offer any suggestions on how I can fix my problem that would be great, thank you
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} | There is nothing wrong with your function, it will simply copy a file (or rename it) from location to another.
Referring to the error you are getting `(is a directory)`, I believe you are specifing the wrong parameter in the destination, it has to be a filename **not** a directory
So to use this function correctly you can do something like:
copy(new File("Director1","filename"), new File("Directory2","filename"));
Or you can use it to `rename` a file (not efficient solution), e.g.
copy(new File("Director1","filename"), new File("Directory1","new_filename")); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, android"
} |
How to see pip package sizes installed?
I'm not sure this is possible. Google does not seem to have any answers.
Running Linux Debian can I list all pip packages and size (amount of disk space used) thats installed?
i.e. List all `pip` packages with size on disk? | Go to the package site to find the size e.g. <
Then expand `releases`, find the version, and look up the `size` (in bytes). | stackexchange-stackoverflow | {
"answer_score": 19,
"question_score": 58,
"tags": "python, linux, debian, pip"
} |
XML Parsing Error: no element found Location: http://localhost/Test/TestService.asmx Line Number 1, Column 1:
I created a Web service in VS 2008 and hosted it in IIS but when trying to oprn it in brwoser it throws this error.
Any help will be appreciated.
Thanx | 1. Don't open it in a browser. Write a unit test to call the service. How the service behaves in the browser may not be how it behaves in real life.
2. Use Fiddler to watch the network traffic. You'll see interesting things.
3. I bet the reason you've got an XML parsing error is that XML isn't what's being returned from the server. I bet you've got text or HTML telling you there's been an error in your web service. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "visual studio 2008, web services, asmx"
} |
Modify namespace of importing script in Python
I'd like a function in my module to be able to access and change the local namespace of the script that's importing it. This would enable functions like this:
>>> import foo
>>> foo.set_a_to_three()
>>> a
3
>>>
Is this possible in Python? | An answer was generously provided by @omz in a Slack team:
import inspect
def set_a_to_three():
f = inspect.currentframe().f_back
f.f_globals['a'] = 3
This provides the advantage over the `__main__` solution that it works in multiple levels of imports, for example if `a` imports `b` which imports my module, `foo`, `foo` can modify `b`'s globals, not just `a`'s (I think)
However, if I understand correctly, modifying the local namespace is more complicated. As someone else pointed out:
> It breaks when you call that function from within another function. Then the next namespace up the stack is a fake dict of locals, which you cannot write to. Well, you can, but writes are ignored.
If there's a more reliable solution, that'd be greatly appreciated. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 6,
"tags": "python, namespaces, python import, python module"
} |
Moshi : converting JSON to Java object when the class has a List<Object> field
Let's say I have something like this:
public class Container implements Serializable {
private List<Object> elements;
[... some other fields ...]
}
public class A implements Serializable {
...
}
public class B implements Serializable {
...
}
public class C implements Serializable {
...
}
Where the `List<Object> elements` contains objects of type `A`, `B` or `C`
I use Moshi to convert it to JSON (and it works perfectly) and convert it back to Java. The conversion back to Java doesn't work.
It seems the `List<Object> elements` cannot be converted back, and all elements of the list are converted to `LinkedHashTreeMap` objects.
What would be the best way to solve this? (if there is a way!)
Thank you. | The answer from Jesse Wilson works perfectly:
public class Container implements Serializable {
private List<Item> elements;
[... some other fields ...]
}
public abstract class Item implements Serializable {}
public class A extends Item {
...
}
public class B extends Item {
...
}
public class C extends Item {
...
}
...
Moshi moshi = new Moshi.Builder()
.add(PolymorphicJsonAdapterFactory.of(Item.class, "item_type")
.withSubtype(A.class, "a")
.withSubtype(B.class, "b")
.withSubtype(C.class, "c"))
.build();
containerAdapter = moshi.adapter(Container.class); | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "java, android, json, moshi"
} |
How sort this array of items by date in desc order (I used loadash sortBy but it returns oldest first while I need newest first)?
How can I sort this array of objects with dates using desc order?
I tried loadsh sortBy
if ( sort && sort == "new") {
items = _.sortBy(items, (dateObj) => {
return new Date(dateObj.pubDate);
});
}
But it returns oldest items first while I need newest first. How can be it fixed? | Since your are already using lodash, the solution is simple and involve just a minimal modification to your current code:
items = _.orderBy(items, (dateObj) => {
return new Date(dateObj.pubDate);
}, 'desc');
lodash orderBy is very similar to `sortBy` with the addition of a third parameter, which specify the sort order (asc or desc), and the difference that the 'iteratee' could also be 'iteratees', by specifying an array of properties to sort by, in which case the sort order could also be an array with corresponding order strings for each property. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, arrays, ecmascript 6, lodash, ecmascript 5"
} |
Oracle get old and new value from audit table
Say I have an audit table structure kind of like this (simplified).
OID,VALUE,CHANGED_DATE
and what I would like to do is write a query that, for each VALUE change, gives me the following output.
OLD_VALUE,NEW_VALUE,CHANGED_DATE
How would I go about doing that? So, for example, if I had
OID|VALUE|CHANGED_DATE
----------------------
1 |ABC |15-JAN-18
2 |DEF |22-JUN-18
3 |XYZ |16-JUL-18
I would like to see output like:
OLD_VALUE|NEW_VALUE|CHANGED_DATE
--------------------------------
ABC |DEF |22-JUN-18
DEF |XYZ |16-JUL-18 | Use `lag()`:
select oid, lag(oid) over (order by changed_date) as prev_oid, changed_date
from t;
This code includes all three rows. If you want to eliminate the first:
select *
from (select oid, lag(oid) over (order by changed_date) as prev_oid, changed_date
from t
) t
where prev_oid is not null; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "sql, oracle"
} |
mongo convert or $rename, $set, $unset a lat lon into 2dsphere Point coordinates array
is there any $rename o $set $unset sequence to convert a subdocument
"loc" : {"lon" : x.0 , "lat" : y.0 }
into a 2dsphere "compliant" subdocument that includes the type and coordinates in an array
"loc: " {"type": "Point", "coordinates" [ x.0, y.0]
using only the mongo shell. (aka without writing an external script) | There is no way to currently `update` a field by manipulating the existing value of that field, but you can do the following:
db.collection.find().forEach(function(doc){
var location = {"type":"Point","coordinates":[doc.loc.lon,doc.loc.lat]};
db.collection.update({"_id":doc._id},{$set:{"loc":location}});
})
Basically, if we want to `update` a field with a new value that is `derived` from it's old value, we need to get hold of that old value first, then `modify` it and `update` the field with the new value. `MongoDB` query framework **limits** us from doing these operations in a single query. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "mongodb, mongodb query"
} |
One google account, multiple chrome users
I have a couple of websites, each has a twitter account, disqus account, special bookmarks... managing both of them was annoying, I had to logout, login again with the other account...
I created a new user for siteB, but I haven't logged in with my gmail account as this will take me back to the first problem, not being able to sign in to twitter for example using 2 accounts at the same time.
I still need to sync bookmarks and settings of UserA and UserB on different computers, without mixing A and B together.
How can that be done?
Thank you. | A better, more stable and faster solution is: Installing a password extension (passwordbox in my case) each time you want to open a site that you have multiple accounts for, open a new incognito tab, open the site, and click on the account you want to use to login. | stackexchange-superuser | {
"answer_score": 1,
"question_score": 1,
"tags": "google chrome, multiple users"
} |
Fill hash with checkboxlist (key) and dropdown (value) doesn't work? In ruby on rails
I am implementing a checkboxlist with some items and next to each item there is a dropdown. These two things hang together and what i want to do is to create a hash, the key is the value or id from the checked item, the value is the value of the selected item in the dropdown.
This is what i have: view:
<% @groups.each do |group| %>
<li>
<%= check_box_tag 'group[]', group.id -%>
<%= h group -%>
<%= select_tag 'role_group[group.id][]', options_for_select(@roles) %>
</li>
<% end %>
controller:
@selected_groups = Group.find(params[:group])
@selected_roles = params[:role_group]
@roleskeys = @selected_roles.keys
Now if i show @roleskeys , he always just say group.id. So this is not correct, this is just the string. Somebody who knows what i am doing wrong? | Try it this way:
<% @groups.each do |group| %>
<li>
<%= check_box_tag 'group[][id]', group.id -%>
<%= h group -%>
<%= select_tag 'group[][group_id]', options_for_select(@roles) %>
</li>
<% end %>
You will have both together in a Hash. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails, ruby, hash"
} |
if df_2 is a subset of df_1 - how to remove df_2 values from df_1?
I have a dataframe, `df_2` which is a subset of `df_1`:
df_2 <- df_1[ lots_of_conditions, ]
I would now like to create a new dataframe `df_3` which is `df_1` with all the `df_2` records removed.
df_3 <- ???
**Question** : how is this done in R? | To develop what I was saying in my comments, you can create `df_3` with the exact same information you use to create `df_2` :
Let's say your conditions for `df_2` are as follows :
lots_of_conditions <- cond1 & cond2 & (cond3 | cond4)
So, you do `df_2 <- df_1[ lots_of_conditions, ]` to get `df_2` and you can just do
df_3 <- df_1[!lots_of_conditions, ]
to get df_3.
Doing this, you just negate the conditions used to create df_2 without the trouble of explicitly negate them (changing `|` in `&` etc. ). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "r"
} |
Use Django ORM to select rows if a value is in a range stored in columns
I apologize for the phrasing, I'm just not sure how to express this idea. It might make more sense if you have a look at my query:
SELECT * FROM geoip_table
WHERE inet '68.180.194.242' BETWEEN start_ip AND end_ip
LIMIT 1;
I'm using a GeoIP database that has ip ranges stored in the columns `start_ip` and `end_ip`. The above query works and is quite performant, I'm just interested to know if it is possible to write an equivalent query using Django's ORM. | I'd suggest reverting the logic of the "WHERE" clause. Provided that you have a suitable IP field, a query may look like this:
GeoIP.objects.filter(start_ip__lte='68.180.194.242', end_ip__gte='68.180.194.242')
For other similar cases, when this "reverting" is not possible, Django provides F objects (see here for examples of usage in queries) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, django, postgresql"
} |
Content Filter based on Heirarchical Taxonomies
I have one taxonomy named "Project Parameters" with hierarchical select and another taxonomy names "Project Sub Parameters" with hierarchical select.
I Want to filter the content with those taxonomies like on selection of Project parameter display its sub parameters and click on sub parameters with ajax call i need content filter
I Had created view and with contextual filter i achieve that but that load the page. I want to do same functionality with ajax only, No page reload.
Is it Possible? Please Help Me.. I am stuck since last 2 days. | Create views for
* Project parameters
* Project sub parameters with contexual filter of project parameter taxonomy id with filter criteria
* Content view with contexual filter of project sub parameters taxonomy id.
After Create these views you can call ajax api and pass those conexutal filter on ajax for particular view like,
$view = views_get_view('viewname'); //viewname is the view machine name
$view->set_display("block_1"); //block_1 is the view display name
$view->set_arguments($tid); //$tid is the argument to pass
$view->pre_execute();
$view->execute();
$content = $view->render();
I got the success by this way.
Hope this answer help somebody. | stackexchange-drupal | {
"answer_score": 0,
"question_score": 1,
"tags": "ajax, nodes, views"
} |
Realizar una query que devuelva todas las filas de una fecha en concreto y todas las traducciones relacionadas en una misma fila
Estoy teniendo problemas para poder obtener lo que quiero. Me explico:
Tengo las dos siguientes tablas con una relación 1:n
**Tabla blog:**
 = '2010-11-12';
* * *
Pero este código da como resultado:

FROM blogs b
INNER JOIN blog_translations bt ON b.id = bt.blog_id
WHERE DATE(b.created_at) = '2010-11-12'
GROUP BY b.id, b.category;
No hace falta la subconsulta en la query de @"Edgar Vazquez":
SELECT b.id, b.Category,
max(case when bt.language = 'es' then bt.title end) title_es,
max(case when bt.language = 'en' then bt.title end) title_en,
max(case when bt.language = 'ca' then bt.title end) title_ca
FROM blogs b
INNER JOIN blog_translations bt ON b.id = bt.blog_id
WHERE DATE(b.created_at) = '2010-11-12'
GROUP BY b.id, b.category;
El único inconveniente es que si agregás un idioma tendrás que agregar una linea mas al SELECT, pero no se me ocurre una solución mejor. | stackexchange-es_stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "mysql, sql"
} |
Is there a way to make GDB print something to tell me that a line has been executed, without stopping?
I'm debugging multi-threaded code and I would just like to know if a line has been reached without it stopping but I don't want to start adding print statements everywhere.
Is this possible? Thanks! | You can attach commands to a breakpoint in gdb with the 'commands' command. One of those commands can be 'continue'. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "c++, multithreading, gdb"
} |
How to get value from span, but no child elements inside of it
I am trying to get only one value from my spans. This is how my code looks like:
HTML:
<span id="box1">
value1
<span class="box2">value2</span>
<span class="box3">value3</span>
</span>
jQuery:
var str = $('#box1').text();
alert(str);
This returns:
value1
value2
value3
How can I get "value1"? | You can do this :
var text = $('#box1').clone().children().remove().end().text(); | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "jquery, html"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.