source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0048479902.txt"
] | Q:
How to upload images from internal storage to server using Retrofit?
I'm trying to upload two images from internal storage of my android device to HTTP-server.
public interface ApiService {
...
@Multipart
@Headers("Content-Type: application/json")
@POST("signature/{id}")
Call<String> sendSignature(
@Header("Authorization") String authorization,
@Path("id") String id,
@Part("descrtipion") RequestBody description,
@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2);
}
...
private void sendSignatures(){
RequestBody description = RequestBody.create(okhttp3.MultipartBody.FORM, getString(R.string.str_file_description));
File file2 = getFileStreamPath(SIGNATURE2_PATH);
RequestBody requestFile2 = RequestBody.create(MediaType.parse("image/png"), file2);
MultipartBody.Part body2 = MultipartBody.Part.createFormData("sign1", file2.getName(), requestFile2);
File file = getFileStreamPath(SIGNATURE_PATH);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("sign2", file.getName(), requestFile);
Call<String> call = ApiFactory.getService().sendSignature(token, PARAMETER_ID, description, body2, body);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) Log.d("myLogs", "Yes: " + response.body());
else Toast.makeText(MainActivity.this, ErrorUtils.errorMessage(response), Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(MainActivity.this, t.toString(), Toast.LENGTH_LONG).show();
}
});
}
But server returns error #500. At the same time request from Postman is successful (#200).
Please, help me to fix it: where do I make a mistake in java-code?
A:
I have found the solution. Particularly in this case it was necessary to remove header:
public interface ApiService {
...
@Multipart
@POST("signature/{id}")
Call<String> sendSignature(
@Header("Authorization") String authorization,
@Path("id") String id,
@Part("descrtipion") RequestBody description,
@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2);
}
When I tried to send this request through Postman and put only one file, or two files, one or both with wrong keys, even if token was incorrect, server passed #500 error. So first of all they check keys and files, and then - authorization parameter. I removed header and in this case got successful responce.
|
[
"stackoverflow",
"0026225954.txt"
] | Q:
Undefined function 'num2str' for input arguments of type 'double'
I'm trying to use num2str in a load function as follows
route=3;
samples=1;
pct=100;
path('C:\')
load(['B2A_Sample_r',num2str(route),'_',num2str(pct),'%_',num2str(1000+samples)])
I also tried:
filename=char(['B2A_Sample_r',num2str(route),'_',num2str(pct),'%_',num2str(1000+samples)]);
load(filename,'-mat')
I'm having to shut down and reboot matlab every time I get this error.
A:
You are clearing your path each time you run, so MATLAB can't find any files or functions, whether built-in or not (including num2str). Each time it tries, it only looks in C:\ and then gives up. Try this:
route=3;
samples=1;
pct=100;
filename=char(['B2A_Sample_r',num2str(route),'_',num2str(pct),'%_',num2str(1000+samples)]);
directory = 'C:\';
fullfilename = fullfile(directory,filename);
load(fullfilename);
|
[
"stackoverflow",
"0061484654.txt"
] | Q:
Filter a list of objects based on a property existing in another list
I've got a class named Container that includes an int property named Id.
I've got a list of objects List<Container> named containers.
I've got a list of numbers List<int> named containerIds.
How can I get a subset of containers where the Id is in containerIds?
Something like the following:
var result = containers.Where(x => x.Id IN containerIds);
A:
You might use Contains method for that
var result = containers.Where(x => containerIds.Contains(x.Id));
Another option is to use Any Linq method
var result = containers.Where(x => containerIds.Any(i => i == x.Id));
|
[
"askubuntu",
"0000706657.txt"
] | Q:
LAMP server couldn't be installed using tasksel
I tried to install LAMP server using tasksel.
But it shows the following error message.
I tried changing permissions using chmod but in vain
debconf: DbDriver "passwords" warning: could not open /var/cache/debconf/passwords.dat: Permission denied
debconf: DbDriver "config": could not write /var/cache/debconf/config.dat-new: Permission denied
tasksel: debconf failed to run
How can it be resolved?
A:
Each system-wide installation needs root-rights. Run
sudo tasksel
and make your choice or run
sudo tasksel install lamp-server
to install LAMP.
|
[
"stackoverflow",
"0030063215.txt"
] | Q:
How to substitute values from one data.frame by values of another one?
I have two data.frames - first one is coded:
correlations <- data.frame(var1 = c('a','a','a','b','e'), var2 = c('b','c','d','e','c'), r = runif(5,0.5,1))
correlations
var1 var2 r
a b 0.6702400
a c 0.7301086
a d 0.5727880
b e 0.5916388
e c 0.5510549
and second one contains key for that codes:
D <- data.frame(code = letters[1:5],name=c('setosa','bulbifer','rubra','minor','nigra'))
D
code name
a setosa
b bulbifer
c rubra
d minor
e nigra
I need to recode the first data set D by the variables code and name within the second data.frame.
Result:
var1 var2 r
setosa bulbifer 0.6702400
setosa rubra 0.7301086
setosa minor 0.5727880
bulbifer nigra 0.5916388
nigra rubra 0.5510549
I have no idea how to achieve this (I need some function like merge, substitute, Map or others, but nothing suits to this).
A:
Try this with the library dplyr
library(dplyr)
D <- left_join(correlations, D, by=c("var1" ="code")) %>%
left_join(D, by=c("var2" ="code")) %>% select(name.x, name.y, r) %>%
rename(var1=name.x, var2=name.x)
The logic is: join twice with correlations one on the var1 and then on var2. Then drop the old var1 and var2 then rename the new vars.
|
[
"stackoverflow",
"0038248293.txt"
] | Q:
Struct can be declared within method body, but only if it doesn't contain member field initializers. Compiler bug or not?
It took me a good hour to locate this issue. The following code
class Test {
public:
void method();
int _member;
};
void Test::method()
{
struct S {
int s = 0; // same with int s {0};
};
_member;
}
int main(int argc, const char* argv [])
{
return 0;
}
Produces a compilation error:
1>error C2327: 'Test::_member' : is not a type name, static, or
enumerator
1>error C2065: '_member' : undeclared identifier
And the error goes away as soon as I replace int s = 0; with int s;.
This only occurs in MSVC 2013, not 2015. I'm pretty sure it's a compiler bug but I want to make sure it's not some C++ peculiarity that I'm not familiar with (something that changed between C++11 and C++14).
A:
[C++11: 12.6.2] defines NSDMIs in C++11, and neither this section nor any other section in the document defines such a constraint on the syntax. Therefore, it must be an implementation bug.
And, since GCC, Clang and Visual Studio 2015 all accept the code, I don't think any more detailed investigation is worthwhile.
|
[
"stackoverflow",
"0037433760.txt"
] | Q:
How to position SVG with CSS?
I am trying to create a button with an icon, cartcount and button text.
Now I already tried to make.
.buttonCart {
padding: 2px 20px;
border-radius: 6px;
border: none;
display: inline-block;
color: #fff;
text-decoration: none;
background-color: #28a8e0;
height: 30px;
/*float: right;*/
white-space: nowrap;
}
.cartCornerIcon {
display: inline-block;
padding-top: 0;
background-size: contain;
vertical-align: middle;
}
.cartCornerText {
display: inline-block;
}
<a href="#" class="cartLinkClass" id="basketLinkId">
<div class="buttonCart">
<div class="cartCornerIcon">
<svg xmlns="http://www.w3.org/2000/svg" width="50px" height="50px" viewBox="0 0 1.09448819 900.3622047">
<path d="M112.58 327.79v-32h90.468l112.015 256h245.5v32H294.126l-112.016-256M400.563 663.79c0 26.5-21.5 48-48 48s-48-21.5-48-48 21.5-48 48-48 48 21.5 48 48zM560.563 663.79c0 26.5-21.5 48-48 48s-48-21.5-48-48 21.5-48 48-48 48 21.5 48 48z" />
</svg>
<div id="itemCountForCart">
0
</div>
</div>
<div class="cartCornerText">
Bestellen
</div>
</div>
</a>
But what I actually want is this:
Anyone here who can help and maybe also can give some tips?
A:
you can use position:absolute in your SVG and some text-indent in your #itemCountForCart
.buttonCart {
padding: 2px 40px;
border-radius: 6px;
border: none;
display: inline-block;
color: #fff;
text-decoration: none;
background-color: #28a8e0;
height: 30px;
/*float: right; - removed for demo */
white-space: nowrap;
position: relative;
}
/*cart in corner top start*/
.cartCornerIcon {
display: inline-block;
vertical-align: top;
}
.cartCornerText {
display: inline-block;
margin-top:8px
}
svg {
position: absolute;
width: 100px;
height: 50px;
left: -42px;
top: -8px;
}
#itemCountForCart {
text-indent:-.8em
}
<a href="#" class="cartLinkClass" id="basketLinkId">
<div class="buttonCart">
<div class="cartCornerIcon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1.09448819 900.3622047">
<path d="M112.58 327.79v-32h90.468l112.015 256h245.5v32H294.126l-112.016-256M400.563 663.79c0 26.5-21.5 48-48 48s-48-21.5-48-48 21.5-48 48-48 48 21.5 48 48zM560.563 663.79c0 26.5-21.5 48-48 48s-48-21.5-48-48 21.5-48 48-48 48 21.5 48 48z" />
</svg>
<div id="itemCountForCart">
0
</div>
</div>
<div class="cartCornerText">
Bestellen
</div>
</div>
</a>
|
[
"stackoverflow",
"0023409087.txt"
] | Q:
Opera—SVG issue
I have got this:
1| var seglist = path.pathSegList, list = [],
2| x, y, ix, iy, item, nItem;
3|
4| for (var i = 0, n = seglist.numberOfItems; i < n; i++) {
5| item = seglist.getItem(i);
6| if (item instanceof SVGPathSegMovetoAbs) {
7| .
8| }
9| .
10| .
11| }
and line 6 throws this error:
Unhandled Error: Undefined variable: SVGPathSegMovetoAbs
why?
A:
Not all SVG DOM interfaces were fully exposed in Opera(Presto).
item instanceof SVGPathSeg
returns true however. If you want to check what type of segment you get, why not use the pathSegType or pathSegTypeAsLetter attributes on SVGPathSeg instead?
|
[
"stackoverflow",
"0017765255.txt"
] | Q:
How to set breakpoints on every line of the code (delphi)?
I have a very big code, and I need to debug it fully, so I need to set breakpoint on every line of the code. Ho to do this?
A:
No need to set breakpoints, F7 is the shortcut for "Debugger step into" which will do exactly what you're trying to do, step through the program stopping at every line.
If you want to skip certain method calls, F8 ("Debugger step over") can also be helpful.
|
[
"stackoverflow",
"0043157248.txt"
] | Q:
Finding the length of a stringvar
I am trying to make a function that will add text to a text box if the variable behind it is empty. I was attempting to do this using the .len() function, but I get an
AttributeError: 'StringVar' object has no attribute 'length'.
My code is as follows:
line1var = StringVar()
line1var.set("")
def tobeplaced(value):
global line1var
if line1var.length() == 0:
txtReceipt.insert(END, value)
foo = Button(root, text="foo", command=lambda : tobeplaced("foo")).pack()
What do?
A:
A Tkinter StringVar doesn't have a .len or .length method. You can access the associated string with the get method, and get the length of that string with the standard Python built-in len function, eg
if len(line1var.get()) == 0:
but it's cleaner (and more efficient) to do
if not line1var.get():
since an empty string is false-ish.
Here's a small (Python 3) demo:
import tkinter as tk
root = tk.Tk()
label_text = tk.StringVar()
label = tk.Label(textvariable=label_text)
label.pack()
def update():
text = label_text.get()
if not text:
text = 'base'
else:
text += '.'
label_text.set(text)
b = tk.Button(root, text='update', command=update)
b.pack()
root.mainloop()
BTW, you should not do
foo = Button(root, text="foo", command=lambda : tobeplaced("foo")).pack()
The .pack method (and the related .grid and .place methods) returns None, so the above statement assigns None to foo. To assign the widget to foo you need to do the assignment and the packing in separate statements, eg
foo = Button(root, text="foo", command=lambda : tobeplaced("foo"))
foo.pack()
|
[
"stackoverflow",
"0029969356.txt"
] | Q:
display a value of an object that exists in the session into jsp page
Hi every one i have an object in my session and i wanna select an input type radio according to the attribut of my object i tried the if tag of struts 2 taglib and it doesn't work. here is a part of my code
<div class="form-group">
<label class="col-sm-2 control-label">Admin </label> <label
class="radio-inline">
<div class="choice">
<s:if test="%{#session.curentprofil.isAdmin == N}">
<span><input type="radio" name="isAdmin" id="isAdmin"
class="styled" value="O" /></span>
</s:if>
</div> O
</label> <label class="radio-inline"> <span><input
type="radio" name="isAdmin" id="isAdmin" checked="checked"
class="styled" value="N" /></span> N
</label>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Admin </label> <label
class="radio-inline">
<div class="choice">
<s:if test="%{#session.curentprofil.isAdmin == O}">
<span><input type="radio" name="isAdmin" id="isAdmin"
class="styled" value="O" checked="checked" /></span>
</s:if>
</div> O
</label> <label class="radio-inline"> <span><input
type="radio" name="isAdmin" id="isAdmin" class="styled" value="N" /></span>
N
</label>
</div>
A:
Try this:
<s:if test="#session.curentprofil.isAdmin == \"N\"">
<!-- your code here -->
</s:if>
removed curly brackets
excaped the character - see documentation [1]
[1] https://struts.apache.org/docs/why-wont-the-if-tag-evaluate-a-one-char-string.html
|
[
"stackoverflow",
"0005907898.txt"
] | Q:
file upload progress bar with paperclip on heroku
I need to show a progress bar for file uploads and i have no idea. Any help will be appreciated.
Application is on Heroku and files are on S3
A:
I'd use jQuery file upload which doesn't require flash, only javascript and is compatible with all browser (including IE6): https://github.com/blueimp/jQuery-File-Upload
I wrote the tutorial in the wiki and made a sample app here: https://github.com/apneadiving/Pic-upload---Crop-in-Ajax
Using both jQuery File Upload and Uploadify (on in each branch)
|
[
"stackoverflow",
"0061949441.txt"
] | Q:
Difference between Deno and NodeJS
As per the Deno's official website:
Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust.
But what are the basic differences that make it simple, modern and secure as compared to NodeJS.
A:
There's one thing you must know first, Deno and Node both are created by the same developer "Ryan Dahl".
He believed there were certain flaws in Node, and thus in year 2018 he started a new project named it Deno- If you notice N O D E when taken in reverse from D gives - D E N O.
There's this article - http://clickify.colorify.tech/isNodeDead in which all the flaws discussed by Ryan Dahl are listed.
Eventually, if you are a long time Node Fanatic, it is not necessary to move onto Deno yet, but if you wanna add something, Deno has a really bright future, so you might wanna go with it.
A:
The creator of Deno and NodeJs is same. He introduced Deno to address the know issues/limitations of Node over the last ten years.
Basic differences are:
Deno supports both Typescript and Javascript. So, no need of additional compilation setup for Typescript.
Deno eliminates the npm, Package.json, and node_modules for dependencies management. It uses “ES Modules” import, which is superior for two reasons:
a. With import, you can selectively load only the pieces you need
from a package, which saves memory.
b. Loading is synchronous with require while import loads modules
asynchronously, which improves performance.
Moreover, package management is decentralized i.e., when you import
a package in a project using package's URL, package is cached on the hard drive after installation. When you need that package again, anywhere, that
cached version would be used!
Deno by default is secure means it don't allow delegate actions, like reading/writing files, accessing a network etc. But you have to pass permission parameters to do so, just like Linux security.
Deno supports top-level await means you can use await anywhere in the code... not need of wrapping await in async function. And, no call-backs hell anymore!
For details, view Comparison to NodeJs in Official Deno Manual, or checkout following articles:
top-5-reasons-javascript-developers-prefer-deno
is-deno-the-new-node?
|
[
"stackoverflow",
"0060429104.txt"
] | Q:
How to expose multiple application in kubernetes with same host via ingress
I have a two independent application which I deployed via helm and have different SCM repository.I would like to expose both of them via ingress using Openstack Loadbalancer DNS. my aim is to access both application such as hostname:8000 for application 1 and hostname:8080 for application2.
Is there any way to handle this via traefik or kubernetes?
Application 1
service:
type: NodePort
port: 8000
networkPolicy:
enabled: true
ingress:
enabled: true
annotations:
kubernetes.io/ingress.class: traefik
hosts:
- host: hostname -> just for example
paths: [/]
tls: []
Application 2
service:
type: NodePort
port: 8080
networkPolicy:
enabled: true
ingress:
enabled: true
annotations:
kubernetes.io/ingress.class: traefik
hosts:
- host: hostname -> just for example
paths: [/]
tls: []
A:
If you have single host
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: staging-ingress
annotations:
kubernetes.io/ingress.class: "nginx"
spec:
rules:
- host: test.example.com
http:
paths:
- path: /
backend:service-1
servicePort: 80
- path: /api
backend:
serviceName: service-2
servicePort: 80
Multiple hosts
spec:
rules:
- host: test-webapp-example.com
http:
paths:
- path: /
backend:
serviceName: test-webapp-example
servicePort: 80
- host: test-another-example.com
http:
paths:
- path: /
backend:
serviceName: test-webapp-somethingelse
servicePort: 80
|
[
"stackoverflow",
"0053376712.txt"
] | Q:
Searching for a color tag in html (Python 3)
I am trying to grab elements from a table if a cell has a certain color. Only issue is that for the color tags, grabbing the color does not seem possible just yet.
jump = []
for tr in site.findAll('tr'):
for td in site.findAll('td'):
if td == 'td bgcolor':
jump.append(td)
print(jump)
This returns an empty list
How do I grab just the color from the below html?
I need to get the color from the [td] tag (it would also be useful to get the color from the [tr] tag)
<tr bgcolor="#f4f4f4">
<td height="25" nowrap="NOWRAP"> CME_ES </td>
<td height="25" nowrap="NOWRAP"> 07:58:46 </td>
<td height="25" nowrap="NOWRAP"> Connected </td>
<td height="25" nowrap="NOWRAP"> 0 </td>
<td height="25" nowrap="NOWRAP"> 0 </td>
<td height="25" nowrap="NOWRAP"> 0 </td>
<td height="25" nowrap="NOWRAP"> 0 </td>
<td height="25" nowrap="NOWRAP"> 07:58:00 </td>
<td height="25" nowrap="NOWRAP" bgcolor="#55aa2a"> --:--:-- </td>
<td height="25" nowrap="NOWRAP"> 0 </td>
<td height="25" nowrap="NOWRAP"> 0 </td>
<td height="25" nowrap="NOWRAP"> 01:25:00 </td>
<td height="25" nowrap="NOWRAP"> 22:00:00 </td>
</tr>
A:
How about this:
jump = []
for tr in site.findAll('tr'):
for td in site.findAll('td'):
if 'bgcolor' in td.attrs:
#jump.append(td)
print(td.attrs['bgcolor'])
print(jump)
|
[
"stackoverflow",
"0053461230.txt"
] | Q:
How would I split a string after the spaces in haskell?
I know Haskell doesn't have loops, so I can't do that. I also know that recursion is "helpful" here, but that's about all I'm aware of.
So far, I've gotten a basic type signature, which is
toSplit :: String -> [String]
Basically, it changes from a string into a list of words...
Thanks!
P.S. I want to use the takeWhile and dropWhile functions... not a library...
A:
If you want to implement that yourself, first thing you need to do is find the first word.
You can do that with:
takeWhile (/=' ') s
If the string starts with delimiter characters you need to trim those first. We can do that with dropWhile.
takeWhile (/=' ') $ dropWhile (==' ') s
Now we have the first word, but we also need the rest of the string starting after the first word, on which we will recurse. We can use splitAt:
(_, rest) = splitAt (length word) s
And then we recurse with the rest of the string and cons the first word onto the result of that recursion giving us a list of all words.
And we need to define the base case, the result for the empty string which will terminate the recursion once there are no more characters.
toSplit :: String -> [String]
toSplit "" = []
toSplit s =
let word = takeWhile (/=' ') $ dropWhile (==' ') s
(_, rest) = splitAt (length word) s
in word : toSplit (dropWhile (==' ') rest)
Edit: There is a bug in the code above and it's not handling an edge case properly.
The bug is that it's calling splitAt on the original s but this gives a wrong result if s has leading spaces:
*Main> toSplit " foo"
["foo","o"]
This should fix the bug:
let trimmed = dropWhile (==' ') s
word = takeWhile (/=' ') trimmed
(_, rest) = splitAt (length word) trimmed
That leaves one edge case:
*Main> toSplit " "
[""]
One possible solution is to use a helper function:
toSplit :: String -> [String]
toSplit = splitWords . dropWhile (==' ')
where
splitWords "" = []
splitWords s =
let word = takeWhile (/=' ') s
(_, rest) = splitAt (length word) s
in word : splitWords (dropWhile (==' ') rest)
|
[
"stackoverflow",
"0037550704.txt"
] | Q:
Kendo UI MVC. How to update Grid and add new value in $('#Grid').data('kendoGrid').dataSource.read()
I need to update Grid after I update data in the database by calling
$('#ExchangeGrid').data('kendoGrid').dataSource.read();
I need to update grid with current DateTime but grid is updating with time that are present in DateTimePicker()
How can I change the time to current?
My Grid
@(Html.Kendo().Grid<Internal.Models.ExchangeRateData>()
.Name("ExchangeGrid")
.Columns(columns =>
{
columns.Bound(p => p.originCurrencyFormated);
columns.Bound(p => p.targetCurrencyFormated);
columns.Bound(p => p.rate);
columns.Bound(p => p.percentage) ;
columns.Command(commands => { commands.Edit(); });
columns.Bound(p => p.adjustedRate) ;
})
.Editable(edit =>
{
edit.Mode(GridEditMode.InLine);
})
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(item => item.targetCurrency);
})
.Events(events =>
{
events.RequestEnd("onRequestEnd");
})
.Read(read => read.Action("ExchangeRate_Read", "MyController").Data("ReadRequestData"))
.Update(c => c.Action("Currencies_Update", "MyControllor"))
)
)
When I update Grid function "ReadRequestData" is called
.Read(read => read.Action("ExchangeRate_Read", "MyController").Data("ReadRequestData"))
In this function value of "date" is populated from DateTimePicker
function ReadRequestData() {
return {
"date": $('#dateList').val()
};
}
Code for DateTimePicker:
@(Html.Kendo().DateTimePicker()
.Name("dateList")
.Start(CalendarView.Month)
.Format("dddd MMMM dd, yyyy H:mm:ss")
.Value(DateTime.Now)
.Events(e => e.Change("changeDate"))
)
Code for function onRequestEnd(e)
function onRequestEnd(e) {
if (e.type == "update") {
$('#ExchangeGrid').data('kendoGrid').dataSource.read();
}
}
I need to update several columns after InLine Edit but automatically only column that have been change is updated. I also need to update the column that are calculated from the column that are changed.
A:
First of all, use the Sync event, not the RequestEnd event. Also, when you call the read() method of the DataSource, the ReadRequestData function is called to get a date and pass it to your ExchangeRate_Read action. But, after the data is updated you don't need that date. So, you can just clear the DateTimePicker.
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(item => item.targetCurrency);
})
.Events(events =>
{
events.Sync("onSync");
})
.Read(read => read.Action("ExchangeRate_Read", "MyController").Data("ReadRequestData"))
.Update(c => c.Action("Currencies_Update", "MyControllor"))
)
)
function onSync(e) {
$("#dateList").data("kendoDateTimePicker").value('');
$('#ExchangeGrid').data('kendoGrid').dataSource.read();
}
Now, in your ExchangeRate_Read action you can use the current date in case the date passed from the view is null.
|
[
"meta.stackoverflow",
"0000267047.txt"
] | Q:
Leave open, or vote-to-close: "Can I host Maven on an FTP server..."
The post "Can I host Maven on an FTP server, or should I use something else?" has been closed 3 times and has been re-opened 3 times. It is on it's way to be closed for the 4th time. See the post revision history here.
If I recall correctly, it has been closed as (not necessarily in this order):
Too broad
A recommendation for a tool
(I did not see the result of the 3rd close vote).
The purpose here is to discuss whether the question should be closed or open. Please give your answer with reasons below.
A:
I think the question is fine. I know the OP writes "should I use something else," but from context it really looks like he means "do I need to use something else?" He's asking how to do something, not for everyone's opinion.
The only reason I can see to close it is that it seems to fall a little more on the sysadmin side of things, but I think it's on-topic enough (and was asked in 2008 enough) that I don't want to make a binding decision.
A:
There's a reason we (I) vote to close - to put a question on hold until it has been edited to remove fundamental problems. This post is attracting so many poor quality answers and product recommendations because the text is too indirect - there's 4 individual questions, many repeated points, and keywords like "do I need a tool" don't help. If these issues were corrected, it would be a perfectly fine question worthy of remaining open.
I wasn't ambitious enough to tackle a foreign topic earlier, but this is what I would recommend updating the text to say:
Can I host Maven on an FTP server?
I would like to host a Maven repository for a framework we're working on and its dependencies. I only have FTP access to the server I want to host the Maven repo on; I do not have full control over the host machine. Can I just deploy my artifacts to my FTP host using mvn deploy, or should I manually deploy and/or set up some things before being able to deploy artifacts?
|
[
"boardgames.stackexchange",
"0000042539.txt"
] | Q:
Can you change your mind about how a multi-target burn spell assigns damage after casting it?
So, my brother and i are playing mtg for fun. I have down a
Nezahal, Primal Tide, a 7/7. He plays a Fight with Fire and kicks it, distributing 7 damage to Nezahal and 3 to other creatures. In response, I play a Moment of Triumph, giving my Nezahal +2/+2. He then declares that he is “redistributing damage”, doing 9 damage to Nezahal and 1 elsewhere. Can he do this?
A:
Nope.
The Gatherer rulings for Fight with Fire have this to say (emphasis mine):
You choose how many targets Fight with Fire has and how the damage is divided as you put the spell onto the stack. Each target must receive at least 1 damage if Fight with Fire is kicked.
Fight with Fire is already on the stack when you respond with Moment of Triumph, so it is too late to make any changes to the way damage is divided.
A:
He can't do that because the distribution of damage is done as part of casting a spell.
601.2. To cast a spell is to take it from where it is (usually the hand), put it on the stack, and pay its costs, so that it will eventually resolve and have its effect. Casting a spell includes proposal of the spell (rules 601.2a–d) and determination and payment of costs (rules 601.2f–h). To cast a spell, a player follows the steps listed below, in order. [...]
601.2d If the spell requires the player to divide or distribute an effect (such as damage or counters) among one or more targets, the player announces the division. Each of these targets must receive at least one of whatever is being divided.
This is summarized in a ruling for Fight with Fire.
You choose how many targets Fight with Fire has and how the damage is divided as you put the spell onto the stack. Each target must receive at least 1 damage if Fight with Fire is kicked.
|
[
"stackoverflow",
"0025367383.txt"
] | Q:
SELECT data filtering by 2 values
long time since the last time...
Problem here is that:
One table with (USER) users data (name, phone etc)
Other table (USER_TYPE) which have and id and a Varchar with the type (student,worker etc)
USER has a relationship 1-N with USER_TYPE_USER. USER_TYPE_USER has a relationship 1-N with USER_TYPE. As you can guess, USER_TYPE_USER stores users' ids and user_type id's. One user can be of one or more types.
My problem here is that I want to select user data and user type from users that are type 1 and 2. So I have this (sorry, names are in Spanish).
SELECT socio.*, socio_tipo_socio.id_tipo_socio,tipo_socio.tipo
FROM ((respeta.socio
INNER JOIN respeta.socio_tipo_socio ON socio.dni = respeta.socio_tipo_socio.socio_dni)
INNER JOIN respeta.tipo_socio ON tipo_socio.id_tipo_socio = socio_tipo_socio.id_tipo_socio)
WHERE socio_tipo_socio.id_tipo_socio = 1 AND socio_tipo_socio.id_tipo_socio = 2
This doesn't work. I know I can place OR instead AND, but this will give me users which are only type 1 or 2.
Any ideas? Hope my data base professor don't see I'm asking that XD. Thanks
EDIT 1.
This is another way of make the query (I ask for less data), maybe It helps to understand what I'm trying to accomplish. I have User1 which is type 1 and 2, and User2, which is type 2. I just want to retrieve users who are Type1 and Type2, so, the ideal query will return just User1.
SELECT distinct(socio.dni), socio.nombre
from socio, socio_tipo_socio, tipo_socio
WHERE socio.dni = socio_tipo_socio.socio_dni
AND socio_tipo_socio.id_tipo_socio = tipo_socio.id_tipo_socio
AND tipo_socio.id_tipo_socio = 2
Obviously, that query above, shows type2 users (User1 and User2). Don't know how fix It to say something like "AND tipo_socio.id_tipo_socio = 2 AND AND tipo_socio.id_tipo_socio = 1" and have only User1. That's where I'm stuck.
EDIT 2
SOLVED!!!! YEYYY!!!
SELECT *
FROM socio, tipo_socio, socio_tipo_socio
WHERE tipo_socio.id_tipo_socio = 1
AND socio.dni IN (
SELECT socio.dni
FROM socio, socio_tipo_socio, tipo_socio
WHERE tipo_socio.id_tipo_socio = 2
AND tipo_socio.id_tipo_socio = socio_tipo_socio.id_tipo_socio
AND socio.dni = socio_tipo_socio.socio_dni
)
AND tipo_socio.id_tipo_socio = socio_tipo_socio.id_tipo_socio
AND socio.dni = socio_tipo_socio.socio_dni
A:
What you have done there logically correct. However none of one single record can have value 1 and value 2 simultaneously. What you should do is finding records with type1, finding records with type2 and merging them.
rows with type1
SELECT *
FROM users utu types
WHERE typeid = 1 AND <table connectors>
rows with type2
SELECT *
FROM users utu types
WHERE typeid = 2 AND <table connectors>
rows with type1 only if they are in type2 also
SELECT *
FROM users
WHERE typeid = 1 AND IN (
SELECT *
FROM users utu types
WHERE typeid = 2
) AND <table connectors>
EDIT:
detailed version.
No. you need to use only this.
SELECT *
FROM users
WHERE typeid = 1
AND IN userid (
SELECT userid
FROM users utu types
WHERE typeid = 2
)
AND tipo_socio.id_tipo_socio = socio_tipo_socio.id_tipo_socio
AND socio.dni = socio_tipo_socio.socio_dni
first table founds the people with type1.second is findind type2. see th IN in the 3rd query it means that find the people with type1 and IN the type2. It is like array search.
|
[
"stackoverflow",
"0000251890.txt"
] | Q:
Displaying unit test results in VS 2008
I am a rookie was using the Visual Studio 2008 built-in Unit Testing components, what would be the best way to record or display your results in a unit test?
I want to test my service method when it returns a System.GUID and an empty System.GUID
[TestMethod]
public void GetGUID()
{
MyWcfServiceService.MyWcfServiceClient proxy = new MyWcfServiceService.MyWcfServiceClient();
string name = "HasGuid";
System.GUID guid = proxy.GetGUID(name);
}
[TestMethod]
public void GetEmptyGUID()
{
MyWcfServiceService.MyWcfServiceClient proxy = new MyWcfServiceService.MyWcfServiceClient();
string name = "HasEmptyGuid";
System.GUID guid = proxy.GetGUID(name);
}
A:
For GetGUID()...
Assert.IsFalse(guid == Guid.Empty);
Similarly for GetEmptyGUID()...
Assert.IsTrue(guid == Guid.Empty);
|
[
"stackoverflow",
"0006703368.txt"
] | Q:
sp_attach_single_file_db Error: failed with the operating system error 5(Access is denied.)
I'm trying to use this DataBase that come with this sample project with from MS:
http://code.msdn.microsoft.com/ASPNET-Web-Forms-6c7197aa/sourcecode?fileId=18930&pathId=365206059
So after I downloaded the files: I need to attach the .mdf DataBase to my Instance of MS SQL 2008.
From Management Studio Attaching DataBase does not work and event using this command i receive the same error:
sp_attach_single_file_db 'School.mdf', 'C:\School.mdf'
ERROR:
Msg 5133, Level 16, State 1, Line 1
Directory lookup for the file "C:\School.mdf" failed with the operating system error 5(Access is denied.).
Any idea what is wrong? Thanks for your help!
A:
Give full permission on folder in which you want to create the mdf file
to the logon account with which the SQL Server service is running.
Usually: NT Service\MSSQL$
You can look that up
Control Panel-> Administrative Tools-> Services=> SQL Server -> Prperties-> Logon Tab-> Note the account
A:
What operating system are you running on? Did you get an elevation prompt when you saved the file to the root of the C drive? What user account is SQL Server running under, and does it have permissions to read any files in the root of the C drive?
You might do better placing the file into %ProgramFiles%\Microsoft SQL Server\MSSQL10.<instance name>\MSSQL\DATA, alongside the other .mdf files that you know it can already read (adjust path above as necessary, but you hopefully get the idea).
A:
I had this issue and all the solutions online was misleading.
The solution was to open SSMS as Administrator. In my opinion first try this and later try all other solutions.
|
[
"math.stackexchange",
"0001717742.txt"
] | Q:
Proving a trigonometric equation
Knowing that : $$ \sin t - \cos t = x $$
Prove that : $$ \cos^3t - \sin^3t = \frac{x}{2}(3-x^2) $$
I tried to solve it by the important corresponding $$ a^3 - b^3 = (a-b)(a²+ab+b²) $$
But I got stuck in the middle and I don't even know if it's correct what I did
A:
I like your idea. We can use the Pythagorean identity to simplify it to $$\sin^3 t-\cos^3 t=(\sin t-\cos t)(\sin^2 t+\cos^2 t+\sin t\cos t)=a(1+\sin t\cos t).$$
From the original equation, we know that $\sin^2 t-2\sin t \cos t+cos^2 t=1-2\sin t \cos t=a^2,$ so $$\sin t\cos t=\frac{1-a^2}{2}.$$ Now we just substitute.
|
[
"stackoverflow",
"0009101971.txt"
] | Q:
Filter base entity from child entities' properties
I have been looking for a solution for days now.
I have eight entities in my application, a base and seven entities that inherits from this base entity. Some of the child entities have same properties.
public class LogEntry(){
public int LogEntryId{get;set;}
public string ...
}
public class TestEntry : LogEntry{
....
public string SomeProperty{get;set;} //SomePropertyThatIsNotInBaseClass
....
}
public class XEntry : LogEntry{
....
public string SomeProperty{get; set;}
....
}
I am trying to filter base entity by this SomeProperty. I am trying to a query like
var value = Db.LogEntry.Where(i=>i.SomePropery == "some string");
It is not allowed. I can only getwhat I want by
IQueryable<LogEntry> first = Db.LogEntry.OfType<TestEntry>.Where(i=>i.SomeProperty == "...");
IQueryable<LogEntry> second = Db.LogEntry.OfType<XEntry>.Where(i=>i.SomeProperty == "...");
...
And concatenate them at the end. Is there more clever way to do than this method? Extension methods etc...
Any help would be appreciated.
A:
Edit
Looking at your example more closely, I don't think what you are trying to do is possible. If you are writing a query against the BASE entity type, then you can only query fields that are defined in the base type.
Since "SomeProperty" is not defined in LogEntry, you cannot write this query:
var logEntries = db.LogEntry.Where(r => r.SomeProperty == "foo");
Because SomeProperty is not defined in the LogEntry class.
If you want to write queries against the base class then you need to do something like the following:
public class TPTContext : DbContext
{
public TPTContext() : base("name=TPT")
{ }
public DbSet<BillingDetail> BillingDetails { get; set; }
}
public abstract class BillingDetail
{
public int BillingDetailId { get; set; }
public string Owner { get; set; }
public string Number { get; set; }
}
[Table("BankAccounts")]
public class BankAccount : BillingDetail
{
public string BankName { get; set; }
public string Swift { get; set; }
}
[Table("CreditCards")]
public class CreditCard : BillingDetail
{
public int CardType { get; set; }
public string ExpiryMonth { get; set; }
public string ExpiryYear { get; set; }
}
I wrote the following query against the base class:
TPTContext db = new TPTContext();
var allAccounts = db.BillingDetails.Where(b => b.Owner == "boran");
var bankAccounts = allAccounts.OfType<BankAccount>();
var creditCards = allAccounts.OfType<CreditCard>();
Everything seems to work fine for me.
|
[
"stackoverflow",
"0013989021.txt"
] | Q:
My nexus S phone not showing up in Android device choose
I can see my own device under "adb devices" and
having Run Configuration -> Target -> Deployment Target Selection Mode already set to "Manual" (in fact with my IDE, there's no Manual option, for some reason) and
Having my phone set to USB Debugging mode
My app is set to android:debuggable=true
However, I am still not able to see my device in "Android Device Chooser". Can anyone help me out in this? I'm using ADT as my IDE. Thanks in advance
A:
Enable USB Debugging in your cell phone.
go to Windows´s Device Manager and you can see the failed driver message, Right click and select "Update Driver Software", then "Browse my computer for driver software".
Browse to your Google Driver location for example "C:\Program Files (x86)\Android_Jorgesys\sdk\extras\google\usb_driver".
Select "Android Composite ADB Interface" driver and click on Next button, then Install.
A:
Thanks to @SalGad, it's to do with my API version that's different between my phone and project build target. The version I had on my Nexus S phone is 4.1.2 and the one on my project is 4.2
|
[
"stackoverflow",
"0045037917.txt"
] | Q:
django - image isn't saving, all other fields are
When I update the user profile via the view everything is saving to the db except the image. The forms are validating but image isn't being saved. I can log in the admin portal and successfully add an image to an existing instance. I assume my problem lies in my html template but I can't figure out what it is.
**Btw I've read multiple similiar post but none I believe addresses my issue.
form.py
class EditUserForm(forms.ModelForm):
template_name='/something/else'
class Meta:
model = User
fields = (
'email',
'first_name',
'last_name',
)
class EditProfileForm(forms.ModelForm):
template_name='/something/else'
class Meta:
model = UserProfile
fields = (
'description',
'city',
'website',
'phone',
'image',
)
views.py
@transaction.atomic
def edit_profile(request):
if request.method == 'POST':
form = EditUserForm(request.POST, instance=request.user)
form2 = EditProfileForm(request.POST, instance=request.user.userprofile)
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return redirect(reverse('accounts:view_profile'))
else:
form = EditUserForm(instance=request.user)
form2 = EditProfileForm(instance=request.user.userprofile)
args = {'form': form, 'form2':form2}
return render(request, 'accounts/edit_profile.html', args)
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.CharField(max_length=100, default='')
city = models.CharField(max_length=100, default='')
website = models.URLField(default='')
phone = models.IntegerField(default=0)
image = models.ImageField(upload_to='profile_image', blank=True)
def __str__(self):
return self.user.username
edit_profile.html
<div class="container">
{% if form.errors %}
<ol>
{% for field in form %}
<H3 class="title">
<p class="error"> {% if field.errors %}<li>{{ field.errors|striptags }}</li>{% endif %}</p>
</H3>
{% endfor %}
</ol>
{% endif %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
{{ form2.as_p }}
<button type="submit">Submit</button>
</form>
<br>
</div>
A:
If you are uploading files, you must instantiate the form with request.POST and request.FILES.
form2 = EditProfileForm(request.POST, request.FILES, instance=request.user.userprofile)
See the docs on file uploads for more info.
|
[
"stackoverflow",
"0033511250.txt"
] | Q:
How to add fields to UserCreationForm in Django?
So I've been working on a Django project and I've hit a dead end. Every time that I try to modify the UserCreationForm to account for Insurance ID and/or provider, I hit an error that says I cannot do this:
Unknown field(s) (Insurance Provider, Insurance ID) specified for User
I was wondering if anyone could tell me how to add these Fields to the form without having to override my User class?
''' Form used in patient registration. Extends UserCreationForm '''
class PatientRegisterForm(UserCreationForm):
email = EmailField(required = True)
insurance_id = forms.CharField(required=True, label="Insurance ID")
insurance_provider = forms.CharField(required=True, label="Insurance Provider")
class Meta:
model = User
fields = ("email", "password1", "password2", "Insurance ID", "Insurance Provider")
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
def save(self, commit=True):
user=super(UserCreationForm, self).save(commit=False)
user.set_password(self.clean_password2())
user.insurance_id = self.cleaned_data["insurance_id"]
user.insurance_provider = self.cleaned_data["insurance_provider"]
if commit:
user.save()
return user
''' This displays the patient login form. Unique because of insurance numbers '''
def patient_registration(request):
if request.POST:
form = PatientRegisterForm(request.POST)
if form.is_valid():
new_user = form.save()
new_patient = Patient(user = new_user)
new_patient.save()
temp= Event(activity= '\n'+new_patient.user.get_full_name()+" has registered as a patient ")
temp.save()
return HttpResponseRedirect('/login/') # TODO : Refer them to there home page
else:
return HttpResponseRedirect('/login/') # TODO : Ditto ^^^
else:
form = PatientRegisterForm()
return render(request, "main_site/patient_registration.html", {"form":form})
A:
You are not correctly referring to the insurance_id and insurance_provider fields in your form. Change the Meta class to:
class Meta:
model = User
fields = ("email", "password1", "password2", "insurance_id", "insurance_provider")
# Note: the last two fields have changed
You will also need to have defined insurance_id and insurance_provider in your User model.
|
[
"chemistry.stackexchange",
"0000083296.txt"
] | Q:
Mechanism of Halogenation of Alkene
In the above reaction, we use a non-polar compound (such as CCl$_4$) as a solvent. Then, why does the Br$_2$ polarise on attack by the alkene, even though a non-polar solvent does not encourage polarisation of a compound. Is the mutual polarisation enough for the reaction to occur.
Further, in different books the mechanism is either explained by the above mechanism or by the Molecular Orbital Theory (the alkene's filled $\pi$ orbital (HOMO) will interact with bromine's empty $\sigma$* to give the product).
Which one of these is the more popular and/or the officially accepted explanation.
A:
Alkene double bond is an area of high electron density and hence high (partial) negative charge. Bromine molecule, approaching double bond, shifts its electrons of covalent bond towards farther Br atom, it becomes polarized and an induced dipole.
That's the simplest explanation in terms of electron movement I would use.
|
[
"stackoverflow",
"0004873893.txt"
] | Q:
window.showModalDialog and postback button
I have two pages A.aspx and B.aspx
Page A.aspx opens B.aspx as modal popup by javascript function window.showModalDialog("B.aspx");
Page B.aspx has two text boxes (Login, Password), <asp:Button> control and button click event in server code.
Problem is when I click on the submit button it opens me B.aspx page in new third window
How is it possible to not open new window on submit button.
Thanks!
A:
simply in the modal window put this to the <HEAD>
<BASE target="_self">
|
[
"stackoverflow",
"0023188314.txt"
] | Q:
iOS Insert Row with 2 Date Fields
How does one insert a row into a table that I've created with two sqlserver smalldatetime fields via the windows azure mobile services library? I'm currently trying to use:
[NSDate timeIntervalSince1970]
to store the date-time value as an NSTimeInterval or double. However, this causes the following error:
Error Domain=com.Microsoft.WindowsAzureMobileServices.ErrorDomain Code=-1302 "Error: Bad request."
A:
DateTime fields should be represented by an NSDate field in the NSDictionary object you are sending to insert or update call.
So you would just do:
[table insert:@{ @"id": @"myid", @"deliveryDate": [NSDate date] } completion:... ];
If you send an NSNumber instead, then you would see the -1302 error shown above.
|
[
"stackoverflow",
"0040898625.txt"
] | Q:
React Native - how can I emit an event to RN from MainActivity.java?
In the React Native AppState library:
iOS has three states background->inactive->active
Android only has background->active
When an Android app is fully backgrounded the MainActivity goes from onPause -> onStop
When there is a System Notification e.g. an In app purchase it goes to onPause
I need to run some code when the app goes from background to the foreground
onStop -> onResume
I don't want it to run if the app was briefly paused because of a system notification
onPause -> onResume
Is this possible? The lifecycle events for React do not have an onHostStop
I tried emitting an event from MainActivity for each Activity lifecycle event but that caused the App to crash with a null pointer exception.
Is it even possible to emit an event to React Native from MainActivity?
Thanks
EDIT Added code to show attempt to emit event from MainActivity
MainActivity.java snippet
import com.facebook.react.ReactActivity;
import com.facebook.react.modules.core.DeviceEventManagerModule;
public class MainActivity extends ReactActivity {
DeviceEventManagerModule.RCTDeviceEventEmitter eventEmitter;
@Override
public void onStop() {
super.onStop();
eventEmitter.emit("onStop", "ActivityonStop");
}
}
React Native
const nativeEventListener = DeviceEventEmitter.addListener('onStop',
(e)=>{
console.log("NATIVE_EVENT");
dispatch({type: "NATIVE_EVENT"})
})
error in logcat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.realer.android, PID: 15251
java.lang.RuntimeException: Unable to stop activity {com.realer.android/com.realer.android.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'void com.facebook.react.modules.core.DeviceEventManagerModule$RCTDeviceEventEmitter.emit(java.lang.String, java.lang.Object)' on a null object reference
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3837)
at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3886)
at android.app.ActivityThread.-wrap25(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1494)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void com.facebook.react.modules.core.DeviceEventManagerModule$RCTDeviceEventEmitter.emit(java.lang.String, java.lang.Object)' on a null object reference
at com.realer.android.MainActivity.onStop(MainActivity.java:40)
at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1289)
at android.app.Activity.performStop(Activity.java:6839)
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3834)
at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3886)
at android.app.ActivityThread.-wrap25(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1494)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
A:
Try updating your MainActivity.java like this:
public class MainActivity extends ReactActivity {
@Override
public void onStop() {
super.onStop();
WritableMap params = Arguments.createMap(); // add here the data you want to send
params.putString("event", "ActivityonStop"); // <- example
getReactInstanceManager().getCurrentReactContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("onStop", params);
}
}
Let me know if this works. In my apps I usually send the events from a class that extends ReactContextBaseJavaModule where I can access the context just by calling getReactApplicationContext(), but it seems that it might work if you can obtain the ReactContext from the ReactInstanceManager.
|
[
"stackoverflow",
"0018499986.txt"
] | Q:
how to update form structure using ajax
Recently i have been working over a contact module.There are 3 columns ie. name, email, phone and a +1 button which includes anew row to add one more contact filed using ajax.
And here the problem arise. When i update my structure, the data in old contact field vanishes.
Eg:
I entered 2 rows and filled the data as name1, email1, and so on..
name1 email1 phone1
name2 email2 phone2
Now in order to add one more contact filed i use +1 botton. and as soon i click it i get:
blank_1 blank_1 blank_1
blank_2 blank_2 blank_2
blank_3 blank_3 blank_3 //here blank_1, blank_2, blank_3 are just expressing blank columns
My jquery code is :
<script>
$(document).ready(function(e) {
num = 0;
$('#plus_contact').click(function(e) {
num = num +1 ;
$.ajax({
url : 'contact/contact_form.php',
method : 'POST',
data : "number="+num,
success : function(data) {
$('#contact_form_div').html(data);
},
});
});
}); </script>
contact_form.php
<?php
if(isset($_POST['number']) && is_numeric($_POST['number']))
{
echo $list =$_POST['number'];
if($list == 1)
{
for($i=0; $i<$list;$i++)
{
?>
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">Full Name</label>
<input type="text" name="c_name[]" class="form-control" id="c_full_name" placeholder="Full Name">
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">Email address</label>
<input type="email" name="c_email[]" class="form-control" id="c_email_id" placeholder="Email">
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">Phone</label>
<input type="tel" name="c_phone[]" class="form-control" id="c_phone_number" placeholder="Phone">
</div>
<?php
}
} } ?>
How can i add a row without altering the old row data ??
A:
Instead of doing:
$('#contact_form_div').html(data);
Do this:
$('#contact_form_div').append(data);
Then you just need to make sure on your PHP that you only return one new row.
A:
Instead of replacing the current form, append the new lines generated by your PHP script. So you need to use $('#contact_form_div').append(data); instead of $('#contact_form_div').html(data);.
After you change that, you can use the num parameter to specify the number of rows to be added.
A:
replace this:
$('#contact_form_div').html(data);
with this :
$('#contact_form_div').append(data);
You just need to append it not to replace it. hope it help :)
|
[
"stackoverflow",
"0055989870.txt"
] | Q:
data-bind foreach for an observable number
I am trying to display stars for each item in a list
I have an interface that has the 5-star score on a video, how do I do a foreach for the count of that score? rather than creating an array for the score?
interface Video{
Score: number;
}
<td>
<span data-bind="foreach: score">
<span class="glyphicon-star"></span>
</span>
<span data-bind="foreach: 5 - score">
<span class="glyphicon-star-empty"></span>
</span>
</td>
A:
You could either use Array.from() or the Array(score) to create an array from the score
Array.from({ length: score })
or
[...Array(score)]
(Use score() if it's an observable)
Here's a minimal snippet:
const model = {
score: 3
}
ko.applyBindings(model)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span data-bind="foreach: Array.from({ length: score })">
<span class="glyphicon-star">*</span>
</span>
|
[
"stackoverflow",
"0051989444.txt"
] | Q:
Rails 5.2. Rendering a js.erb partial from a helper method
I have a model called Question, and it has action create;
My goal is to display a flash message instantly, using a helper method (show_alert for example) when the instance is not valid.
question_controller.rb
def create
question = Question.new(question_params)
if question.save then
redirect_to show_question_path(question.id)
else
show_alert(:warning, question.errors)
end
end
application_controller.rb
helper_method :show_alert
def show_alert(type, message)
@type = type; @msg = message
respond_to do |format|
format.js { render :template => 'alert.js.erb'}
end
end
alert.js.erb
var div = $('<div></div>').addClass(`alert alert-${@type}`)
$('<ul></ul>').append( $('<li></li>').html(@msg)
div.append(ul)
$('#alerts').html(div)
But instead of displaying the flash, I get only the partial's code on the white screen.
see the screenshot
Since I've used respond_to I got another error: ActionController::UnknownFormat
I need the snippet of code in alert.js.erb to be executed, in order to render the flash, I think the trick is somewhere in the render function, but two hours of googling were just a waste of time.
Please help! Thank you in advance
A:
ActionController::UnknownFormat error is showing up because the browser is sending HTML request to Rails server, but the respond_to block has only specified what to do in case of a javascript request from web server.
You will need to add a little bit of Ajax to achieve what you want. See this tutorial on Ajax. https://www.tutorialspoint.com/ruby-on-rails/rails-and-ajax.htm
Ajax will send a js request to browser in the background (i.e the browser will not refresh or show any signs of loading). This js request will be sent to Rails server and it will return the .js.erb file containing the script back to the browser. Now since this script was returned as a response to Ajax request by browser, the browser will already know that it is javascript that needs to be executed.
If you do not wish to implement Ajax, you have the alternate of doing something like this in your create controller:-
def create
question = Question.new(question_params)
if question.save then
redirect_to show_question_path(question.id)
else
redirect_to new_question_path(error: question.errors) #new_question_path is the action that displays the question form to the user
end
end
and then you can initialize an error variable in the action that displays the question form. e.g.
def new
@error=params[:error]
#rest of the code...
end
And then in somewhere in your new.html.erb (or whatever the html.erb file name is)
<script>
<% if @error %>
var div = $('<div></div>').addClass(`alert alert-<%= @type %>`)
$('<ul></ul>').append( $('<li></li>').html(<%= @msg %>)
div.append(ul)
$('#alerts').html(div)
<% end %>
// you might need to tweak the variable names in controller or the above code
</script>
(This code above may not be perfect. its just to give u an idea)
However this approach will not be as quick and beautiful as ajax because when the user will submit their question, the entire page will load again to display the error warning.
|
[
"stackoverflow",
"0021998836.txt"
] | Q:
Link bigger than image
I looked around the boards a bit and couldn't find anything that worked for me, but basically when I center an image that has an anchor tag wrapped around it, the linkable area fills out to fit the entire width of the div, even when specifying a width. How can I get the link to only be around the image?
Link to JS Fiddle http://jsfiddle.net/jJ4hv/
HTML
<div id="right">
<div id="content">
<div class="title">
<h3>Spawn</h3>
<a href="index.html"><p><< Go Back</p></a>
</div>
<a href="images/spawn.png" data-lightbox="inks" title="Spawn"><img src="images/spawnThumb.png" /></a>
<p class="description">Spawn</p>
</div><!-- END content -->
</div><!-- END right -->
CSS
#content img {
display: block;
margin: 0 auto;
width: 400px;
}
.title {
border-bottom: thin solid #316b9c;
margin-bottom: 20px;
}
.title a {
font-size: 12px;
color: #bcbdbf;
}
.title a:hover {
color: #316b9c;
}
.title a:active {
color: #000;
}
.topImage {
margin-bottom: 10px;
}
p {
color: #bcbdbf;
}
A:
Just add #content a to the #content img CSS.
#content img,
#content a{
display: block;
margin: 0 auto;
width: 400px;
}
http://jsfiddle.net/jJ4hv/2/
|
[
"stackoverflow",
"0025992333.txt"
] | Q:
Amazon S3 & C# Signature does not match error
I'm new to Amazon AWS & trying to put(upload) the object(image in this case) to the bucket using the SDK for .NET using a console application shown below:
namespace AwsConsoleApp1
{
class Program
{
static string bucketName = "bucketName";
static string keyName = "keyName";
static string filePath = "filePath";
static IAmazonS3 client;
public static void Main(string[] args)
{
NameValueCollection appConfig = ConfigurationManager.AppSettings;
string accessKeyID = appConfig["AWSAccessKey"];
string secretAccessKeyID = appConfig["AWSSecretKey"];
try
{
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKeyID, secretAccessKeyID, Amazon.RegionEndpoint.EUWest1))
{
Console.WriteLine("Uploading an object");
WritingAnObject();
}
}
catch (AmazonS3Exception s3Exception)
{
Console.WriteLine(s3Exception.Message, s3Exception.InnerException);
}
catch (AmazonSecurityTokenServiceException stsException)
{
Console.WriteLine(stsException.Message, stsException.InnerException);
}
}
/// <summary>
/// Put object to AWS bucket
/// </summary>
static void WritingAnObject()
{
try
{
PutObjectRequest putRequest1 = new PutObjectRequest
{
BucketName = bucketName,
Key = keyName,
FilePath = filePath
};
PutObjectResponse response1 = client.PutObject(putRequest1);
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
Console.WriteLine("Check the provided AWS Credentials.");
Console.WriteLine(
"For service sign up go to http://aws.amazon.com/s3");
}
else
{
Console.WriteLine(
"Error occurred. Message:'{0}' when writing an object"
, amazonS3Exception.Message);
}
}
}
}
}
I'm getting following error:
The request signature we calculated does not match the signature you provided.Check your key and signin method.
A:
Got my answer from this post.
I was defining Key as "/folder/file.png",which is not correct as it has a forward-slash in the beginning of the Key.
The correct way of defining the Key is "folder/file.png".
|
[
"stackoverflow",
"0043162808.txt"
] | Q:
Queue is not adding object properly
I am having some issues, like in the title, with adding objects to a queue in java. I am trying to write some code that simulates a toll booth, cars, and a queue. Below is the code.
//Below is creating and naming objects and variables
int numberOfCars, numberOfTollbooths;
double tollboothTotalServiceTime = 0, tollboothAverageServiceTime = 0;
Scanner keyboard = new Scanner(System.in);
ExpRandom random = new ExpRandom(13);
Queue<Car> carQueue = new LinkedList<Car>();
//Asks the user how many cars need to be created for this simulation
System.out.print("How many cars do you want to simulate? ");
numberOfCars = Integer.parseInt(keyboard.next());
for(int i = 1; i <= numberOfCars; i++)
{
carQueue.add(new Car(i, Increasing.increasingNumber()/10));
System.out.println("Car queue: [" + carQueue.poll() + "]");
}
Output:
#1 arrived at time 1.
Car queue: [#1]
#2 arrived at time 2.
Car queue: [#2]
#3 arrived at time 4.
Car queue: [#3]
#4 arrived at time 18.
Car queue: [#4]
#5 arrived at time 33.
Car queue: [#5]
#6 arrived at time 38.
Car queue: [#6]
#7 arrived at time 42.
Car queue: [#7]
#8 arrived at time 47.
Car queue: [#8]
#9 arrived at time 48.
Car queue: [#9]
#10 arrived at time 52.
Car queue: [#10]
#11 arrived at time 53.
Car queue: [#11]
#12 arrived at time 58.
Car queue: [#12]
how can i see the whole carQueue once all the cars are added? something like Car queue: [1,2,3,4...]
A:
poll removes the head of the queue, use peek instead.
System.out.println("Car queue: [" + carQueue.peek() + "]");
|
[
"stackoverflow",
"0015517149.txt"
] | Q:
Convert Byte Array into List Windows phone 8
I am using this piece of code to convert List into byte array but again I want to convert to this data into List how it is possible.
List<String> stringlist = new List<String>();
stringlist.Add("Oye Oye");
stringlist.Add("Hello hello");
byte[] byteArr = stringlist.SelectMany(s => System.Text.Encoding.UTF8.GetBytes(s)).ToArray();
A:
In your example it isn't possible, because you have no way to tell where a string ends and where the next one starts. It would be possible by using a separator (the character \0 is often used to indicate the end of a string):
List<String> stringlist = new List<String>();
stringlist.Add("Oye Oye");
stringlist.Add("Hello hello");
byte[] byteArr = stringlist.SelectMany(s => System.Text.Encoding.UTF8.GetBytes(s + '\0').ToArray();
You can then retrieve your list by using the Split method:
var stringList = System.Text.Encoding.UTF8.GetString(byteArr, 0, byteArr.Length).Split('\0');
But overall I don't think it's a good idea. Depending on what you need, I'd rather recommend to use the DataContractSerializer to convert your array to bytes:
var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(List<string>));
byte[] byteArr;
using (var ms = new System.IO.MemoryStream())
{
serializer.WriteObject(ms, stringlist);
byteArr = ms.ToArray();
}
And to convert it back:
using (var ms = new System.IO.MemoryStream(byteArr))
{
stringlist = (Sserializer.ReadObject(ms);
}
|
[
"stackoverflow",
"0040866385.txt"
] | Q:
Concat after checking condition in Pig
I am trying to CONCAT a column in my pig if a certain condition is getting matched for that i am using below code but it is throwing error.
CODE:
STOCK_A = LOAD '/user/cloudera/pati1.hl7' USING PigStorage('|');
data = FILTER STOCK_A BY ($0 matches '.*OBR.*' or $0 matches '.*OBX.*');
MSH_DATA = FOREACH data GENERATE ($0=='OBR' ? CONCAT('OBR',CurrentTime(),$1) : ($0=='OBX' ? CONCAT('OBR',CurrentTime(),$1))) AS Uid; , $1 AS id, $5 AS result, $3 AS resultname;
Dump MSH_DATA;
ERROR:
ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1200: <line 13, column 122> mismatched input ')' expecting COLON
A:
Source:CONCAT : The data type of the two elements must be the same, either chararray or bytearray.
First,You are trying to CONCAT fields of different datatype.Cast the fields to chararray.Second, your bincond syntax is incorrect.Since you have already filtered the records for values OBR and OBX,you need not check for $0 == 'OBX'.Third, when the value of $0 == 'OBX' you are again concatenating OBR with the current time which is same as the if part.Fourth, there is a ';' after Uid which is incorrect.
MSH_DATA = FOREACH data GENERATE ($0 == 'OBR' ? CONCAT('OBR',ToString(CurrentTime(), 'yyyy-MM-dd\'T\'HH:mm:ssz'),(chararray)$1) : CONCAT('OBX',ToString(CurrentTime(), 'yyyy-MM-dd\'T\'HH:mm:ssz'),(chararray)$1)) AS Uid, $1 AS id, $5 AS result, $3 AS resultname;
|
[
"stackoverflow",
"0026934443.txt"
] | Q:
If variable empty / null display results, if variable not null display other results
I'm trying to figure out the appropriate way of writing a query that would display results based on whether one or two variables are present. I'm still quite new to PHP, though I am learning, albeit slowly.
My current code, which accepts only one variable for a search criteria is below. As you can see I have only one _POST variable I am receiving $reg
What I'd like to do is receive a second variable
$toest=$_POST['toestelID'];
If only $reg contains a value {and $toest is Null/Empty) I would like it to query the WHERE statement as such
WHERE vg.luchtvaartmaatschappijID= '$reg'
If $reg and $toest both contain values then it would be
WHERE vg.luchtvaartmaatschappijID= '$reg' AND vg.toestelID='$toest'
I know this can be done with a IF / Else type statement, I just don't know how to program this as such.
Original Code:
<?php
$reg=$_POST['luchtvaartmaatschappijID'];
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
$reg=$_POST['luchtvaartmaatschappijID'];
$color1 = "#C2DFFF";
$color2 = "#FFFFFF";
$row_count = 0;
//connect to the database
$db=mysql_connect ("localhost", "someusername", "somepassword") or die ('I cannot connect to
the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("somedatabase");
//-query the database table
$sql="SELECT vg.*, lvm.luchtvaartmaatschappij AS lvmnaam, lvm.luchtvaartmaatschappijID as lvmid,
t.toestel
FROM tbl_vliegtuiggegevens vg
INNER JOIN tbl_luchtvaartmaatschappij lvm
ON vg.lvmID = lvm.luchtvaartmaatschappijID
INNER JOIN tbl_toestel t
ON vg.toestelID = t.toestelID
WHERE vg.luchtvaartmaatschappijID= '$reg'
ORDER BY lvm.luchtvaartmaatschappij ASC, t.toestel ASC, vg.inschrijvingnmr ASC";
//-run the query against the mysql query function
$result=mysql_query($sql);
echo "zoekresultaten:<br>
<table border='0' cellspacing='0'>
<tr>
<th width='100' valign='top'><div align='left'>cn</div></th>
<th width='150' valign='top'><div align='left'>reg</div></th>
<th width='300' valign='top'><div align='left'>Luchtvaartmaatschappij</div></th>
<th width='330' valign='top'><div align='left'>Toestel</div></th>
</tr>
<tr>
<th height='1' colspan='4' valign='top' bgcolor='#333333'></th>
</tr>";
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$row_color = ($row_count % 2) ? $color1 : $color2;
$reg=$row['inschrijvingnmr'];
$toestel=$row['toestel'];
$cnid=$row['cn'];
$lvmid=$row['lvmid'];
$lvmnaam=$row['lvmnaam'];
$ID=$row['vliegtuiggegevenID'];
//-display the result of the array
echo "<tr>";
echo "<td bgcolor='$row_color'>".$cnid."</td>";
echo "<td bgcolor='$row_color'><a target='_blank'
href=\"../vliegtuiggegevens/vliegtuiggegevens_form.php?id=$reg&cid=$cnid&lvid=$lvmid\">" .$reg
. "</a></td>";
echo "<td bgcolor='$row_color'>" . $lvmnaam . "</td>";
echo "<td bgcolor='$row_color'>" . $toestel . "</td>";
echo "</tr>";
// Add 1 to the row count
$row_count++;
}
echo "</table>";
}
if( mysql_num_rows($result) == 0 )
{
include('../vliegtuiggegevens/voegvliegtuiggegevenstoe_form.php');
}
}
?>
A:
Yes, you got it right - a few if and else statements are what you need. Here is a snippet that should help:
$toest=$_POST['toestelID'];
$reg=$_POST['reg'];
$where_stmt="";
if((isset($reg) && !empty($reg)) && (!isset($toest) || empty($toest)))
{
$where_stmt="WHERE vg.luchtvaartmaatschappijID='".$reg."'";
}
elseif((isset($toest) && !empty($toest)) && (!isset($reg) || empty($reg)))
{
$where_stmt="WHERE vg.toestelID='".$toest."'";
}
elseif(isset($reg) && !empty($reg) && isset($toest) && !empty($toest))
{
$where_stmt="WHERE vg.luchtvaartmaatschappijID='".$reg."' and vg.toestelID='".$toest."'";
}
else
{
//where statement should be excluded as no filters are available
}
$sql="SELECT vg.*, lvm.luchtvaartmaatschappij AS lvmnaam, lvm.luchtvaartmaatschappijID as lvmid,
t.toestel FROM tbl_vliegtuiggegevens vg INNER JOIN tbl_luchtvaartmaatschappij lvm ON vg.lvmID = lvm.luchtvaartmaatschappijID INNER JOIN tbl_toestel t ON vg.toestelID = t.toestelID $where_stmt ORDER BY lvm.luchtvaartmaatschappij ASC, t.toestel ASC, vg.inschrijvingnmr ASC";
|
[
"askubuntu",
"0001025368.txt"
] | Q:
2d to 3d video conversion
I'm looking for a method to convert a normal movie format like m4v or mkv and creating a file with side by side images that would be viewable in Vic for Android in a Google cardboard.
I have an old Android phone and the tilt and gyro sensors don't work with 3d video players. You can't control anything.
What I would like to do is create the side by side video image from a normal mkv or m4v. Then I would start the video and place it in the Google cardboard. I don't care about the control aspect.
I didn't find anything in other questions. Googling gives a few windows centric solutions, but I don't have the darkside in my house.
A:
Converting from 2D to 3D is impossible...
Why? Because of the entropy of the universe of course! :-)
(Meaning: You cannot add what's not there; 3D movies are filmed with 2 cameras, one of each eye; 2D movies are filmed with 1 camera)¹
Converting from 2D to Side-by-Syde (SBS) 2D is possible however:
ffmpeg -i 2D.mp4 -filter_complex \
"[0]scale=iw*sar:ih,setsar=1,scale=-1:$720,\
crop=$720:$720,split[left][right]; \
[left][right]hstack[sbs]" -map "[sbs]" -map 0:a? SBS.mp4
which will give you a movie that you can still watch using cardboard, but it'll be 2D, not 3D.
in the above command, you can change the following options:
720 to the resolution you want (SD=540, HD=720,FHD=1080, but any value can be taken)
2D.mp4 is the input file
SBS.mp4 is the output file
¹Yes, it's more complex than that, but let's keep it simple... ;-)
|
[
"stackoverflow",
"0020177453.txt"
] | Q:
How to populate Angular UI Bootstrap Typeahead with newest $resource
According to this Paweł Kozłowski's answer, Typeahead from AngularUI-Bootstrap should work when asynchronously obtaining popup items with $resource in newest Angular versions (I'm using 1.2.X).
Plunk - Paweł's version - Typeahead with $http
I guess I don't know how to use it properly (As a result I get an error in typeaheadHighlight directive's code - typeahead treats instantly returned Resources as strings and tires to highlight them).
Plunk - Typeahead with $resource
I think the critical code is:
$scope.cities = function(prefix) {
var p = dataProviderService.lookup({q: prefix}).$promise;
return p.then(function(response){
$log.info('Got it!');
return response.data;
});
return p;
};
I've tried bunch of stuff - returning $promise (version from Plunker), query(), then().
Currently, I'm using $http for this functionality in my app and I'm ok with it. Still, just wanted to know how to achieve the same with $resource.
You might want to take a look at this: https://github.com/angular/angular.js/commit/05772e15fbecfdc63d4977e2e8839d8b95d6a92d
is ui.bootstrap.typeahead compatible with those changes in $resource's promise API ?
A:
Should be:
$scope.cities = function(prefix) {
return dataProviderService.lookup({q: prefix}).$promise.then(
function(response){
// might want to store them somewhere to process after selection..
// $scope.cities = response.data;
return response.data;
});
};
This is based of the angular commit mentioned above, and it worked for me on Angular 1.2.13
A:
Thanks to the answer from @andrew-lank, I did mine with $resource as well. I didn't have a data attribute in my response though. I used the query method on $resource, which expects a responsetype of array so maybe that is why there is no data attribute. It is an array of Resource objects, each of which contains the data. So my code is slightly simpler, looks more like this:
$scope.cities = function(prefix) {
return dataProviderService.query({q: prefix}).$promise.then(
function(response){
return response;
});
};
|
[
"math.stackexchange",
"0002202418.txt"
] | Q:
Find interval solutions of $y'=2y\cos^2t-\sin t$
I need to find interval solutions of following equation:
$y'=2y\cos^2t-\sin t$
So it looks like odrinary linear equation, so we can solve it first, assuming that $\sin t=0$, and obtain $$y=ce^{\sin t\cos t+t}$$ Then assume it is solution of "full" equation and find $c$, which, I believe, is $$-\int\frac{\sin t}{e^{\sin t\cos t+t}}$$
But what to do next?
A:
You have the equation of the form $y'+p(x)y=q(x)$ It can be solved by a sum of the solution to the homogeneous equation and the particular solution given by integrating factor. The homogeneous solution you have just obtained
$$\int\frac{dy_{h}}{y_{h}}=2\int\cos^{2}(t)dt$$
$$y_{h}(t)=c_{1}e^{(\frac{1}{2}\sin(2t)+t)}$$
The integrating Factor is
$$I=e^{\int{p(t)}dt}=e^{(-\frac{1}{2}\sin(2t)-t)}$$
So, the particular solution is
$$y_{p}(t)=-e^{(\frac{1}{2}\sin(2t)+t)}\int{e^{(-\frac{1}{2}\sin(2t)-t)}}\sin(t)dt$$
So the solution of the equation is
$$y(t)=y_{h}(t)+y_{p}(t)=e^{\frac{1}{2}\sin(2t)+t}\Big[c_{1}-\int{e^{(-\frac{1}{2}\sin(2t)-t)}}\sin(t)dt\Big]$$
|
[
"stackoverflow",
"0014289770.txt"
] | Q:
Windows Phone: Log to console
Disclaimer: I'm quite new to the MSFT tech world and only started Windows Phone development a month or so ago.
I am unable to figure out how to log information to the Visual Studio Output window from within a C# and C++ (Direct3D) Windows Phone 8 App. Is this possible?
I am building in debug mode, targeting Windows Phone 8, running in the XDE emulator and my development machine is a Windows 8 box with VS2012 Ultimate installed. My App runs fine, my Direct3D scene renders normally, but I can't log anything! This makes tracing code execution difficult and forces me to use breakpoints (which can be overkill in many situations).
I've been searching far and wide and have tried many methods (OutputDebugString being one of them). I can't see anything on MSDN about this - why is this not documented anywhere?
A:
Yep, it's possible to write debug strings from WP8 C++ to the output window in VS2012. I actually have an example of that here.
1) Invoke OutputDebugString from C++.
void Direct3DInterop::MyButtonWasClicked()
{
OutputDebugString(L"Button was clicked!");
}
2) Before running the app make sure to change to the native debugger from the managed debugger in the project's properties.
|
[
"stackoverflow",
"0013428260.txt"
] | Q:
Verify if the email entered for requesting password is present in the database
I have the following code to retrieve the password of a user from the database and email to him. I am successfully able to send a user his password if his email is present in the database. But in the event that the email doesn't exist, I want the code to echo that the email for the particular user doesn't exist in the database. My code gives me the below result if an invalid email is entered in the form:
Failed to add recipient: @localhost [SMTP: Invalid response code received from server (code: 555, response: 5.5.2 Syntax error. v9sm2318990paz.6)]
I have tried using the if-else statement for this purpose. Here's the code I wrote:
<?php
//Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
// email value sent from HTML form
$email_to=$_POST['email'];
// table name
$tbl_name="registration";
if($mysql1 = "SELECT ID,Email,Password FROM $tbl_name WHERE Email='$email_to' ORDER BY ID DESC ")
{
$selectemail = mysql_query($mysql1);
$shah = mysql_fetch_array($selectemail);
$EMAIL = $shah['Email'];
$UID = $shah['ID'];
$password = $shah['Password'];
require_once "/home/computat/php/Mail.php";
$from = "[email protected]";
$to = $EMAIL;
$subject = "Your password for www.computationalphotography.in";
$body = "Your password for logging on to our website www.computationalphotography.in is:\n$password\r\nIf you have any additional queries, kindly write to us at [email protected]\r\n\nThanks & Regards\nThe Computational Photography Team\n";
$host = "ssl://smtp.gmail.com";
$port = "465";
$username = "[email protected]"; //
$password = "*********";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p></p>");
}
}
else{
echo "<b><center>Email not found in the database</center></b>";
}
/*
A:
Use this
$mysql1 = mysql_query("SELECT ID,Email,Password FROM $tbl_name WHERE Email='$email_to' ORDER BY ID DESC ");
if(mysql_num_rows($mysql1)){
//exists in db
}
else{//does not exist}
Avoid using mysql_*functions use mysqli_* or PDO as mysql_* is being depreciated
|
[
"stackoverflow",
"0003424172.txt"
] | Q:
UISearchBar and resignFirstResponder
I have a very basic UITableView with an attached UISearchBar, and here's the flow of what happens
UITableView is empty, user taps UISearchBar, and brings up keyboard.
Once the user taps the Search button
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder]; //move the keyboard out of the way
//Code....
}
Works just fine, and moves the keyboard out of the way, and populates the UITableView.
The problem is any subsequent search attempts.
The same steps as before occur, however the keyboard is never dismissed. I have a feeling something else is becoming the responder, I just need a little clarity to understand what is actually occurring.
A:
Without seeing your code it is difficult to guess. However, if you include:
[self.view endEditing:YES];
all views will resign first responder.
|
[
"superuser",
"0000339430.txt"
] | Q:
Is there any GUI tool to manipulate package in Ubuntu
Wondering if there is any GUI tool to handle the command apt-get. I am using Ubuntu 10
A:
Synaptic package manager.
System > Administration > Synaptic Package Manager
Keep in mind that this is dropped from Ubuntu 11.10 onwards in favor of Ubuntu Software Center.
|
[
"stackoverflow",
"0049044973.txt"
] | Q:
Mysql for a given group type get count and sum from other tables
I have two tables. users and transactions.lets say type 1 is student and type 2 is teacher
users:
+----+--------+--------------+
| id | name | user_type_id |
+----+--------+--------------+
| 1 | Noob | 1 |
| 2 | Coder | 2 |
+----+--------+--------------+
transactions:
+----+---------+--------+
| id | user_id | amount |
+----+---------+--------+
| 1 | 1 | 10 |
| 2 | 2 | 10 |
| 3 | 1 | 10 |
+----+---------+--------+
I want to get the sum and count for each user_type_id;
Something like this
user_type_id:1
sum_of_transaction: 20,
number_of_transactions: 2,
user_type_id:2
sum_of_transaction: 10,
number_of_transactions: 1
How can I do that? Noob here
A:
select aa.user_type_id, sum(bb.amount) as sum_of_transaction,
count(bb.id) as number_of_transactions
from users aa inner join transactions bb on aa.id = bb.user_id
group by aa.user_type_id
|
[
"stackoverflow",
"0056706172.txt"
] | Q:
Why is .then() never executed in this Node JS example, even though Promise is resolved?
I am new to node and following Ryan Lewis' excellent course on advanced use of the AWS Javascript SDK. The code I wrote is according to the instructions and runs fine, it even connects to AWS and creates a security group as expected. After that it is expected to resolve the returned promise and continue by creating a key-pair and finally the instance. If there were an error, it is expected to be caught.
However, the code in the resolve (or reject) functions passed into the promise using the .then() and .catch() statements near the end is never executed, which is not expected.
I tried:
restructuring the code a bit
adding some logging
adding a setInterval() at the end to prevent node from exiting
Here is my code:
// Imports
const AWS = require('aws-sdk')
const proxy = require('proxy-agent')
const helpers = require('./helpers')
AWS.config.update({
region: 'eu-central-1'
})
console.log(AWS.config)
// Declare local variables
const ec2 = new AWS.EC2()
const sgName = 'hamster_sg'
const keyName = 'hamster_key'
// Create functions
function createSecurityGroup(sgName) {
const params = {
Description: sgName,
GroupName: sgName
}
return new Promise((resolve, reject) => {
ec2.createSecurityGroup(params, (err, data) => {
if (!err) {
const params = {
GroupId: data.GroupId,
IpPermissions: [
{
IpProtocol: 'tcp',
FromPort: 22,
ToPort: 22,
IpRanges: [
{
CidrIp: '0.0.0.0/0'
}
]
},
{
IpProtocol: 'tcp',
FromPort: 3000,
ToPort: 3000,
IpRanges: [
{
CidrIp: '0.0.0.0/0'
}
]
}
]
}
ec2.authorizeSecurityGroupIngress(params, err => {
console.log('Creating Security Group.')
if (!err) {
console.log('Calling Resolve.')
resolve
} else {
reject(err)
}
})
} else {
reject(err)
}
})
})
}
function createKeyPair(keyName) {
const params = {
KeyName: keyName
}
return new Promise((resolve, reject) => {
ec2.createKeyPair(params, (err, data) => {
if (!err) {
resolve(data)
} else {
reject(err)
}
})
})
}
function createInstance(sgName, keyName) {
const params = {
ImageId: 'ami-026d3b3672c6e7b66',
InstanceType: 't2.micro',
KeyName: keyName,
MaxCount: 1,
MinCount: 1,
SecurityGroups: [sgName],
UserData:
'IyEvYmluL2Jhc2gKY3VybCAtLXNpbGVudCAtLWxvY2F0aW9uIGh0dHBzOi8vcnBtLm5vZGVzb3VyY2UuY29tL3NldHVwXzgueCB8IHN1ZG8gYmFzaCAtCnN1ZG8geXVtIGluc3RhbGwgLXkgbm9kZWpzCnN1ZG8geXVtIGluc3RhbGwgLXkgZ2l0CmdpdCBjbG9uZSBodHRwczovL2dpdGh1Yi5jb20vdGl0dXNuL2hhbXN0ZXJjb3Vyc2UuZ2l0CmNkIGhiZmwKbnBtIGkKbnBtIHJ1biBzdGFydAo='
}
return new Promise((resolve, reject) => {
ec2.runInstances(params, (err, data) => {
if (!err) {
resolve(data)
} else {
reject(err)
}
})
})
}
// Do all the things together
createSecurityGroup(sgName)
.then(
() => {
console.log('SecurityGroup Created.')
return createKeyPair(keyName)
},
err => {
console.error('Failed to create instance with:', err)
}
)
.then(helpers.persistKeyPair)
.then(() => {
console.log('Keypair Created.')
return createInstance(sgName, keyName)
})
.then(data => {
console.log('Created instance with:', data)
})
.catch(err => {
console.error('Failed to create instance with:', err)
})
setInterval(function() {
return console.log("I'm still running!")
}, 1000)
And here is the output:
Creating Security Group.
Calling Resolve.
I'm still running!
I'm still running!
I'm still running!
I'm still running!
I'm still running!
Node version is 10.16.0
When I set a breakpoint in IntelliJ on the line that prints "Calling Resolve." then I see the following:
And this is the point where I am a bit lost. I cannot see if the resolve function is properly set. Is there any way to do that? But more importantly: what am I missing? It really doesn't seem like I am doing anything special (except maybe leaving out all the semicolons, which eslint and prettier made me do). So the question is simply: why are all the then() calls near the end of the code never executed, even though I am calling resolve nicely? Any help is much appreciated.
A:
Change resolve to resolve() in this:
ec2.authorizeSecurityGroupIngress(params, err => {
console.log('Creating Security Group.')
if (!err) {
console.log('Calling Resolve.')
resolve
} else {
reject(err)
}
so it becomes:
ec2.authorizeSecurityGroupIngress(params, err => {
console.log('Creating Security Group.')
if (!err) {
console.log('Calling Resolve.')
resolve() // <===== change here
} else {
reject(err)
}
You have to actually call the function. Just putting resolve in your code does nothing without parens after it.
FYI, it is generally considered a lot cleaner coding style to "promisify" your functions outside (creating separate functions/methods that return a promise), separately from their use so then your main coding logic and control flow shows only promise operations, not a mix of inline promises and callbacks.
Also, for functions that follow the node.js asynchronous calling convention of a callback with arguments (err, data) (which is only some of the async functions you're using), you can use util.promisify() to create promisified versions of your functions/methods without hand coding each one.
|
[
"stackoverflow",
"0042418493.txt"
] | Q:
How do I upload to Google Cloud Storage with Curl and an API key?
I am trying to upload to google cloud storage with Curl and an API key, without success. The error message seems to indicate that I lack the Content-length header, which I don't. Any ideas?
$ curl -v -T ./myfile -X POST https://storage.googleapis.com/my-app/my-bucket/myfile?key=<my-api-token>
> Host: storage.googleapis.com
> User-Agent: curl/7.51.0
> Accept: */*
> Content-Length: 4
> Expect: 100-continue
>
< HTTP/1.1 100 Continue
* We are completely uploaded and fine
< HTTP/1.1 411 Length Required
< Date: Thu, 23 Feb 2017 13:46:59 GMT
< Content-Type: text/html; charset=UTF-8
< Server: UploadServer
< Content-Length: 1564
< Alt-Svc: quic=":443"; ma=2592000; v="36,35,34"
< Connection: close
<
<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
<title>Error 411 (Length Required)!!1</title>
<style>
[snip snip]
</style>
<a href=//www.google.com/><span id=logo aria-label=Google></span></a>
<p><b>411.</b> <ins>That’s an error.</ins>
<p>POST requests require a <code>Content-length</code> header. <ins>That’s all we know.</ins>
* Curl_http_done: called premature == 0
* Closing connection 0
A:
API keys do not provide authentication. They associate a call with a project for purposes of quota and a few other things, but you cannot use them to access resources that require anything beyond anonymous access.
What you'll need is an "Access Key", which can be acquired in a variety of ways, usually via an OAuth exchange. If you have the gcloud command installed, the easiest way to grab a quick access key to use with cURL is to run gcloud auth print-access-token. The following should work:
$> curl -v --upload-file my-file.txt \
-H "Authorization: Bearer `gcloud auth print-access-token`" \
'https://storage.googleapis.com/my-bucket/my-file.txt'
|
[
"stackoverflow",
"0047875978.txt"
] | Q:
Reference to left hand side on implicit cast operator
Is there a way I can get an instance of the left hand side of the operation when overloading an implicit cast from int to A?
Like this:
public class A
{
int myInt;
public static implicit operator A(int x)
{
a.myInt = x;
}
}
and then
A myA = new A();
myA = 2;
so that myA.myInt is 2
I searched on the internet but I couldn't find an answer to this exact problem. I don't think it is possible since it is a static function and it will throw you an error if you try to put two parameters into the function. Also, I can see this would give you an error if you tried to do this on a null variable (like if I had declared it like this A myA;). But then you could do it in a struct (because as far as I know structs can't ever be null - or can't be assigned null -, please correct me if I'm wrong).
I'm just wondering if there is some sort of wizardry that I could do to make something like this work.
A:
You cannot get a reference to myA.myInt or any other left side, because it is not always there.
Here is an example when determining the left side would be problematic:
void Foo(A a) {...}
...
Foo(2);
Above, calling Foo(2) requires invoking your implicit conversion operator, yet its return value is not assigned to anything other than Foo's a parameter, which is not a variable that would be available in the caller.
Demo.
A:
This is not possible. The implicit operator returns a value. It is the code generated by the C# compiler that calls that code to get the value and use it in whatever way the caller indicates it should be used.
It's worth noting that there may not even be a storage location. If someone writes SomeMethodThatAcceptsAnAInstance(2) then you're not storing the results of the implicit conversion in a variable. You could also write A a = 2; in which a is an uninitialized variable until the implicit operator's value is set to it, so the storage location does not have valid state at the time the implicit operator is called.
|
[
"stackoverflow",
"0016000165.txt"
] | Q:
javaee-api in jboss7.1.3 causing: Caused by: java.lang.NoClassDefFoundError: javax/faces/component/UIComponentBase
I'm currently trying to develop an ear app and would like to deploy it in jboss7.1.3 server.
I've use the jboss maven template to create a javaee6 ear app and replaced most of the javaee6 related dependencies with:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
Because I thought it would be better to stick with the standard. But when I add seam-faces to the dependency an error was thrown:
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: JBAS018045: Failed to load annotated class: org.jboss.seam.faces.component.UIViewAction
Further digging revealed a missing class:
Caused by: java.lang.NoClassDefFoundError: javax/faces/component/UIComponentBase
Why is that? Should I just stick with the dependencies provided by the maven archetype? My concern is what if I migrate to Glassfish.
A:
The answer above is valid but what I did was different, I removed the seam-faces dependency and it solved my problem. What I'm using from seam-faces is the s:objectConverter I've use in combo box, without it I created my own entity converter.
|
[
"stackoverflow",
"0036698463.txt"
] | Q:
typescript - namespaces not included on import
I have an angular application, written in typescript whose config registration was just getting out of control, and huge - it took up about 3 pages.
So I broke it up into multiple config(fn) sections, and moved as much logic out of that page as I could and encapsulated specific behaviors into their own classes; it seemed like the smart way to go about cleaning it up.
each of the new classes looks something like this;
namespace config {
export class http {
constructor($httpProvider: ng.IHttpProvider){
// $httpProvider configuration
}
}
}
so back in my main.ts, the file that creates my module and registers everything, I import them over.
import { http } from './config/http';
import { router } from ./config/router';
// etc.
but the namespace doesn't seem to be a part of this. I cannot call them such as...
config(config.http)
config(config.router)
// etc.
I've had to instead give them new alias when bringing them in;
import { http as configHttp } from './config/http';
import { router as configRouter } from './config/router';
// etc.
Why is this? Is there anything I can do to keep the namespace definition intact and use the simpler method I was aiming for?
A:
The namespace you have is redundant if you're using import statements.
Here:
import { http } from './config/http';
You're asking only for the http class in that file so that's what you're getting.
Also, if anything it should be module config and not namespace config.
You should read Namespaces and Modules and more precisely Needless Namespacing.
|
[
"stackoverflow",
"0059452081.txt"
] | Q:
What would be the return type for React function
I am new typescript and React.
I was creating a container
import React from 'react'
interface containerProps {
heading: string,
para: string
}
const container = (props: containerProps) => {
return (
<>
</>
)
}
but this is giving me an error in JSX saying type expected.
What should be react JSX return type?
A:
Assuming you are using React 16.8, the right way of providing typings would be to use React.FC or React.FunctionComponent. Then, we can provide the component's props(ContainerProps) as part of the generics parameter.
import * as React from 'react';
interface ContainerProps {
heading: string,
para: string
}
const container: React.FC<ContainerProps> = (props: ContainerProps) => {
return (
<>
</>
)
}
|
[
"stackoverflow",
"0048160482.txt"
] | Q:
Class Method missing one positional argument
I have defined the following parent class:
class Material(object):
def newMaterial(self,matPhysLaw, stressState,e,nu,alpha,sigY = 0.0,kM = 0.0,mM = 0.0):
if (matPhysLaw=="elastic"):
return ElasticMaterial(self,stressState,e,nu,alpha,sigY,kM,mM)
And the following Child Class:
class ElasticMaterial(Material):
def __init__(self,StressState,e,nu,alpha,sigY=0.0,kM=0.0,mM=0.0):
#Material.__init__(self,StressState,e,nu,alpha,sigY=0.0,kM=0.0,mM=0.0)
self.StressState = StressState
if self.StressState=='threed':
self.lv=6 #lv is length of stress and strain vectors
else:
self.lv=4
self.e = e
self.nu = nu
self.alpha = alpha
self.sigY = sigY
self.kM = kM
self.mM = mM
I am trying to create the child class from the base class itself and I am calling the newMaterial() method as below:
m2 = Material.newMaterial('elastic','threed',10e6,0.2,1e7)
But, I am getting an error as newMaterial() is missing 1 positional argument: alpha.
I want an explanation as to why I am getting this error and how can I rectify it?
A:
If you're calling Material.newMaterial(...) directly, self is not bound, so you're missing a mandatory argument. (You're trying to call newMaterial with self='elastic', etc.)
Either remove the parameter and make it a @staticmethod:
class Material(object):
@staticmethod
def newMaterial(matPhysLaw, stressState, e, nu, alpha, sigY=0.0, kM=0.0, mM=0.0):
if matPhysLaw == "elastic":
# But here you don't need the `self` parameter for instantiation
return ElasticMaterial(stressState, e, nu, alpha, sigY, kM, mM)
Or use a @classmethod decorator if you need to keep a reference to the class:
class Material(object):
@classmethod
def newMaterial(cls, matPhysLaw, stressState, e, nu, alpha, sigY=0.0, kM=0.0, mM=0.0):
if (matPhysLaw=="elastic"):
return ElasticMaterial(stressState, e, nu, alpha, sigY, kM, mM)
# Do something with `cls`...
|
[
"stackoverflow",
"0005383790.txt"
] | Q:
Question About move_uploaded_file()
I used to have a php file that does a simple move_uploaded_file by using selecting a local file and upload to our UNIX web server.
Now we migrate our code to a Windows2003 Server, then the move_uploaded_file() fails, the error that keeps coming up reads like:
"Cannot move the C:Windows\temp\100D.php" file to desiredDirectory.
here desiredDirectory means it caputures the correct directory for this file movement. The code we used is pretty straightforward:
if(move_uploaded_file($_FILES['file']['tmp_name'], $target))
and we did try change it to $HTTP_POST_FILES, but still not working.
So we are really clueless at the moment, wonder if any experts could give us some hints, thanks a lot.
A:
You should check if the target directory exists and if the apache user has all rights on that folder.
For a test you can set the folder access settings for the user 'everyone' to 'full'
The snippet of your code i see here is correct and you don't have to use $HTTP_POST_FILES
|
[
"stackoverflow",
"0005810540.txt"
] | Q:
Django for social networking
I know this is a relatively broad question, but is Django robust enough to build a social network on? I am concerned mainly with performance/speed. For example, for a site with a small user base (<10,000 users), is it possible to create a Django-backed site that would perform at a speed similar to Facebook?
What are its potential weaknesses, and things that need to be focused on in order to make it as fast as possible?
A:
"What are its potential weaknesses, and things that need to be focused on in order to make it as fast as possible?"
The one thing you might be worried about further down the road is that depending on how you create your models and connect them to one another, you may run into an issue where a single page generates many, many, many queries.
This is especially true if you're using a model that involves a generic relation.
Let's say you're using django-activity-stream to create a list of recent events (similar to Facebook's News Feed). django-activity-stream basically creates a list of generic relations. For each of these generic relations you're going to have to run a query to get information about that object. And, since it's generic (i.e. you're not writing a custom query for each kind of object), if that object has its own relations that you want to output, you might be looking at something like 40-100 queries for an activity feed with just 20-30 items.
Running 40-100 queries for a single request is not optimal behavior.
The good news is that Django is really just a bunch of classes and functions written in python. Almost anything you write in python can be added into Django, so you can always write your own functions or code to optimize a given request.
Choosing another framework is not going to avoid the problem of scalability; it's just going to present different difficulties in different areas.
Also, you can look into things like caching in order to speed up responses and prevent server load.
A:
This question was asked in 2011 and Django has come a long way since then. I've previously build a social network with 2 million users on Django and found the process to be quite smooth. Part of getstream.io's infrastructure also runs on Django and we've been quite happy with it. Here are some tips for getting most out of your Django installation. It wasn't quite clear from the question but I'll assume your starting from a completely unoptimized Django installation.
Static files & CDN
Start by hosting your static files on S3 and stick the Cloudfront CDN in front of it. Hosting static files from your Django instance is a terrible idea, please don't do it.
Database & ORM: Select related
The 2nd most common mistake is not optimizing your usage of the ORM. You'll want to have a look at the documentation regarding select related and apply it as needed. Most pages on your site should only take 2-3 queries and not N queries as you'll typically see if you don't use select related correctly:
https://docs.djangoproject.com/en/1.11/ref/models/querysets/
Database: PGBouncer
Creating a new connection to your postgres database is a rather heavy operation. You'll want to run PGBouncer on localhost to ensure you don't have any unneeded overhead when creating database connections. This was more urgent with older versions of Django, but in general is still a good idea.
Basic Monitoring & Debugging
Next you'll want to get some basic monitoring and debugging up and running. The django debug toolbar is your first friend:
https://github.com/jazzband/django-debug-toolbar
After that you'll want to have a look at tools such as NewRelic, Datadog, Sentry and StatsD/Graphite to get you more insights.
Separate concerns
Another first step is separating out concerns. You'll want to run your database on its own server, your search server on it's own server, web on their own servers etc. If you run everything on one machine it's hard to see what's causing your app to break. Servers are cheap, split stuff up.
Load balancer
If you've never used a load balancer before, start here:
https://aws.amazon.com/elasticloadbalancing/
Use the right tools
If you're doing tag clouds, tag search or search use a dedicated tool such as Elastic for this.
If you have a counter that is frequently changing or a list that is rapidly changing use Redis instead of your database to cache the latest version
Celery and RabbitMQ
Use a task queue to do anything that doesn't need to be done right now in the background. The most widely used task queue is Celery:
http://www.celeryproject.org/
Denormalize everything
You don't want to compute counts such as likes and comments on reads. Simple update the like and comment count every time someone adds a new like or comment. This makes the write operation heavier, but the read lighter. Since you'll probably have a lot of reads and very few writes, that's exactly what you want.
News feeds and activity streams
If you're building feeds have a look at this service for building news feeds & activity streams or the open source Stream-Framework
In 2011 you had to build your own feed technology, nowadays this is no longer the case. Build a social network with PHP
Now that we've gone over the basics lets review some more advanced tips.
CDN and 2 stage loading
You are already using Cloudfront for your static files. As a next step you'll want to stick Cloudfront in front of your web traffic as well. This allows you to cache certain pages on the CDN and reduce the load on your servers.
You can even cache pages for logged in users on the CDN. Simply use Javascript to load in all the page customizations and user specific details after the page is served from the CDN.
Database: PGBadger
Tools such as PGBadger give you great insights into what your database is actually doing. You'll want to run daily reports on part of your log data.
Database: Indexes
You'll want to start reading up on database indexes. Most early scaling problems can be fixed by applying the right index and optimizing your database a little bit. If you get your indexes right you'll be doing better than most people. There is a lot more room for database optimization and these books by the 2nd quadrant folks are awesome. https://www.2ndquadrant.com/en/books/
Database: Tuning
If you're not using RDS you'll want to run a quick PGTune check on your database. By default postgres' configuration is pretty sluggish, PGTune tells you the right settings to use:
https://github.com/gregs1104/pgtune
Cache everything
Scaling your database is a pain. Eventually you'll get around to having multiple slave databases, handling sharding and partitioning etc. Scaling your database is time consuming and your best way to avoid spending tons of time on that is caching. Redis is your go to cache nowadays, but memcached is also a decent option. Basically you'll want to cache everything. A page shows a list of posts: Read from Redis, Looking up user profiles? Read from Redis. You want to use your database as little as possible and put most of the load on your cache layer since it's extremely simple to scale your cache layer
Offsets
Postgres doesn't like large offsets. Use ID filtering when you're paginating through large result sets.
Deadlocks
With a lot of traffic you'll eventually get deadlocks. This happens when multiple transactions on postgress try to lock a piece of information and A waits for B while B waits for C and C waits for A. The obvious solution is to use smaller transactions. That reduces the chance for deadlocks to occur. Next, you'll want to batch updates to your most popular data. IE. Instead of updating counts whenever someone likes a post, you'll want store a list like changes and sync that to the count every 5 minutes or so.
Those are some of the basic tips, have fun dealing with rapidly growing social networks :)
A:
Pinterest & Instagram use django, i'm sure it's scaleable, for most loaded parts such as activities feed you can use in-memory storage like Redis.
high-load sites on django
Disqus
http://www.slideshare.net/zeeg/djangocon-2010-scaling-disqus
Pinterest
http://www.slideshare.net/eonarts/mysql-meetup-july2012scalingpinterest
Instagram
http://instagram-engineering.tumblr.com/
|
[
"electronics.stackexchange",
"0000410578.txt"
] | Q:
Which way of winding the toroid ferrite ring is correct?
Following my previous question I'm trying to prepare a test to see the effect of a torodial ferrite ring. The setup will be simply as below:
simulate this circuit – Schematic created using CircuitLab
But I'm not sure which way the wires should be wound around the toroid.
Which one below is correct:
Photo 1(wires wound together):
Photo 2(separately wound):
I want to vary the sine wave of the function generator from 1MHz upto 10MegHz and observe the attenuation on scope. If the setup is fine, which way of winding if correct? Photo 1 or Photo 2?
A:
Picture 1 shows the winding for a common mode filter. This will attenuate the sum of the current flowing on the wires. This is useful when something like a PC is sending RF along the mains lead or a USB lead. It will not attenuate differential signals.
Picture 2 shows the winding for a differential mode filter. This will attenute your signal. However, it won't attenuate it very much, as the scope load is so high. The resistive part of the load is 680k, which might as well be infinity compared to 70 ohms.
You've not defined the capacitive part of the scope load. Depending on what you mean by 'scope probe', it could be a few pFs, if it's a good 10:1 probe, it could be around 30pF if it's the basic scope input, it could be 100pF or more if you have a length of 50ohm coax connected to the scope. This is what will cause signal attenuation at high frequencies.
|
[
"stackoverflow",
"0062301871.txt"
] | Q:
Materialize CSS select dropdown arrow displaced
Below is a screen shot of the materialize css as seen from:
https://materializecss.com/select.html
But for some reason, I get the little arrow of the drop down under the list rather than on the side.
I am using Django 3.
How do I fix this?
And the following is the HTML of the rendered page:
<html><head>
<meta name="viewport" content="width = device-width, initial-scale = 1">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js">
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
</script>
</head>
<body class="vsc-initialized">
<nav>
<div class="nav-wrapper">
<a href="#" class="brand-logo right">SIW</a>
<ul id="nav-mobile" class="left hide-on-med-and-down">
<li><a href="/">Home</a></li>
<li><a href="/Contact">Contact</a></li>
</ul>
</div>
</nav>
<div class="section">
<div class="row">
<form class="col s12">
<div class="input-field col s4">
<div class="select-wrapper"><input class="select-dropdown dropdown-trigger" type="text" readonly="true" data-target="select-options-07dbac11-476d-4358-8e69-a8d561e0df80"><ul id="select-options-07dbac11-476d-4358-8e69-a8d561e0df80" class="dropdown-content select-dropdown" tabindex="0" style=""><li class="disabled selected" id="select-options-07dbac11-476d-4358-8e69-a8d561e0df800" tabindex="0"><span>Choose your option</span></li><li id="select-options-07dbac11-476d-4358-8e69-a8d561e0df801" tabindex="0"><span>Option 1</span></li><li id="select-options-07dbac11-476d-4358-8e69-a8d561e0df802" tabindex="0"><span>Option 2</span></li><li id="select-options-07dbac11-476d-4358-8e69-a8d561e0df803" tabindex="0"><span>Option 3</span></li></ul><svg class="caret" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg><select tabindex="-1">
<option value="" disabled="" selected="">Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select></div>
<label>Materialize Select</label>
</div>
</form>
</div>
</div>
<!--JavaScript at end of body for optimized loading-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<div class="hiddendiv common"></div></body></html>
A:
You're using multiple conflicting versions of materialize both 1.0.0 and 0.97.3:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
Select only the 1.0.0 version on both the .css and .js files, for it to work.
Below is a snippet using the HTML code you provided.
<html><head>
<meta name="viewport" content="width = device-width, initial-scale = 1">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
</script>
</head>
<body class="vsc-initialized">
<nav>
<div class="nav-wrapper">
<a href="#" class="brand-logo right">SIW</a>
<ul id="nav-mobile" class="left hide-on-med-and-down">
<li><a href="/">Home</a></li>
<li><a href="/Contact">Contact</a></li>
</ul>
</div>
</nav>
<div class="section">
<div class="row">
<form class="col s12">
<div class="input-field col s4">
<div class="select-wrapper"><input class="select-dropdown dropdown-trigger" type="text" readonly="true" data-target="select-options-07dbac11-476d-4358-8e69-a8d561e0df80"><ul id="select-options-07dbac11-476d-4358-8e69-a8d561e0df80" class="dropdown-content select-dropdown" tabindex="0" style=""><li class="disabled selected" id="select-options-07dbac11-476d-4358-8e69-a8d561e0df800" tabindex="0"><span>Choose your option</span></li><li id="select-options-07dbac11-476d-4358-8e69-a8d561e0df801" tabindex="0"><span>Option 1</span></li><li id="select-options-07dbac11-476d-4358-8e69-a8d561e0df802" tabindex="0"><span>Option 2</span></li><li id="select-options-07dbac11-476d-4358-8e69-a8d561e0df803" tabindex="0"><span>Option 3</span></li></ul><svg class="caret" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg><select tabindex="-1">
<option value="" disabled="" selected="">Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select></div>
<label>Materialize Select</label>
</div>
</form>
</div>
</div>
<!--JavaScript at end of body for optimized loading-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<div class="hiddendiv common"></div></body></html>
|
[
"stackoverflow",
"0013186906.txt"
] | Q:
Regex: Identify phone numbers in different formats
I have a website that people write jokes there. users can send jokes they like to their (or their friends) phones as sms. and the sender of the joke (who has added the joke to the site) displayed below it:
Joke #12234
this is the body of the joke
sender: John
some times people use their phone numbers as the sender name, that is not allowed in public. I want to determine if there is a phone number in the sender name to be able to censor it. I assume any number bigger than 6 digits as a phone number. but the problem is that user might separate the numbers like:
1234567890 should become 1234XXX7890
123 456 7890 should become 123 XXX 7890
123-456-7890
123456-7890
and so on. any of the forms similar to above formats should be censored. I tried removing non numeric characters and then use regular expressions but the problem is then it also fetches:
john23 peterson12345
can anyone offer a better way?
A:
To keep all the formatting, replace
(\d{3}[-\s()]*)\d{3}([-\s()]*\d{4})
with
$1XXX$2
To further constrain for 10-digit numbers (i.e. disallow additional numbers immediately before and after), use negative lookaround assertions:
(?<!\d)(\d{3}[-\s()]*)\d{3}([-\s()]*\d{4})(?!\d)
^^^^^^^ ^^^^^^
Finally, what if typos lead users to insert space or symbols between groups, e.g. (123)45 6-7890? To catch these too, do the following:
(?<!\d)((?:\d[-\s()]*){3})(?:\d[-\s()]*){3}((?:\d[-\s()]*){4})(?!\d)
This may, however, catch "too much," e.g. 1-2-3-4-5-6-7-8-9-0. You will have to determine what balance you want to strike.
|
[
"gaming.meta.stackexchange",
"0000014614.txt"
] | Q:
Minor adjustment to badge description
Shouldn't the description of the gold badge 'Electorate'
Vote on 600 questions and 25% or more of total votes are on questions
be
Vote on 600 questions and answers* and 25% or more of total votes are on questions
?
Logically, the first description is unnecessarily explicit.
(* Preferably with a more concise form of "questions and answers".)
A:
No, that description is correct. You need to vote at least 600 times on questions, and for your votes on questions to be at least 25% of your total votes.
|
[
"askubuntu",
"0000317297.txt"
] | Q:
Compare files script
I am using this script to find information stored in one file using other file as a source for variables to look for:
#!/bin/bash
clear
file=/home/victor/Documentos/Temporal/13-06-04_Cuentas_para_revisar_cajas.txt
while IFS= read -r line
do
echo $line
cat Inventory.csv | grep "$line" >> cuentasxcajas.txt
done < $file
echo "done"
but the file cuentasxcajas.txt is empty, any suggestions?
A:
If I had your task to do, I would proceed thus:
grep -f '/home/victor/Documentos/Temporal/13-06-04_Cuentas_para_revisar_cajas.txt' -- Inventory.csv > cuentasxcajas.txt
No need for a Bash script, of for loops of for useless uses of cats. Just make sure you don't have empty lines in the file /home/victor/Documentos/Temporal/13-06-04_Cuentas_para_revisar_cajas.txt.
|
[
"stackoverflow",
"0021433195.txt"
] | Q:
How to find DataTemplate-Generated UIElement
Hi i try to find the generated UIElement from a DataTemplate
but i'm not able to find my UserControl which should be somewhere in my ContentPresenter
i looked in to the control via a Breakpoint and Snoop but i cant find the UserControl
can someone please enlight where i can find it?
Here my Test Project:
App XAML
<Application.Resources>
<DataTemplate x:Name="TESTTemplate" DataType="{x:Type vmv:VM}">
<vmv:MyView/>
</DataTemplate>
</Application.Resources>
View
<UserControl ...>
<DataGrid ItemsSource="{Binding MyItems}"/>
</UserControl>
VM
public class VM
{
private ObservableCollection<MyRow> myItems;
public ObservableCollection<MyRow> MyItems
{
get { return myItems; }
set { myItems = value; }
}
public VM()
{
myItems = new ObservableCollection<MyRow>();
myItems.Add(new MyRow { Text = "a", Number = 1 });
myItems.Add(new MyRow { Text = "s", Number = 2 });
myItems.Add(new MyRow { Text = "d", Number = 3 });
myItems.Add(new MyRow { Text = "f", Number = 4 });
}
}
public class MyRow
{
public string Text { get; set; }
public int Number { get; set; }
}
MainWindow XAML
<Window x:Class="MyPrinterAPI.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<ContentPresenter Name="CPresenter">
</ContentPresenter>
</StackPanel>
</Window>
CodeBehind
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var vm = new VM();
DataContext =vm;
CPresenter.Content = vm;
}
}
A:
VisualTreeHelper can get you UserControl but like you mentioned in another answer, you want to know where exactly this property is set.
You can get that using Reflection which is set on private field _templateChild like this. But still i would suggest use VisualTreeHelper to get that.
var userControl = typeof(FrameworkElement).GetField("_templateChild",
BindingFlags.Instance | BindingFlags.NonPublic).GetValue(CPresenter);
|
[
"meta.stackexchange",
"0000228256.txt"
] | Q:
Why did my custom flag on a comment placed as answer get declined?
I just got my custom flag on this answer declined for the well known reason
"flags should not be used to indicate technical inaccuracies, or an altogether wrong answer"
My custom message was
It does not answer the question (at the most it should be a comment to the related answer) but even then it does not change any functionality whatsoever.
I don't see why this should be declined, certainly with an explanation.
The code he suggests alteration to is part of another answer
The change he suggests is literally swapping a synonym
I provided the second reason to make it clear that no value would be lost by simply deleting instead of converting it to a comment (otherwise everyone might just as well quote MSDN for reasons unrelated to answering the question since that is what he basically does).
Regardless of this second reason, the first one is a direct comment to another answer and has no value by itself.
Take for example this post:
A wrong answer is a technical inaccuracy.
The technical correctness of an answer is judged through votes. Moderators (and therefore flagging for moderator attention) are for problems with an answer other than its technical accuracy, such as whether it is offensive, not even an attempt to answer the question, etc.
I believe from this reason I can deduce that this was not even an attempt to answer the question. Just because it is put in the answer section, doesn't make it an answer.
Why was the flag declined, considering all this?
A:
While you used a custom "Other" flag that said:
It does not answer the question (at the most it should be a comment to the related answer) but even then it does not change any functionality whatsoever.
How are we supposed to know what the related answer is? You didn't provide any other details to us.
I declined the flag because it does appear to be an answer. Please give as many details as possible when flagging items as "Other" for us, including a link to the post you think it is a comment on. These things are incredibly helpful when processing the flags.
If your flag said:
It does not answer the question (at the most it should be a comment to this answer insert link here)
Then I would have been much more inclined to mark it as helpful. The more details the better.
A:
That post has been flagged as "not an answer" many times over the past year, and each time the flag has been either declined or disputed. This might have influenced the moderator's decision when your flag was processed.
The problem with flagging this post as "not an answer" is that in isolation, it looks like an answer, so a moderator is probably just going to decline the flag and move on to the next one.
You were right, of course. That "answer" was not a reply to the question (it points out a change to code that appears in another answer, not the question), so you were right to flag it with a custom flag explaining the problem. As already pointed out, it would have been even more helpful to use the "Other" text box to tell moderators which answer the flagged post was a reply to. That makes it easier for us to process the flag quickly and accurately.
Since the corrective action suggested by this post was already taken in the other answer, I went ahead and deleted the flagged post.
|
[
"stackoverflow",
"0034730170.txt"
] | Q:
table division text dissapears after validation is run on submit
In my razor page I've got several check boxes arranged in a table. I've got some other @Html.EditorFor elements that are required inputs. When I submit, and the validations are run, the page refreshes with the eoor messages and the text next to my check boxes in the table disappears. What's up with that?
My checkboxes are made with @Html.CheckBoxFor
I'm not using any special stylings or class attributes or anything right now.
A:
You are correct. When the form is posted, you will lose all of that data provided you do not resend it back into your view. In your controller, you need to return the model along with the view. Without seeing your code, I can't give a specific answer but it should look something like this:
public ActionResult DoSomethingWithFormPostData(Model yourModel)
{
//Do whatever you need to do.
return PartialView("_yourView", model);
}
Alternatively, I like to have a method in my controllers to I use for the sole purpose of populating a page. If you have something like that, you can refer back to that sending the model as a routevalue in this way:
public ActionResult DoSomethingWithFormPostData(Model yourModel)
{
//Do whatever you need to do.
return RedirectToAction("_yourView", "YourController", model);
}
|
[
"stackoverflow",
"0009527719.txt"
] | Q:
Eclipse JAD result
I have a very basic question. When I decompile any java class using JAD in eclipse I can find that it there are comment lines like. What does this mean? and how to reference one class in another in eclipse.
//Referenced classes of package <package name>:
// DetailedLoginException
Thanks!!
A:
I think it lists the classes of the package <package name> which are being referenced/used by this class(decompiled class). And the <package name> is also same as the decompiled class's package. Like in following example Assert and ComparisonFailure both belongs to org.junit package.
package org.junit;
import org.hamcrest.*;
.....
// Referenced classes of package org.junit:
// ComparisonFailure
public class Assert
{
|
[
"stackoverflow",
"0023153255.txt"
] | Q:
Forcefully download converted image from text input
Here i am trying to convert text to png image ,text entered by the user in input box and on submit button i am converting image ,the image converting properly working but i am not able download that image png file which is converted.The force download downloading the conversion.php file insted of .png image.
click here demo link
When i use the only header("Content-type: image/png");
instead of
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=").$im.("png ");
header("Content-Transfer-Encoding: binary ");
Its display the image on browser.
Check out converted image snap shot.
(conversion.php)Below is the sample code for text to image conversion.
<?php
### Declare this script will be displayed as a PNG image.
header("Content-type: image/png");
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=").$im.("png ");
header("Content-Transfer-Encoding: binary ");
if (isset($_POST['convert'])) {
$username = $_POST['text'];
$fsize = $_POST['size'];
$fsize=200;
if(strlen($username)<=6){
####################### BEGIN USER EDITS #######################
$imagewidth = 1200;
$imageheight = 600;
$fontsize = $fsize;
$fontangle = "0";
$font = "ByzantineEmpire.ttf";
$text = $username;
$backgroundcolor = "003366";
$textcolor = "black";
######################## END USER EDITS ########################
### Convert HTML backgound color to RGB
if( eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $backgroundcolor, $bgrgb ) )
{$bgred = hexdec( $bgrgb[1] ); $bggreen = hexdec( $bgrgb[2] ); $bgblue = hexdec( $bgrgb[3] );}
### Convert HTML text color to RGB
if( eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $textcolor, $textrgb ) )
{$textred = hexdec( $textrgb[1] ); $textgreen = hexdec( $textrgb[2] ); $textblue = hexdec( $textrgb[3] );}
### Create image
$im = imagecreate( $imagewidth, $imageheight );
## Declare image's background color
$bgcolor = imagecolorallocate($im, $bgred,$bggreen,$bgblue);
### Declare image's text color
$fontcolor = imagecolorallocate($im, $textred,$textgreen,$textblue);
### Get exact dimensions of text string
$box = @imageTTFBbox($fontsize,$fontangle,$font,$text);
### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);
### Get height of text from dimensions
$textheight = abs($box[5] - $box[1]);
### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth/2)-($textwidth/2)-2;
### Get y-coordinate of centered text vertically using height of the image and height of the text
$ycord = ($imageheight/2)+($textheight/2);
### Declare completed image with colors, font, text, and text location
imagettftext ( $im, $fontsize, $fontangle, $xcord, $ycord, $fontcolor, $font, $text );
### Display completed image as PNG
imagepng($im);
### Close the image
imagedestroy($im);
}
}
?>
A:
As per OP's Request
try changing
header("Content-Disposition: attachment;filename=").$im.("png ");
to
header("Content-Disposition: attachment;filename=".$im.".png");
looks like you forgot to declare the $im variable as well.
|
[
"stackoverflow",
"0056536232.txt"
] | Q:
format option text based on condition
I am trying to format the option text based on certain condition. I have tried several ways but doesn't seem to be working. For a workaround I could use jquery and populate the option list based on condition but trying to do it without adding more code. Any help would be appreciated. Thanks in advance.
<option value="fooditem_size1">{{selectedFoodItem.fooditem_size1_name}}
<span ng-if="selectedFoodItem.fooditem_size1_price > 0"> +
${{selectedFoodItem.fooditem_size1_price}}
</span>
</option>
A:
Use a ternary operator:
<option value="fooditem_size1">
{{selectedFoodItem.fooditem_size1_name +
(selectedFoodItem.fooditem_size1_price > 0) ?
( ' + $' + selectedFoodItem.fooditem_size1_price ) : "" }}
</option>
The only permitted content of an <option> element is text, possibly with escaped characters (like é).
For more information, see
MDN HTML Reference - <option>
|
[
"stackoverflow",
"0015785479.txt"
] | Q:
How do i get a list of users in active directory using .NET?
I want to get a list of users in active directory. How would i achieve this in asp.net?
What objects and functions are invloved. Has anyone got any sample code?
A:
I don't have any sample code right now, but I think using an external text file would do.
You can store your data in a normal .txt file or XML file. I usually use XML file for storing data in the project's directory.
Tutorials for reading and writing XML files are all over the internet for C#. Just search on Google!
Good Luck!
|
[
"stackoverflow",
"0037835179.txt"
] | Q:
How can I specify the function type in my type hints?
I want to use type hints in my current Python 3.5 project. My function should receive a function as parameter.
How can I specify the type function in my type hints?
import typing
def my_function(name:typing.AnyStr, func: typing.Function) -> None:
# However, typing.Function does not exist.
# How can I specify the type function for the parameter `func`?
# do some processing
pass
I checked PEP 483, but could not find a function type hint there.
A:
As @jonrsharpe noted in a comment, this can be done with typing.Callable:
from typing import AnyStr, Callable
def my_function(name: AnyStr, func: Callable) -> None:
Issue is, Callable on it's own is translated to Callable[..., Any] which means:
A callable takes any number of/type of arguments and returns a value of any type. In most cases, this isn't what you want since you'll allow pretty much any function to be passed. You want the function parameters and return types to be hinted too.
That's why many types in typing have been overloaded to support sub-scripting which denotes these extra types. So if, for example, you had a function sum that takes two ints and returns an int:
def sum(a: int, b: int) -> int: return a+b
Your annotation for it would be:
Callable[[int, int], int]
that is, the parameters are sub-scripted in the outer subscription with the return type as the second element in the outer subscription. In general:
Callable[[ParamType1, ParamType2, .., ParamTypeN], ReturnType]
A:
Another interesting point to note is that you can use the built in function type() to get the type of a built in function and use that.
So you could have
def f(my_function: type(abs)) -> int:
return my_function(100)
Or something of that form
|
[
"stackoverflow",
"0007523179.txt"
] | Q:
Is there a way to check if jQuery has already been attached to an html page?
I have some jQuery which will be put on multiple different HTML pages which I have no clue whether they will have the jQuery Library attached or not. I would like to make it so that it does not load the library if it does already exist on the page so that it can be faster, but I can't figure out if there is a way to check for whether the library already is attached to the page.
Is there a way?
A:
From HTML5 Boilerplate:
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.6.4.min.js"><\/script>')</script>
Loads a local jQuery file if it hasn't already been loaded.
|
[
"stackoverflow",
"0005741699.txt"
] | Q:
Attribute assignment to built-in object
This works:
class MyClass(object):
pass
someinstance = MyClass()
someinstance.myattribute = 42
print someinstance.myattribute
>>> 42
But this doesn't:
someinstance = object()
someinstance.myattribute = 42
>>> AttributeError: 'object' object has no attribute 'myattribute'
Why? I've got a feeling, that this is related to object being a built-in class, but I find this unsatisfactory, since I changed nothing in the declaration of MyClass.
A:
Python stores attributes in a dict. You can add attributes to MyClass, see it has a __dict__:
>>> class MyClass(object):
>>> pass
>>> dir(MyClass)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
The important difference is that object has no __dict__ attribute.
>>> dir(object)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
More detailed explanations:
Can't set attributes of object class
Why can't you add attributes to object in python?
A:
As for the rationale behind this, the words of the BDFL himself:
This is prohibited intentionally to prevent accidental fatal changes
to built-in types (fatal to parts of the code that you never though
of). Also, it is done to prevent the changes to affect different
interpreters residing in the address space, since built-in types
(unlike user-defined classes) are shared between all such
interpreters.
|
[
"stackoverflow",
"0007487642.txt"
] | Q:
How can I follow a particular CPAN module's updates?
I subscribe to the CPAN weekly update mailing list but it reports on every module updated in the past week.
Instead, I would like to subscribe to particular modules and get only their updates. I want to "follow" that module for the purposes of reviewing interesting fixes/enhancements and choosing when I want to upgrade.
The mailing list is too much info to wade through.
How can I follow/subscribe to a particular CPAN module's updates?
A:
Write a Perl script to do it!
Schedule the script to parse the CPAN Changes Feed daily and then have the script mail you the details of any changes to the modules you are interested in.
A:
I found about CPAN-Outdated just the other day.
|
[
"stackoverflow",
"0045266826.txt"
] | Q:
PHP Get Page Not Working
if (isset($_GET['page']) && $_GET['page'] == 'myProfile') { // Account Profile
$page = 'myProfile';
} else { // Dashboard
$page = 'dashboard';
}
if (isset($_GET['page']) && $_GET['page'] == 'coupon') { // Settings
$page = 'settings';
} else { // Dashboard
$page = 'dashboard';
}
The code above,
If i go to ?page=myProfile it leads to the dashboard rather myProfile same for the settings one?
There is code further down that leads myProfile to the .php file etc.
If i remove the 2nd bit of the code (settings) the account profile bit works?
This is using a framework called FrameWorx
A:
Second if rewrites value of $page which has been set in previous if. Change your ifs to this, for example:
if (isset($_GET['page']) && $_GET['page'] == 'myProfile') {
$page = 'myProfile';
} elseif (isset($_GET['page']) && $_GET['page'] == 'coupon') {
$page = 'settings';
} else {
$page = 'dashboard';
}
|
[
"english.stackexchange",
"0000194243.txt"
] | Q:
What's the difference between "I'm happy" and "I have a happy heart"?
What's the difference? Could you say that romantically? About an infant?
A:
I'm happy is a simple sentence that expresses the state of mind of the person (Subject) at that particular instance. There will be a specific reason behind the happiness expressed on the sentence.
For example: I am happy to know that you got state first in board exams.
I have a happy heart is poetic self explanation of his character by the Subject (I). This expresses that the person is easy going and he doesn't have any stress or hard feelings dumped on his mind. A state of peace.
For example: I have a happy heart despite the serious problems in my life.
|
[
"stackoverflow",
"0037083251.txt"
] | Q:
Django - why is edit form posting to edit url + create url on top of each other?
I'm reusing my 'create' form for an edit view. 'Create' routing works just fine, but when the 'edit' form is submitted, my terminal says it tries to POST /comment/edit/26/comment/add/.
I was trying a custom class view, so then switched to just generic UpdateView:
class CommentUpdate(UpdateView):
model = Comment
fields = ['title']
and still the same thing. So I figure maybe it's a problem with the ModelForm or with urls?
Here's forms.py
from django import forms
from comments.models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
etc. -- the form itself looks like this:
<form id="new-form" role="form" method="post">
{% csrf_token %}
<p>{{ form.title }}</p>
<p>
<button type="submit">Submit</button>
<a href="/">Cancel</a>
</p>
</form>
aaand urls.py:
from django.conf.urls import url
from django.contrib import admin
from ratings.views import (home, CommentCreate, CommentUpdate)
urlpatterns = [
url(r'^$', home, name='comment-home'),
url(r'comment/add/$', CommentCreate.as_view(), name='comment-add'),
url(r'comment/edit/(?P<pk>\d+)/$', CommentUpdate.as_view(), name='comment-edit')
]
So I've read that a form has its action set automatically to the view that rendered it. Looks like it gets that (/comment/edit/26/) but then every time chucks comment/add/ on the end too. Don't know where else to look.
A:
You need to anchor your URL patterns at the start.
url(r'^comment/add/$', CommentCreate.as_view(), name='comment-add'),
url(r'^comment/edit/(?P<pk>\d+)/$', CommentUpdate.as_view(), name='comment-edit')
|
[
"gaming.stackexchange",
"0000214273.txt"
] | Q:
How to increase the bus density?
I've noticed that on some of my bus lines, there are not enough buses to deal with all passengers. What can I do to increase the throughput of a bus line?
Add more stops? Remove stops? Replace long bus-lines with multiple shorter ones? Create multiple bus-lines which intersect? Build more bus depots? Allocate more budget to buses?
A:
If you don't mind using mods, there are some of them that deals with that problem. I would recommend using Improved Public Transport that gives you more control over your transport lines.
This mods allows to set the capacity for each kind of public transport and to manage the number of vehicles for each line.
As you increase the vehicles' capacities, the maintenance cost are also increased accordingly.
Alternatives to this mod :
Configurable Transport Capacity
Improved Transport Capacity (deprecated)
A:
Since the free update which came with the release of the Public Transportation DLC you can now adjust the budget of bus lines (or any kind of public transportation line, for that matter) individually, which will affect the number of vehicles used on that line.
Open the "Transport" map mode
Click on "Lines Overview"
Click on the magnifying glass next to the line you want to adjust
Use the "vehicle count modifier" slider to assign more or less budget to the line, resulting in more or less vehicles.
Keep in mind that it uses the mechanic of the regular budget panel: the further you go away from 100% (in either direction), the more you pay for each vehicle. So if you feel the need to crank it up a lot, it might be better to add more bus lines instead.
|
[
"stackoverflow",
"0001152875.txt"
] | Q:
Problem passing dates to a webservice method (SqlDateTime overflow)
I have a VS2008 solution containing two projects, a web service (the actual work I'm doing) and a web application (that I'm using to test the service). The latter has a "web reference" to the former. It is also set as the startup project, so that when I start debugging VS sets up two ports on localhost, one for the app (which runs its default.aspx) and one for the service.
The service code in events.asmx.cs has the following:
public class events : System.Web.Services.WebService
{
/* various object classes specific to service */
[WebMethod]
public List<EventItem> GetEvents(DateTime From, DateTime To, string[] EventType)
{
EventsDataContext dc = new EventsDataContext();
List<EventsMain> events = dc.EventsMains
.Where(ev => ev.EventStartDate >= From
&& ev.EventEndDate < To
&& ev.Live == true
&& ev.IsOnWebsite == true
)
.ToList();
}
}
It is intentional that the last parameter (EventType) is not currently used.
The EventsMain class is from the data context, and is representing a table that has a whole load of fields, of which in this case the LINQ query is assessing the values of a couple of BIT fields and two DATETIME fields. It's supposed to return a list of events based on the provided criteria.
In the web application, I have this code in the default.aspx code-behind to call the above method:
protected void Page_Load(object sender, EventArgs e)
{
events eventService = new events();
DateTime from = new DateTime(2009, 1, 1, 10, 0, 0);
DateTime to = new DateTime(2009, 2, 1, 10, 0, 0);
EventItem[] eventList = eventService.GetEvents(from, to, new string[] { });
}
That last line (which calls the webservice method) fails, with the following error:
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
When debugging, at the point just before the webservice method call, the DateTime variables look fine. Stepping into the method, even before the LINQ statement, the From and To parameters appear to have ended up as the C# DateTime.MinValue, which obviously is well below the SQL Server minimum datetime value.
Changing the from and to variables to other dates before calling the method appears to have no effect.
So the question is: What am I doing wrong currently, and what should I be doing for these dates to cross the webservice interface correctly?
A:
Is it possible that you've changed the interface of your method slightly and not updated the web reference? It looks like you've renamed the From and To parameters but are still using an out of date proxy class.
Try updating the web reference.
|
[
"superuser",
"0001117698.txt"
] | Q:
Tunneling git through ssh (to get past a firewall): port specification interperted as relative path?
I have access to server A via ssh, and from server A can access server B, which runs gitlabs and contains the repository I need access to. When I am ssh'd into server A, I can run git clone http://serverB/path/to/repo.git successfully. Using ssh:// or git:// instead of http:// does not work. (Errors are "does not appear to be a git repository" and "unable to connect to serverB," respectively.)
If I set up a tunnel like this:
ssh username@serverA -L 3333:serverB:80 -N
The following two attempts at git clones fail:
git clone http://localhost:3333/path/to/repo.git
Fails with: "fatal: repository not found"
git clone localhost:3333/path/to/repo.git
Prompts me for my password for serverB, and then fails with "fatal: 3333/path/to/repo.git does not appear to be a git repository." Of course, it isn't! My attempt at specifying localhost, port 3333, is clearly being interpreted as a relative path on serverB.
Is there a way to fix this? Is something fundamentally wrong with this approach?
A:
Why does it not work
http://localhost:3333/path/to/repo.git
This fails because the URL's hostname is different (localhost vs server2), and as a result the server uses a different configuration.
All HTTP clients send the requested hostname to the server, and the server may choose from several configurations (virtual hosts) based on that name. This is how many websites (often hundreds) can share the same IP address at a hosting provider.
localhost:3333/path/to/repo.git
This fails because it's not an HTTP URL, or in fact any URL at all. (Git is not a web browser and doesn't assume http:// by default.)
Instead it's an rcp-style SSH address in the form [user@]host:path. You might have seen it earlier as [email protected]:foo/bar.git, where the ssh@ prefix is really just a SSH username.
Git treats it as equivalent to ssh://[user@]host[:port]/path URLs, except the rcp-style addresses do not have a port field at all.
What to do
curl, the HTTP client used by Git, supports SOCKS proxies as provided by ssh -D dynamic tunnel.
Set up a dynamic (SOCKS) tunnel with:
ssh username@serverA -D 1080 -N
Configure Git to use it as a proxy:
Globally (or per-repository):
git config [--global] http.proxy socks5://localhost:1080
For a single command:
git -c http.proxy=socks5://localhost:1080 clone http://serverB/repo.git
The socks5 and socks4 protocols perform DNS resolution on the client side, while socks5h and socks4a pass all hostnames through SOCKS to the SSH server.
|
[
"stackoverflow",
"0047582081.txt"
] | Q:
update one table with 2 where conditions in the same and one condition in another table
I have 2 tables fees and students. i want to update one field of fees with 3 WHERE conditions, i.e, 2 conditions in table 'fees' and 1 condition in table 'students'.
I tried many queries like
UPDATE fees, students SET fees.dues= 300 WHERE fees.month= November
AND fees.session= 2017-18 AND students.class= Nursery
It gives me error like java.sql.SQLException: near",": syntax error
I am using sqlite as database. Please suggest me a query or let me correct this query.
Thanks
A:
You cannot join tables in a UPDATE command in SQLite. Therefore, use a sub-query in the where condition
UPDATE fees
SET dues = 300
WHERE
month = November AND
session = 2017-18 AND
student_id IN (SELECT id FROM students WHERE class=Nursery)
Also, I am not sure about the types of your columns. String literals must be enclosed in single quotes ('). The expression 2017-18 would yield the number 2017 minus 18 = 1999. Should it be a string literal as well?
UPDATE fees
SET dues = 300
WHERE
month = 'November' AND
session = '2017-18' AND
student_id IN (SELECT id FROM students WHERE class='Nursery')
|
[
"pt.stackoverflow",
"0000467412.txt"
] | Q:
Posicionar icone do Material dentro de tag span
Faaala meus queridos, estou tentando posicionar um icone dentro e no cantro superior direito de um elemento, porém quando aplico right: 0; meu icone some. Algum mestre dos magos do css por aí?
.btn-redirect {
display: block;
text-align: left;
font-size: 16px;
color: #000;
line-height: 50px;
border-left: 3px solid #7455D4;
margin-bottom: 10px;
background-color: #f5f5f5;
box-shadow: 0 1px 1px 0 rgba(0,0,0,.14), 0 1px 0 -3px rgba(0,0,0,.12), 0 0 2px 0 rgba(0,0,0,.2);
transition: box-shadow .25s;
border-radius: 3px;
padding: 16px;
}
.icons {
position: absolute;
}
.icons span.material-icons {
color: #5622AC;
position: absolute;
z-index: 100;
/* right: 0; Icone desaparece ao aplicar isso.*/
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<div class="col s12 m3 l3">
<div class="icons"><span id="individual" class="material-icons">error_outline</span></div>
<a id="btn-individual" class="btn-redirect waves-effect waves-light" target="_blank">
DF Individual
</a>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
https://jsfiddle.net/joaofds/u149jtz3/104/
A:
No elemento pai vc deve colocar position: relative e ter um tamanho fixo nele, e o elemento que vc quer posicionar deve estar como position: absolute;
https://jsfiddle.net/2xr46an0/
Mudei um pouco a estrutura do seu elemento, ela ficou assim:
<div class="col s12 m3 l3">
<a id="btn-individual" class="btn-redirect waves-effect waves-light" target="_blank">
DF Individual
<div class="icons"><span id="individual" class="material-icons">error_outline</span></div>
</a>
</div>
e no css adicionei:
#btn-individual {
position: relative;
}
.icons {
position: absolute;
top: 0;
right: 0;
}
|
[
"stackoverflow",
"0016309302.txt"
] | Q:
Why is strange CSS Background image transition happening?
I ran into an interesting thing in chrome today. I had a transition set to change between 2 background images, and it works, but with interesting results. I made a pen to illustrate the issue:
http://codepen.io/anon/pen/LmkJG
It happens to fit well with what I was trying to accomplish, but I don't know why this is happening. I'd be happy if someone could explain it to me.
A:
My assumption is that it's applying a transition between the two background image sizes. Since one background image is larger than the other, it's transforming one image to the dimensions of the other, while at the same time fading it out.
To eliminate the transformation of the height/width on the image, just make both images the same dimensions.
|
[
"drupal.stackexchange",
"0000263967.txt"
] | Q:
How to render a form in custom template?
I'm looking to add a form inside a custom template. The form, if I open the path registered inside the file cmodule.routing.yml, works but if i try to use it inside a custom template it doesn't work: with a dump(form) or dump(form.anyfield) i get NULL.
cmodule.routing.yml:
cmodule.manageform:
path: '/cmodule/manageform'
defaults:
_title: 'Documents'
_form: '\Drupal\cmodule\Forms\RequestForm'
requirements:
_permission: 'access content'
cmodule.manage:
path: '/cmodule/manage'
defaults:
_controller: '\Drupal\cmodule\Controller\CmoduleController::manageAction'
_title: 'Custom Documents'
requirements:
_permission: 'access content'
RequestForm.php:
/**
* {@inheritdoc}
*
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['type'] = array(
'#type' => 'radios',
'#options' => array(
'0' =>t('DOC'),
'1' =>t('PDF')
),
);
$form['pid'] = array(
'#type' => 'textfield',
'#title' => t('ID:'),
'#required' => FALSE
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Submit'),
'#attributes'=> ['class'=>['glyphicon', 'glyphicon-search']],
);
return $form;
}
cmodule.module:
/**
* Implements hook_theme().
*/
function cmodule_theme(){
$templates = array(
'manage_cmodule_page' => array(
'variables' =>
[
'id' => NULL,
'form' => NULL
],
'template' =>'manage_cmodule',
'render element' => 'form'
)
);
return $templates;
}
the controller contains:
public function manageAction() {
$id = 1;
$form = \Drupal::formBuilder()->getForm('Drupal\cmodule\Forms\RequestForm');
$form['type']['#title_display'] = 'invisible';
return [ '#theme' => 'manage_cmodule_page',
'#form' => $form,
'#id' => $id,
];
}
and then the template/view (contains):
<div>
{{ form.form_token }}
{{ form.form_build_id }}
{{ form.form_id }}
{{form.type}}
{{form.submit}}
</div>
etc..
But as I said above the template doesn't show the form, but show (if i print it) the #id value passed through the controller.
Do you have any suggestions?!
UPDATE #1
I tried also to follow the suggestion of Beebee, and then this and this so the code is:
controller:
controller contains:
public function manageAction() {
$form = \Drupal::formBuilder()->getForm('Drupal\cmodule\Forms\RequestForm');
$render['#form'] = $form;
$render['theme'] = 'manage_cmodule_page';
return $render;;
}
and the implementation of hook_theme in .module file is:
return [
'manage_cmodule_page' => [
'template' =>'manage_cmodule',
'render element' => 'form',
]
];
The result is an empty page with an error inside the apache log:
[php7:error] [pid 12660:tid 1592] [client ::1:59521] PHP Fatal error:
Out of memory (allocated 270532608) (tried to allocate 266354688
bytes) in
C:\drupal\vendor\twig\twig\lib\Twig\Extension\Debug.php on
line 60, referer: http://localhost/drupal/
if I remove the following row from the controller
$render['theme'] = 'manage_atps_page';
the page loads, but it is empty (without any form).
UPDATE #2
I fixed my issue following also the idea of Alex Kuzava. Thus I used the code of UPDATE 1, with the new directory of the form, and then I added these 3 lines inside the part of my template (otherwise the submit button doesn't work).
{{ form.form.form_build_id }}
{{ form.form.form_id }}
{{ form.form.form_token }}
A:
'render element' => 'form'
Your render element is form which means all provided variables will be passed there.
In your twig template you can render your form like here
<div>{{ form.form }}</div>
UPDATE #1
Wow man, you have wrong namespace Drupal\cmodule\Forms\RequestForm
Should be Drupal\cmodule\Form\RequestForm
Please rename Forms to Form (the same for directory) and clear cache. It should help you.
|
[
"stackoverflow",
"0055185021.txt"
] | Q:
Error with NLTK package and other dependencies
I have installed the NLTK package and other dependencies and set the environment variables as follows:
STANFORD_MODELS=/mnt/d/stanford-ner/stanford-ner-2018-10-16/classifiers/english.all.3class.distsim.crf.ser.gz:/mnt/d/stanford-ner/stanford-ner-2018-10-16/classifiers/english.muc.7class.distsim.crf.ser.gz:/mnt/d/stanford-ner/stanford-ner-2018-10-16/classifiers/english.conll.4class.distsim.crf.ser.gz
CLASSPATH=/mnt/d/stanford-ner/stanford-ner-2018-10-16/stanford-ner.jar
When I try to access the classifier like below:
stanford_classifier = os.environ.get('STANFORD_MODELS').split(':')[0]
stanford_ner_path = os.environ.get('CLASSPATH').split(':')[0]
st = StanfordNERTagger(stanford_classifier, stanford_ner_path, encoding='utf-8')
I get the following error. But I don't understand what is causing this error.
Error: Could not find or load main class edu.stanford.nlp.ie.crf.CRFClassifier
OSError: Java command failed : ['/mnt/c/Program Files (x86)/Common
Files/Oracle/Java/javapath_target_1133041234/java.exe', '-mx1000m', '-cp', '/mnt/d/stanford-ner/stanford-ner-2018-10-16/stanford-ner.jar', 'edu.stanford.nlp.ie.crf.CRFClassifier', '-loadClassifier', '/mnt/d/stanford-ner/stanford-ner-2018-10-16/classifiers/english.all.3class.distsim.crf.ser.gz', '-textFile', '/tmp/tmpaiqclf_d', '-outputFormat', 'slashTags', '-tokenizerFactory', 'edu.stanford.nlp.process.WhitespaceTokenizer', '-tokenizerOptions', '"tokenizeNLs=false"', '-encoding', 'utf8']
A:
I found the answer for this issue. I am using NLTK == 3.4. From NLTK ==3.3 and above Stanford NLP (POS, NER , tokenizer) are not loaded as part of nltk.tag but from nltk.parse.corenlp.CoreNLPParser. The stackoverflow answer is available in stackoverflow.com/questions/13883277/stanford-parser-and-nltk/… and the github link for official documentation is github.com/nltk/nltk/wiki/Stanford-CoreNLP-API-in-NLTK.
Additional information if you are facing timeout issue from the NER tagger or any other parser of coreNLP API, please increase the timeout limit as stated in https://github.com/nltk/nltk/wiki/Stanford-CoreNLP-API-in-NLTK/_compare/3d64e56bede5e6d93502360f2fcd286b633cbdb9...f33be8b06094dae21f1437a6cb634f86ad7d83f7 by dimazest.
|
[
"stackoverflow",
"0016031812.txt"
] | Q:
Lazy, overloaded C++ && operator?
I'm trying to implement my own boolean class, but cannot replicate native semantics for &&. The following contrived code demonstrates the issue:
#include <iostream>>
class MyBool {
public:
bool theValue;
MyBool() {}
MyBool(bool aBool) {theValue = aBool;}
MyBool operator&& (MyBool aBool) {return theValue && aBool.theValue;}
};
bool f1() {std::cout << " First\n"; return false;}
bool f2() {std::cout << " Second\n"; return false;}
int main(int argc, char** argv) {
std::cout << "Native &&\n";
f1() && f2();
std::cout << "Overloaded &&\n";
MyBool(f1()) && MyBool(f2());
return 0;
}
When compiled and run, the result is:
Native &&
First
Overloaded &&
Second
First
In other words, && on bools is lazy (as any C++ programmer would expect) but the overloaded && isn't (as this C++ programmer at least didn't expect).
Is there a way to make overloaded && lazy? I can find various full-on lazy evaluation schemes to provide Haskell-like functionality, but they seem like complete overkill for my use case.
A:
You should not overload bool operator&&, since you lose short circuit evaluation, as you have discovered.
The correct approach would be to give your class a bool conversion operator
class MyBool {
public:
bool theValue;
MyBool() {}
MyBool(bool aBool) : theValue(aBool) {}
explicit operator bool() { return theValue; }
};
Note that explicit conversion operators require C++11 compliance. If you do not have this, have a look at the safe bool idiom.
A:
Is there a way to make overloaded && lazy?
No.
|
[
"stackoverflow",
"0045698552.txt"
] | Q:
Run shell command with "redirecting of an output from a subshell" statement within go
According to run bash command in new shell and stay in new shell after this command executes, how can I run command:
bash --rcfile <(echo "export PS1='> ' && ls")
within golang? I've tried many combinations of exec.Command() but they did't work. For example:
exec.Command("bash", "--rcfile", `<("echo 'ls'")`)
I've also read this os, os/exec: using redirection symbol '<' '>' failed, but I think maybe my case is a bit more complicated.
A:
You're almost there - I think the confusion is you're using piping to call bash, which means you actually need to call bash using bash:
exec.Command("bash", "-c", `bash --rcfile <(echo "export PS1='> ' && ls")`)
|
[
"stackoverflow",
"0018455889.txt"
] | Q:
unexpected T_String when adding "get_the_excerpt" to single.php
When I add
<?php $excerpt = get_the_excerpt() ?>
to the single page php code below, I get "Parse error: syntax error, unexpected T_STRING on line 10"
<?php get_header(); ?>
<div class="post"><?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php post_class('margin') ?> id="post-<?php the_ID(); ?>">
<div class="casestudy"><a class="anchor-hover">
<?php echo get_the_post_thumbnail( $post->ID ); ?>
<span class="details">
<p class="desc"><?php $excerpt = get_the_excerpt() ?>
</p>
</span>
</a>
<?php the_content(); ?>
</div>
<?php endwhile; endif; ?>
</div>
<?php get_footer(); ?>
My functions.php file originally did not have
add_filter( 'get_the_excerpt', 'wp_trim_excerpt');
so I added that but I still get the error. What am I missing here? Have I taken it out of the loop?
A:
I believe you forgot the ; at the end there.
I'm also curious as to why you are simply setting the variable in a <p> instead of maybe echoing it?
|
[
"economics.stackexchange",
"0000005304.txt"
] | Q:
Question about the Ellsberg Paradox in Expected Utility Theory
The von Neumann-Morgenstern theorem states that, assuming a person's preferences under risk satisfy certain rationality axioms, then there exists a utility function u, the von Neumann utility function, such that the person will tend to maximize the expected value of u. For this reason, the hypothesis that people satisfy the von Neumann-Morgenstern rationality axioms is known as expected utility theory. Now one of the major challenges for expected utility theory is the Ellsberg Paradox. It goes as follows.
Suppose you have an urn which has a total of 90 balls, 30 of which are red and each of the other 60 balls is either black or yellow. And suppose a ball is drawn at random from the urn. Then would you rather have lottery A, where you get 100 dollars if a red ball is drawn, or lottery B, where you get 100 dollars if a black ball is drawn? Most people would prefer lottery A. And would you rather have lottery C, where you get 100 dollars if you draw a red or yellow ball, or lottery D, where you get 100 dollars if you draw a black or yellow ball? Most people would prefer lottery D. But the thing is, preferring both lottery A to lottery B and lottery D to lottery C is inconsistent with expected utility theory; see this Wikipedia article for the proof.
I'd like to understand this logic a little better. Consider a new urn that just has 60 balls, and each ball is either black or yellow. Then would you rather have lottery A', where you get 30 dollars guaranteed, or lottery B', where you get a dollar for every black ball in the urn? I think most people would prefer lottery A'. And would you rather have lottery C', where you get 30 dollars plus a dollar for every yellow ball in the urn, or lottery D', where you get 60 dollars guaranteed? I think most people would prefer lottery D'.
So my question is, does it violate expected utility theory to prefer both A' to B' and D' to C'? I think it's consistent with expected utility theory. Assuming I'm right, couldn't you just change the currency from "dollars" to "lottery tickets" everywhere in my example, where a lottery ticket entitles you to a 1/90 chance of getting a 100 dollars? That would transform my example into the example in Ellsburg's paradox. So where's the flaw in my reasoning?
A:
The short answer seems to be yes your example violates expected utility... It mostly seems to me like a simple transformation of the first example you gave (but you got rid of the red balls).
As mentioned in other answers expected utility is not equipped to handle uncertainty because it deals with taking expectations and expectations cannot be computed when you don't know probabilities. For that reason, I think it is relevant to my answer to specify the distinction between what risk and uncertainty are.
Risk: This deals with facing a set of probabilities over outcomes in which the agent knows/understands the possible outcomes that he is facing
Uncertainty: This deals with an agent facing an unknown set of probabilities over possible outcomes
In a previous version of my answer, I wasn't careful in how I thought about and explained these ideas and I have clarified a few ideas in my head since then which hopefully translates to a clarified answer. Now to answer your question:
We have an urn with 60 balls. We are uncertain about the number of black balls and yellow balls in this urn. Imagine we present this urn with the above specified lotteries to an individual (with a monotonic utility function $u$) and ask them to choose between $L_{A'}$ and $L_{B'}$. Without loss of generality, imagine they choose to take $L_{A'}$.
This tells us by revealed preference $L_{A'} \succ L_{B'}$ which then implies
$$u(30) > u(B)$$
where $B$ is the number of black balls that are believed to be in the urn (no probabilities here, this is some number the decision maker arrived at and at this point we don't know how). This implies
$$B < 30$$
Now imagine that you give the agent the choice between $L_{C'}$ and $L_{D'}$ and the agent chooses to face lottery $D'$. Then
$$u(60) > u(30 + (60-B))$$
where $(60-B)$ is the number of yellow balls that the agent must think are in the urn. This implies
$$60 > 30 + (60-B) \Rightarrow B > 30$$
This means that an agent cannot prefer $L_{A'}$ to $L_{B'}$ and prefer $L_{C'}$ to $L_{D'}$ because that would imply $B > 30$ and $B < 30$. It is difficult to talk about where $B$ comes from because it is a hard concept to think about when we are used to working in expected value terms, this agent cannot compute any type of expectation over the sets of values that he thinks $B$ lies in. As an example of this, let me use a max-min approach.
Imagine that when he is presented the urn and lotteries that he is told that the number of black balls is either 15 or 45, but the agent doesn't know with what probability it is 15 and what probability it is 45.
Lottery $A'$ will give him $u(30)$ utility units for sure
Lottery $B'$ will give him either $u(15)$ utility units or $u(45)$ utility units.
Lottery $C'$ will give him either $u(75)$ utility units or $u(45)$ utility units.
Lottery $D'$ will give him $u(60)$
The agent is worried about uncertainty (an interpretation of the max-min is that he thinks it is a magic urn that tries its best to pay the least amount as possible, so it will choose the value that leaves him worse off if given a choice). Then using this in his decision process when comparing $L_{A'}$ and $L_{B'}$ he thinks these lotteries will pay the following amounts
$L_{A'}$ will pay $u(30)$
$L_{B'}$ will pay $\min(u(15), u(45)) = u(15)$
thus he chooses lottery $A'$. Now consider $L_{C'}$ and $L_{D'}$. He thinks these lotteries will pay
$L_{C'}$ will pay $\min(u(45), u(75)) = u(45)$
$L_{D'}$ will pay $u(60)$
thus he would choose lottery $D'$. This is one example of how uncertainty can be treated in a problem like this, but by no means is the only.
Note: Earlier I thought had a piece of my answer that talked about priors over the value of $B$, but this wasn't carefully thought through. You can have multiple values that you might imagine $B$ takes, but as soon as you assign a probability distribution to any of these values then you have left the realm of uncertainty and moved to the realm of risk.
|
[
"ru.stackoverflow",
"0000610832.txt"
] | Q:
Вывод текста в TextBox WPF
Есть переменная, которая получает значение вычисляемое методом при поступлении новых данных с потока. Как сделать программное изменение текста в textbox при присваивании новый значений переменной. Программное - это значит без участия пользователя, нажатия кнопок и т.д. Не таймером же проверять?
A:
Для вашего класса реализуете интерфейс INotifyPropertyChanged. Он необходим для оповещения о том, что изменилось значение свойства. Подробнее о нем можно прочесть в MSDN.
Тогда всякий раз, когда будет изменяется ваше свойство, интерфейс будет обновляться и отображать актуальные данные.
Если вам нужно только выводить информацию, то лучше использовать TextBlock вместо TextBox.
<TextBlock Text="{Binding НазваниеCвойства}" ... />
|
[
"stackoverflow",
"0044080138.txt"
] | Q:
Delete or Unlink folders inside a directory using PHP
I am able to delete files inside my upload folder inside my server using PHP unlink() see below code, but script only deletes files, how to include and delete folders?
$files = glob('upload/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}
I found this code but it gives me a permission denied error.
array_map('unlink', glob("upload/*"));
And used this code below
function deleteFiles($directory) {
$recursive = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($recursive, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
rmdir($directory);
}
deleteFiles('upload');
But permission denied error displays
Warning: rmdir(upload): Permission denied in
I am trying this code my self on my localhost and my user account is administrator.
A:
Ok so after modifying the function deleteFiles() i need to set my directory to 0777 using below code
chmod($directory,0777);
Then after deleting i need to remake the directory again using mkdir below is the modified code.
function deleteFiles($directory) {
chmod($directory,0777);
$recursive = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($recursive, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
rmdir($directory);
}
deleteFiles('upload');
mkdir("upload", 0700);
|
[
"stackoverflow",
"0062226594.txt"
] | Q:
Python append function not working as intended
I am trying to append a list to a list using an append function. See the below code - the temp will be a temporary list which is created dynamically. I want to append temp to list1.
temp = []
list1 = []
for num in range(0,2):
temp.clear()
temp.append(num)
list1.append(temp)
print(list1)
The output intended in list1 is [[0],[1]]. However i get [[1],[1]].
Can some one explain the reason behind this. Append should append to a list with out changing the list.
A:
Since you have appended the whole temp list, then list1 contains a reference to that list. So when you modify temp with temp.clear() and temp.append(num), then list1 is also modified. If you don't want that to happen, you'll need to append a copy:
import copy
temp = []
list1 = []
for num in range(0,2):
temp.clear()
temp.append(num)
list1.append(copy.copy(temp))
print(list1)
> [[0]]
> [[0], [1]]
Another way to get the desired results is to use temp = [] instead of temp.clear(). That will make temp point to a new object in memory, leaving the one that is referenced in list1 unchanged. Both work!
|
[
"stackoverflow",
"0022369364.txt"
] | Q:
PHP and MYSQL database connection and table creation only once
I'm developing a small application for my academic. i have a registration form and a log_in form. Here is what i want, i have a database configuration file which contains "connection to server, creating database and creating table queries" included in it. I've included this database file at the top of my registration form so that when the page is loaded the "query should execute and create database and table ONLY ONCE". But the problem is the query is successfully executing for the first time but when the registration page is loaded again, it prompt's an error "DATABASE ALREADY EXISTS". Please me.
I've attached the db.php code..
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$connect = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$connect) {
die('SERVER CONNECTION FAILED...\n: ' . mysql_error());
}
;
$sql = 'CREATE DATABASE USERS';
$retval = mysql_query($sql, $connect);
if (!$retval) {
die('DATABASE CREATION FAILED\n: ' . mysql_error());
}
;
$sql = "CREATE TABLE USERS( " . "Memberid int(10) NOT NULL AUTO_INCREMENT,
" . "Name varchar(100) NOT NULL,
" . "Username varchar(20) NOT NULL,
" . "Password varchar(10) NOT NULL,
" . "Email varchar(20) NOT NULL,
" . "Activation varchar(40) DEFAULT NULL,
" . "Status int(1) NOT NULL DEFAULT '1',
" . "PRIMARY KEY (`Memberid`)); ";
mysql_select_db('USERS');
$retval = mysql_query($sql, $connect);
if (!$retval) {
die('COULD NOT CREATE TABLE\n: ' . mysql_error());
}
;
mysql_close($connect);
?>
<html>
<body>
//registration form code
</body>
</html>
A:
query to create database only once if it doesn't exists
CREATE DATABASE IF NOT EXISTS DBName;
query to create table only once if it doesn't exists
CREATE TABLE IF NOT EXISTS tablename;
|
[
"stackoverflow",
"0029168447.txt"
] | Q:
Cypher relationships + paths and lucene
The issue here is that I'm using a path (p=) to select various relationships down a path, I thought by having them start with a common reserved pre-term (has_..) I could make assumptions using Neo4j's lucene syntax in the WHERE clause, however when using paths (p=) we are returned a collection, thus making the WHERE unable to define what's in the MATCH. Maybe there are other options?
MATCH (se:SourceExtended {name: 'BASE_NODE'})
WITH se
MATCH p =(:Trim)-[r:has_publication|has_model|has_trim|has_dealer|extends*1..5]-(se)
//WHERE type(r)=~ 'has_.*' OR type(r) = 'extends' <-Fails because p is a collection!!!
WITH se, p LIMIT 1
RETURN extract(n in nodes(p) | labels(n)) as labels, extract(r in relationships(p) | r) as relationships
UPDATE: Based on Dave Bennett's suggestion I can do:
MATCH (se:SourceExtended {source: 'XPRIMA_SPEC'})
WITH se
MATCH p =(:Brand)-[r*1..5]-(se)
WHERE ANY(r in relationships(p) WHERE type(r)=~ 'has_.*' OR type(r) = 'extends')
WITH se, p LIMIT 1
RETURN extract(n in nodes(p) | labels(n)) as labels, extract(r in relationships(p) | r) as relationships
However I'm surprised that the queries have now gone from ~500 ms up to ~3200 ms. Starting to think that dynamically adding all the relationship types while building the query might be the only solution.
A:
you need to do something like this...
...
WHERE ANY(r in relationships(p) WHERE type(r)=~ 'has_.*' OR type(r) = 'extends')
...
but why would you need to do that since your path relationship already contains only relationship types that match the terms in the desired where clause.
|
[
"math.stackexchange",
"0003428513.txt"
] | Q:
Self-Study: "Chi-square distribution is a transformation of Pareto distribution"
I ran across the following statement on Wikipeia at the following location
"chi-square distribution is a transformation of Pareto distribution"
I have looked for this transformation but cannot seem to find it. I have also looked here but it doesn't list it. I am curious if there is a transformation or if this may be a typo.
Any help would be greatly appreciated!
A:
You can get from any continuous distribution to a uniform distribution on $(0,1)$ by the probability integral transform. Take it from there.
Say $X$ has a Pareto distribution with pdf $$f(x)=\frac{a\theta^a}{x^{a+1}}1_{x>\theta>0}\quad,\,a>0$$
So cdf of $X$ is $$F(x)=1-\left(\frac{\theta}{x}\right)^a\quad,\,x>\theta$$
Then by probability integral transform, $$F(X)=1-\left(\frac{\theta}{X}\right)^a\sim U(0,1)$$
Or equivalently, $$Y=\left(\frac{\theta}{X}\right)^a\sim U(0,1)$$
And finally, $$-2\ln Y=2a\ln\left(\frac{X}{\theta}\right)\sim \chi^2_2$$
|
[
"cstheory.stackexchange",
"0000036671.txt"
] | Q:
Difference between time-bounded and memory-bounded Kolmogorov complexity
Let $x$ be a finite string of length $n$.
Denote by $C^t(x)$ the Kolmogorov complexity of $x$ bounded by time $t$ (i.e. the length of a minimal program that outputs $x$ and running at most $t$ steps).
Denote by $C_m(x)$ the Kolmogorov complexity of $x$ bounded by memory $m$.
Can $C^{\mathsf{poly}(n)}(x)$ be much greater than $C_{\mathsf{poly}(n)}(x)$?
It seems that the answer is "yes" but how to prove it under natural assumptions?
More accurately: let $(x_i)$ be a sequence of finite strings. Is it true that for every polynomial $p$ there exist a polynomial $q$ and a constant $c$ such that for every $x_i$ of length $n$ the following inequality holds: $$C^{q(n)}(x_i) < C_{p(n)}(x_i) + c\log n ?$$
Does it contradict to some natural assumptions of Computational complexity theory?
A:
Assume that there exists a sparse set $L \in \mathbf{NP} -\mathbf{P}$, this is equivalent to $\mathbf{EXP}\not= \mathbf{NEXP}$.
Then we can construct such a sequence. Indeed, consider $L_n = \{l_1,\ldots, l_k\} = L \cap \{0,1\}^n$.
Denote by $s_i$ the lexicographically first certificate for $l_i$.
Define $x_n$ as the list of pairs: $ x_n:= \{ (l_1, s_1), \ldots, (l_k,s_k)\}$.
Certainly, $C_{\mathsf{poly}(n)}(x_n) = O(\log n)$. Let us show that $C^{\mathsf{poly}(n)}(x_n) > c\log n$ for every $c$.
Indeed, otherwise there exists a polynomial-time algorithm calculating all strings of complexity at most $c\log n$ (including $x_n$). Hence we can verify that a string belongs to $L$ in polynomial time.
|
[
"softwareengineering.stackexchange",
"0000384671.txt"
] | Q:
Folder structure for child classes
I have a user feature. user feature also has other subfeatures user application details and user contact information.
Usually, because application details and contact information are part of user feature, we are dealing with one-to-one relation, I would put application details and contact information within user folder on the system. I see those two as an extension of the user feature.
So we would have a structure similar to:
app/Models/User.php
app/Models/User/ApplicationDetail.php
app/Models/User/ContactInformation.php
app/Services/User.php
app/Services/User/ApplicationDetail.php
app/Services/User/ContactInformation.php
I had one individual put forward an idea that we should think of user application details and user contact information as individual services (features_, due to which both of them can and should be located in the main folder and regarded us features of their own.
So we would have a structure similar to:
app/Models/User.php
app/Models/UserApplicationDetail.php
app/Models/UserContactInformation.php
app/Services/User.php
app/Services/UserApplicationDetail.php
app/Services/UserContactInformation.php
This seems like a very silly thing to ask on here, but I am trying to give this individual a chance and hence I am trying to evaluate the benefit of what was put forward. However, from my experience, we will end up with a folder that has too many files, which may feel very overwhelming even for those who know how the system is structured.
A:
Be pragmatic. What is more convenient for day to day tasks like:
Find class file. What place would astonish you the least?
Find class by looking at Project files
Use autocomplete what pops up first?
Move/rename/change one class what other classes might be affected?
Creating new classes
In my opinion:
It is reasonable to have those classes in models and services but if there are more than 1 class related to user it would be more convenient to search in user folder.
If I would open models or services folder it would be hard to find anything. Users folder is a reasonable choice here.
If you would type "User" you would get everything that is related to user. On the other hand typing "ContactInformation" you would get far fewer choices.
Having "User" folder immediately points to classes that might be affected.
Creating new class also is more convenient since you see what other "User" related classes there are. Seeing those different classes gives you clues whether you can reuse something.
It would be more consistent if "User" class would belong to "User" folder in 1st version. For convenience it might be reachable from "models" or "services" if needed.
Flat is sometimes better than nested but you have to weight different options and find what works best for you.
|
[
"stackoverflow",
"0015065839.txt"
] | Q:
java queue to queue calculaton not satisfied
I'm having a slight issue trying to see where I'm going wrong with the following piece of code:
public void processNextJob() {
/*
* 1. get # of free CPU's still avaialble
* 2. get top most job from priority queue
* 3. run job - put to CPU queue
* 4. develop a CPU queue here
* 5. count cores against freeCPUS and some sort of calculation to sort run times
*/
int freeCPUS = 500;
int availableCPUS = 0;
JobRequest temp = new JobRequest(); // initalised to new JobRequest
Queue q = new LinkedList();
while (true) {
int size = q.size();
for (int i = 0; i < size; i++) {
temp = (JobRequest) q.peek();
if (temp != null) {
availableCPUS += temp.getCores();
}
}
if ((freeCPUS - availableCPUS) >= 0) {
JobRequest nextJob = schedulerPriorityQueue.closestDeadlineJob(freeCPUS - availableCPUS); // returns top job from queue
if (nextJob != null) {
System.out.println("Top priority / edf job:");
printJob(nextJob);
q.add(nextJob);
} else {
System.out.println("Job = null");
}
} else {
break;
}
}
if (temp != null) {
System.out.println("Execution Queue");
for(Object jr : q){
printJob((JobRequest)jr);//print all elements in q
}
}
}
What's happening here is that I'm adding the top element from a priorityqueue and adding it to a new LinkedList. But the jobs I'm taking off the priorityqueue have a item with a value called "cores". I'm trying to get it to take as many jobs off as possible while staying under the core limit.
temp.getCores() is where I get the cores value
The issue I'm having is that it's not adding them correctly to my linkedlist queue, the value it takes in doesnt change. My queue displays 5 outputs with a core value of "160" but I've set a 500 cap, so the queue doesnt satisfy it at all
I dont see where I'm going wrong in the adding the values from the priorityqueue to make my available CPUS reach the designated limit of it being under 500.
EDIT:
public JobRequest closestDeadlineJob(int freeCPUS) {
// find top job to determine if other jobs for date need to be considered
JobRequest nextJob = scheduledJobs.peek(); // return top most job
if (nextJob != null) {
System.out.println("Found top EDF job:");
printJob( nextJob );
// what is it's date?
Date highestRankedDate = nextJob.getConvertedDeadlineDate();
// create a temporary queue to work out priorities of jobs with same deadline
JobPriorityQueue schedulerPriorityQueue = new JobPriorityQueue();
// add the top job to priority queue
//schedulerPriorityQueue.addJob(nextJob);
for (JobRequest jr : scheduledJobs) {
// go through scheduled jobs looking for all jobs with same date
if (jr.getConvertedDeadlineDate().equals(highestRankedDate)) {
// same date deadline, soadd to scheduler priority queue
schedulerPriorityQueue.addJob(jr);
System.out.println("Adding following job to priority queue:");
printJob(jr);
}
}
JobRequest highestPriorityJob = schedulerPriorityQueue.poll();
// this is the item at the top of the PRIORTY JOB queue to return
// remove that item from scheduledJobs
scheduledJobs.remove(highestPriorityJob);
return highestPriorityJob;
} else {
return null;
}
}
A:
I think you need to have a look here.
In your for() loop where you increment the availableCPUS variable, you are always taking the head of the Queue:
temp = (JobRequest) q.peek();
And because peek() does not remove an element from the queue, you end up assigning the same JobRequest to temp.
Try using an Iterator instead of the for:
availableCPUS = 0;
Iterator<JobRequest> it = q.iterator();
while (it.hasNext()) {
temp = it.next();
if (temp != null) {
availableCPUS += temp.getCores();
}
}
Also, I think you need to set availableCPUS to 0 for every iteration of the while loop to be able to count the cores correctly.
So you should be placing availableCPUS = 0; just above the Iterator initialization.
|
[
"stackoverflow",
"0022888233.txt"
] | Q:
Set multiple cursor loaders with multiple adapters - Android
I want to have two cursor loaders in my application fragment. Each one of them has different set of data and is used in different lists.
I found somewhere that with cursor you can use getId() method and then using switch do something. But, there is always method: getLoaderManager().initLoader(0,null,this); after which can be something like this:
adapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_1, null, from, to, 0);
This method is only for one cursor, but what if I have adapter1 and adapter2? How can I determine which cursor is for which adapter?
A:
My solution is to implement callback listeners
public class Query extends FragmentActivity {//do not implement callbacks
getSupportLoaderManager().initLoader(Constants.LOADER_DAILY_TASK,
null,dailyTaskResultLoaderListener);//note listener not "this"
getSupportLoaderManager().initLoader(Constants.LOADER_OTHER_TASK,
null,otherTaskResultLoaderListener);//note listener not "this"
private LoaderCallbacks<Cursor> dailyTaskResultLoaderListener
= new LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle bun) {
return new CursorLoader(getBaseContext(),
Constants.DAILY_TASK_URI,projection, selection,selArgs,null); }
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor)
{...}
public void onLoaderReset(Loader<Cursor> cursor) {...}};
private LoaderCallbacks<Cursor> otherTaskResultLoaderListener
= new LoaderCallbacks<Cursor>() {
....I think you get the idea
|
[
"stackoverflow",
"0031868793.txt"
] | Q:
How do I input My FIle?
I have dug around and found a function to copy files, my only issue is I do not know where I insert my directory (I'm moving "/data/data/com.android.providers.contacts/databases/contacts2.db" to "/sdcard/tpzb/")
I would appreciate some help very much. All I need is someone to put "FILE TO COPY DIR" and "OUTPUT DIR" in where it goes. I know this is a dumb question but I see many other functions like this, I figure once I see one I will be able to figure it out on my own with out asking. :)
private void moveFile(String inputPath, String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File (outputPath);
if (!dir.exists())
{
dir.mkdirs();
}
in = new FileInputStream(inputPath + inputFile);
out = new FileOutputStream(outputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
// write the output file
out.flush();
out.close();
out = null;
// delete the original file
new File(inputPath + inputFile).delete();
}
A:
Use this code to copy file
also, don't forget to add below permission in AndroidManifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Usage
copyFile("/data/data/com.android.providers.contacts/databases/contacts2.db", Environment.getExternalStorageDirectory().toString() + "/tpzb/");
|
[
"stackoverflow",
"0001065630.txt"
] | Q:
A loop in a loop to fill an array?
I am building a time registration program. Users can work on a project, and I want to display in a chart how many hours each user worked on a project, let's say, each month. The chart plugin works like this:
first_serie = OpenFlashChartLazy::Serie.new(
[["2008-1",100],["2008-2",120],["2008-3",130]],
{:title=>"name_of_user1",:start_date=>Time.mktime(2008,1,1),:items=>8})
This adds a new line in the graph.
My question is how can I loop through all my users and for each fill a new series with data from the database?
A:
I have no idea how you generate all the data for Serie.new, but you can get started using this:
@series = []
users = User.find(:all)
users.each do |user|
@series << OpenFlashChartLazy::Serie.new(blah, blah, blah)
end
This will add all of the added Serie objects to an array.
A:
As a follow up to Pesto would be nicer to use inject.
@series = User.all.inject([]) do |mem, user|
mem << OpenFlashChartLazy::Serie.new(user.foo, user.bar, user.foobarbob)
end
Same code, just doesnt have a @series = []
|
Subsets and Splits