text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How to diff two revisions of a file that got renamed in between and Mercurial doesn't know about the renaming?
I accidentally renamed a file outside of Mercurial. When I committed the change, Mercurial treated the change as two unrelated files (ie. a remove and a add). I need to go back to diff the two revisions but I don't know how to do so when Mercurial sees them as two respective files across different revisions. What can I do to diff the files?
A:
If you want to actually fix the history so that Mercurial is aware of the rename (and can use that information in future merges if needed), there's a way to do so documented on the Tips and Tricks page on the Mercurial wiki.
Current contents copied here for ease of use (and in case the link gets broken later):
Steps:
Update your working directory to before you did the rename
Do an actual "hg rename" which will create a new head
Merge that new head into the revision where you did the "manual" rename (not the head revision!)
Then finally merge the head revision into this merge result.
Advice:
Make a clone first and work on that, just in case!
After finishing the steps, use a file compare tool to check that the original and the clone are identical
Check the file history of any moved file to make sure it is now restored
That being said, if all you want to do is compare the contents at the point in time, you can definitely accomplish that without making Mercurial aware of the rename (as mentioned in Stephen Rasku's answer). In fact, you can use a combination of "hg cat" and an external comparison tool to compare any files, not just ones that Mercurial knows about.
A:
You didn't say what operating system you were using. The following will work with bash on Linux:
diff <(hg cat -r rev1 file1) <(hg cat -r rev2 file2)
You can replace diff with another program like vimdiff if you want a visual diff.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does jQuery have built in JSON support?
Does jQuery have built in JSON support or must I use a plugin like jquery.json-1.3.min.js ?
A:
Yes, absolutely it does. You can do something like:
$.getJSON('/foo/bar/json-returning-script.php', function(data) {
// data is the JSON object returned from the script.
});
A:
You can also use $.ajax and set the dataType option to "json":
$.ajax({
url: "script.php",
global: false,
type: "POST",
data: ({id : this.getAttribute('id')}),
dataType: "json",
success: function(json){
alert(json.foo);
}
}
);
Also, $.get and $.post have an optional fourth parameter that allows you to set the data type of the response, e.g.:
$.postJSON = function(url, data, callback) {
$.post(url, data, callback, "json");
};
$.getJSON = function(url, data, callback) {
$.get(url, data, callback, "json");
};
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is the file name getting replace by a JavaScript function in the address bar?
A local html file, lets says its path is /path/to/file.html. Has the following at the start.
<html>
<head>
<link rel="shortcut icon" href="logo.ico"/>
<LINK href="1.css" rel="stylesheet" type="text/css" />
<script src="1.js" type="text/javascript"> </script>
</head>
<body class = "body_background">
.
.
.
when tries to open it in a browser using its full path:
The file name along with its extension ( file.html ) gets replaced by a JavaScript function.
i.e.
file:///path/to/file.html
gets changed to the following: The file name with its extension gets replace by the function location located in 1.js.
file:///path/to/function location() { ...
The JavaScript file has this at the beginning:
if(window.addEventListener) {
window.addEventListener('load', location, false);
}
else if (window.attachEvent) window.attachEvent('onload', location);
This is happening on FireFox and Safari not on Chrome through.
On Chrome the page gets displayed appropriately.
This question is for a friend.
A:
location is a reserved word in some JS implementations, as in document.location.
See: http://www.javascripter.net/faq/reserved.htm
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to impact different class or HTML elements when hovering over a button?
I have a button in React and when I hover over it a funky saw animation happens. However, the effect I truly want is for the H1 tag on the page to have the saw animation in the background occur when I hover over the button. Yet, whenever I add a className and try to target that in the button:hover css, I get no effect. I've tried .btn:hover h1 and .btn:hover."classname" and a number of other combinations. yet none work.
How can I target a class, div, or h1 when hovering over a button that is not directly connected to the class, div, or h1 that will have the effect?
The current CSS I'm using for this, which works for the button itself, is:
.btn {
color: black;
}
.btn:hover {
animation: sawtooth 0.35s infinite linear;
background: linear-gradient(45deg, #d3f169 0.5em, transparent 0.5em) 0 0 / 1em 1em
, linear-gradient(-45deg, #d3f169 0.5em, transparent 0.5em) 0 0 / 1em 1em;
color: adjust-hue($color,180);
}
@keyframes sawtooth {
100% {
background-position: 1em 0;
}
}
The template I have is:
return (
<div className="App">
<h1>Question Genie</h1>
<button className="btn" onClick={this.displayQuestion}>View Unanswered Questions</button>
{questions}
</div>
);
}
}
A:
You can use a next sibling selector (~) and flexbox column-reverse to accomplish this. The main issue here is that there is no previous sibling selector in CSS
So, you can reorder the HTML so that <h1> is after the <button>, like this:
<div class="App">
<button class="btn" onClick={this.displayQuestion}>View Unanswered Questions</button>
<h1>Question Genie</h1>
</div>
and then you can use flex-direction: column-reverse; (or even order: -1 on the button) to make the <h1> appear above the <button>
CSS:
.App {
display: flex;
flex-direction: column-reverse;
align-items: flex-start;
}
.btn:hover ~ h1 {
animation: sawtooth 0.35s infinite linear;
... rest of the stuff
}
Here's the codepen: https://codepen.io/palash/pen/ZvVNav
Be sure to check flexbox support here https://caniuse.com/#feat=flexbox
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to deal with time it takes to finish something in REST?
Using Jersey/JAX-RS I have a get handler that contains code to copy a large file to another location. I want to be able to go to a URL and be able to see the current state of the copying (i.e. time elapsed). How do I accomplish this?
A:
On which side? The sender or the receiver?
The sender could expose a link or something, as part of the request.
You could arguably do something like
POST receiver/foo/incoming
<incoming-foo>
<link rel="status" uri="sender/foo/abc/status">
</incoming-foo>
receiver might '201 Created' or '303 See Other' sender to the URI receiver/foo/1
at this time, a
GET receiver/foo/1
might simply return the provided status link, or embed it in the representation:
<foo>
<status>incoming</status>
<link rel="status" href="sender/foo/abc/status" />
</foo>
GET sender/foo/abc/status
Might return, at this time, "pending" or "queued" or something like that.
...
Then, sender is free to
PUT receiver/foo/1
<foo>
<content>...</content>
</foo>
During the PUT, async GET to the services can still GET the status from the origin service, which might now be "transmitting" or include the bytes/total, etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Не срабатывает transition после animation
@keyframes anim {
0% {
left: -200px;
}
50% {
left: 0;
}
}
div {
widtH: 100px;
height: 100px;
background: green;
animation: 5s anim;
transition: all 1s;
position: absolute;
left: 0;
}
div:hover {
left: 20px;
}
<div></div>
Оно вроде как работает но первый раз идет рывок а дальше плавно. Как исправить ситуацию?
A:
Вместо left:20px; решил использовать margin-left: 20px;.
@keyframes anim {
0% {
left: -200px;
}
100% {
left: 0;
}
}
div {
widtH: 100px;
height: 100px;
background: green;
animation: 2.5s anim;
transition: all 1s;
position: absolute;
}
div:hover {
margin-left: 40px;
}
<div></div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Obfuscate strings in Python
I have a password string that must be passed to a method. Everything works fine but I don't feel comfortable storing the password in clear text. Is there a way to obfuscate the string or to truly encrypt it? I'm aware that obfuscation can be reverse engineered, but I think I should at least try to cover up the password a bit. At the very least it wont be visible to a indexing program, or a stray eye giving a quick look at my code.
I am aware of pyobfuscate but I don't want the whole program obfuscated, just one string and possibly the whole line itself where the variable is defined.
Target platform is GNU Linux Generic (If that makes a difference)
A:
If you just want to prevent casually glancing at a password, you may want to consider encoding/decoding the password to/from base64. It's not secure in the least, but the password won't be casually human/robot readable.
import base64
# Encode password (must be bytes type)
encoded_pw = base64.b64encode(raw_pw)
# Decode password (must be bytes type)
decoded_pw = base64.b64decode(encoded_pw)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
A simple C++ class for packing DNA strings
Introduction
I have this small C++ program that packs a DNA string over alphabet ACGT into a bit vector, two bits per character.
Code
dnapack.hpp
#ifndef NET_CODERODDE_DNAPACK_HPP
#define NET_CODERODDE_DNAPACK_HPP
#include <string>
#include <vector>
namespace net {
namespace coderodde {
namespace dna {
class packed_dna_sequence {
public:
packed_dna_sequence(std::string& dna_sequence);
std::string&& unpack() const;
std::vector<bool> get_packed_sequence() const;
private:
std::vector<bool> m_packed_bits;
};
} // End of namespace net::coderodde::dna.
} // End of namesapce net::coderodde.
} // End of namespace net.
#endif // NET_CODERODDE_DNAPACK_HPP
dnapack.cpp
#include "dnapack.hpp"
#include <algorithm>
#include <cctype>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
static std::string&& dna_to_upper_case(std::string& unpacked_dna_sequence)
{
std::string ret;
std::for_each(unpacked_dna_sequence.cbegin(),
unpacked_dna_sequence.cend(),
[&ret](char c) { ret.push_back(std::toupper(c)); });
return std::move(ret);
}
namespace net {
namespace coderodde {
namespace dna {
using std::string;
packed_dna_sequence::packed_dna_sequence(string& unpacked_dna_sequence)
{
std::string upper_case_unpacked_dna_sequence =
dna_to_upper_case(unpacked_dna_sequence);
m_packed_bits.reserve(2 * upper_case_unpacked_dna_sequence.length());
for (char c : upper_case_unpacked_dna_sequence) {
switch (c) {
case 'A':
m_packed_bits.push_back(false);
m_packed_bits.push_back(false);
break;
case 'C':
m_packed_bits.push_back(false);
m_packed_bits.push_back(true);
break;
case 'G':
m_packed_bits.push_back(true);
m_packed_bits.push_back(false);
break;
case 'T':
m_packed_bits.push_back(true);
m_packed_bits.push_back(true);
break;
default:
throw std::invalid_argument("Unknown character.");
}
}
}
std::vector<bool> packed_dna_sequence::get_packed_sequence() const
{
// Copy. We don't want the client to tamper with the bits.
return m_packed_bits;
}
std::string&& packed_dna_sequence::unpack() const
{
std::string ret;
ret.reserve(m_packed_bits.size() / 2);
for (size_t index = 0; index < m_packed_bits.size(); index += 2)
{
bool bit1 = m_packed_bits[index + 1];
bool bit2 = m_packed_bits[index];
size_t num = (bit2 << 1) | bit1;
switch (num)
{
case 0:
ret += 'A';
break;
case 1:
ret += 'C';
break;
case 2:
ret += 'G';
break;
case 3:
ret += 'T';
break;
}
}
return std::move(ret);
}
} // End of namespace net::coderodde::dna.
} // End of namespace net::coderodde.
} // End of namespace net.
main.cpp
#include "dnapack.hpp"
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
bool same_dna(std::string& dna1, std::string& dna2)
{
if (dna1.length() != dna2.length())
{
return false;
}
for (size_t i = 0; i < dna1.length(); ++i)
{
if (std::toupper(dna1[i]) != std::toupper(dna2[i]))
{
return false;
}
}
return true;
}
int main(int argc, const char * argv[]) {
using net::coderodde::dna::packed_dna_sequence;
std::string dna;
std::cout << "> ";
std::cin >> dna;
packed_dna_sequence pds(dna);
std::vector<bool> rep = pds.get_packed_sequence();
std::cout << "Binary representation: ";
std::ostream_iterator<int> out_it(std::cout);
std::copy(rep.cbegin(), rep.cend(), out_it);
std::cout << '\n';
std::string unpacked_dna = pds.unpack();
std::cout << "Unpacked DNA: "
<< unpacked_dna
<< '\n';
std::cout << "Agrees: "
<< std::boolalpha
<< same_dna(dna, unpacked_dna)
<< '\n';
}
Critique request
I would like to hear comments regarding:
const correctness,
move semantics,
resource management,
coding style,
API design.
A:
static std::string&& dna_to_upper_case(std::string& unpacked_dna_sequence). That's wrong. It returns a dangling reference. You can't return an rvalue reference to a temporary object. Return it by value. It doesn't change the unpacked_dna_sequence, so it would be better to pass it by a const reference.
The same is true for std::string&& packed_dna_sequence::unpack() const. It's also broken because it returns a reference to a temporary object.
bool same_dna(std::string& dna1, std::string& dna2). Once again, if you don't change the input objects, pass them by a const reference. You can also simplify this function using std::equal function with a custom predicate.
This piece of code is a little bit confusing:
std::string ret;
std::for_each(unpacked_dna_sequence.cbegin(),
unpacked_dna_sequence.cend(),
[&ret](char c) { ret.push_back(std::toupper(c)); });
std::for_each is usually used for something with side effects. If you want to transform one sequence into another, std::transform is an idiomatically better choice.
A:
First things first:
Undefined behavior
Kraskevich pointed at the most obvious one. Yet, there is one more (although it will work on X86, from what I've been told). Basically, do not pass chars directly to any function in cctype, convert them to unsigned char first. More info.
vector bool
Very interesting decision. I'd rather pack it myself using fallthrough switch statement into std::uint8_t. Duff's device never gets old.
Supported operations
I believe scientists would want to do more operations on it. I'm not sure which ones, but definitely building some algorithms on top of this would be useful. This leads to the next point:
What does it represent?
If one wants to pack it, I'd guess they want to store it in some persistent storage, but there is no serialization/deserialization functions. Passing around into functions? May be, but it is not clear yet if it is beneficial. So, what I want to say is, the class doesn't have clear purpose.
Smaller things:
Constructor can take the sequence by const reference, since it is not modifying it.
Return by value, let people/compiler decide if they want to copy. I believe in the worst case they'll need to add std::move(), though at the return site it will prevent NRVO.
No equivalence operator. I believe it will be useful.
Conclusion
The code looks like it was written in a rush. It needs rethinking.
A:
The Interface
class packed_dna_sequence {
public:
packed_dna_sequence(std::string& dna_sequence);
std::string&& unpack() const;
std::vector<bool> get_packed_sequence() const;
private:
std::vector<bool> m_packed_bits;
};
Does not look very useful. You have a full dna_sequence as a string already (so you have the space). When you unpack the sequence you have to build the full string again.
So does it really save space? Not really; you must have the full size string to create it and you can only get values from it after de-compressing the whole thing back to a string.
So the only thing this structure is good for is pre-materalizing a packed structure before serialization to some storage.
This is not a great design -- memory is much more scarce than offline storage. So your design seems to fail on all these fronts. If you wanted to optimize for storage then you should write a compressing stream.
If you want to optimize for memory then you should have an object that allows random (or serialized) access to the members while it is in the compressed form.
Code Review
Const Reference Parameters
Sure pass by reference (it avoids the copy).
packed_dna_sequence(std::string& dna_sequence);
But if you are not going to modify the input then pass by const reference.
R-Value return
Looks like a good move.
std::string&& unpack() const;
But in practice does nothing. Return by value and RVO (or NRVO) will automatically kick in and build the object in place at the destination (so technically a tick faster as you don't even need to swap pointers).
Return by Value.
std::vector<bool> get_packed_sequence() const;
Should that not return a const reference to the internal object.
Leaky Abstraction
std::vector<bool> get_packed_sequence() const;
Also, why do you want to expose the raw packed sequence? This only exposes your implementation in binds you to maintaining it. This is known as a leaky abstraction. Never leak your internal implementation details.
Copying the string?
Your uppercasing function makes a copy of the complete string. That seems rather wasteful. Why not do it as you use the letters. That would seem a lot less costly and would not require you to loop over the string multiple times.
static std::string&& dna_to_upper_case(std::string& unpacked_dna_sequence)
{
std::string ret;
std::for_each(unpacked_dna_sequence.cbegin(),
unpacked_dna_sequence.cend(),
[&ret](char c) { ret.push_back(std::toupper(c)); });
return std::move(ret); // Not needed NRVO will kick in here.
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I prevent decimal rounding in the middle of an operation?
I'm trying to perform an operation that will find number of pizza slice (homework assignment) from the user's input of diameter, but my problem is that c++ keeps rounding down in the middle of the operation. Here's the code
//Calculates the number of slices that can be obtained using the diameter from the user's input
sliceNumber = (pi *(pow((pizzaDiameter/ 2.0 ) , 2.0 ))) / sliceArea;
//Outputs the number of slices that can be cut, accurate to 1 decimal point using the command "setprecision"
cout << "The number of slices your pizza can be divided into is ";
cout << setprecision(2) << sliceNumber << endl;
The end result should be rounded to one decimal place, that is correct since it was forced with setprecision. But when I did the problem on my own with a calculator the result is a little different. For example I would input the diameter as 10 in the program and it will output 5.4, even though on a real calculator it's 5.6. (the # of slices is found by finding the area of the pizza then dividing it by 14.125, which is declared with sliceArea)
pi is declared as a constant integer of 3.14 and both sliceNumber and sliceDiameter are declared as doubles. sliceArea is declared as an int of 14.125.
A:
If sliceArea is an int, then the value is 14, not 14.125. Similarly, if pi is an int, the value is 3, not 3.14. Not coincidentally, (3 * pow(10 / 2.0, 2.0)) / 14 comes to 5.357... which would round to 5.4 with two digits of precision. You need to declare these values to be double (or float) or your compiler will just truncate the fractional value to get an int.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
function handles in Octave
I have a question regarding function(handles) in Octave.
So, I want to call a function, which accepts two variables and returns two(the implementation is faulty; but not relevant in this case).
According to the documentation this should be quite straightforward:
function [ret-list] = name (arg-list)
body
endfunction
I'm trying the following:
function two_d_comp = twodcomp
twodcomp.twoDperp=@perp;
^
end
function twoDperp[vmag, vangle]=perp(x,y)
W = hypot(y,x);
vmag = y/W;
vangle = x/y;
end;
I saved the function in a file called twodcomp.m.
When I call the function as follows:
[X, Y] = twodcomp.twoDperp(1,2)
Octave spits out the following:
error: @perp: no function and no method found
error: called from
twodcomp at line 2 column 20
I managed to remove the error by removing the output arguments vmag and vangle, as follows:
function twoDperp=perp(x,y)
But this is obviously not really what I want.
Do you guys happen to have some pointers as to what I'm doing wrong?
Cheers
A:
Your initial function twodcomp: you cannot have the output variable (before the =) be named the same as your function name (after the =).
Then if you want to assign an anonymous function (MATLAB docs, Octave docs) using the @ notation, you can still pass the desired inputs.
So rewrite it like:
% Include empty parentheses after a function name to make it clear which is the output
function output = twodcomp()
% Not sure why you're assigning this function to a struct, but
% still give yourself the ability to pass arguments.
% I'm assuming you want to use the output variable,
% and not reuse the main function name (again)
output.twoDperp = @(x,y) perp(x,y);
end
With your second function, you just need to remove the twoDperp before your output arguments. In your question you state the expected syntax from the docs, but then didn't follow it...
function [vmag, vangle] = perp(x,y)
W = hypot(y,x);
vmag = y/W;
vangle = x/y;
end
Now these can be used like so:
% Deliberately using different variable names to make it clear where things
% overlap from the function output. twodcomp output is some struct.
myStruct = twodcomp();
% The output struct has the field "twoDperp" which is a function with 2 outputs
[m, a] = myStruct.twoDperp(1,2);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
if else condition in oracle with update and counter in it
I am using Oracle, PL/SQL.
I have written the following procedure:
Declare result number;
countExceed Number;
begin
select count(*) into result from
(select "LoginName","LoginPassword" from "ApplicationUser" where "LoginName"='adin' and "LoginPassword"='admin');
if result>0
then
execute immediate('Update "test" set "Count"=0 where "Count"<5');
dbms_output.put_line('Update as count 0!');
elsif result=0 then
execute immediate(' select "Count"
into countExceed from "test";
if countExceed >5 then
Update "test" set "Count"="Count"+1 where "Count" <5;
END IF;');
dbms_output.put_line('Update as Count + 1!');
End If;
end;
All I want it to do is :
Check username and password, if exists check count<=5, if true update count=0 where username='admin'.
if username and pass exists and if count>5, update Isactive=0. And finally
if username and password not exists, update count=count+1 where username=username.
the above Procedure is giving me this error
ORA-00911: invalid character
Please Help.
A:
try this
Declare result number;
countExceed Number;
begin
select count(*) into result from ApplicationUser where LoginName='adin' and LoginPassword='admin';
if result>0 then
execute immediate('Update "test" set "Count"=0 where "Count"<5');
dbms_output.put_line('Update as count 0!');
else
select "Count" into countExceed from "test";
if countExceed >5 then
execute immediate('Update "test" set "Count"="Count"+1 where "Count" <5');
END IF;
dbms_output.put_line('Update as Count + 1!');
End If;
end;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Running Leopard on a MacBook Pro that shipped with Snow Leopard
I have a MacBook Pro with 10.6 pre-installed. Is there a way to use this machine to test my software on 10.5?
Do I need 10.5, or is there is a mode within 10.6 with which I can run 10.5?
If I need 10.5, how can I get it?
Do I need to buy the 10.5 OS? (if so, where does one do that?)
Does 10.6 somehow include 10.5 with it?
Do I already have a license for 10.5 by buying 10.6?
How do I install 10.5 once I have it?
Will it work in Virtualbox?
Do I need to dual boot?
A:
No, this will not work. You can have multiple versions of OS X on one machine, but you can only install newer versions than the one that came pre-installed. For example, if your machine came with 10.6.4, you can't run 10.6.3 or older.
When Apple releases new hardware, the drivers for that hardware get rolled into a special build of OS X that comes only on that model. They don't get added to OS X in general until the next point release. (That means that drivers for the hypothetical machine I'm talking about wouldn't be added until 10.6.5.)
Apple doesn't release drivers as standalone software, which effectively makes it impossible to install and older version of OS X than what your Mac shipped with. You'll find that if you put the install disc for an older version in the drive, it either won't boot or it will refuse to install.
However, you can go the other direction. If you have an old Mac running 10.5, you can use Disk Utility to make another partition (HFS+ Journaled), then boot the install DVD for 10.6 and install it to that partition. To switch between the two after installing, hold alt when you boot up. (You can also select the default boot partition through the Startup Drive pane in System Preferences within either OS X install.) Boot camp is not required for this. Boot camp is only required for installing non-Apple operating systems like Windows and Linux.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Google charts add option programmatically
Is it possible to add an option to the chart after it is drown?
I know i can delete an option with delete option.optionname but how can i add a new one?
Edit: @WhiteHat answer options.backgroundColor = 'cyan'; works quite well but how can i add an animation like:
animation: {
duration: 4000,
startup: true,
easing: 'inAndOut',
}
to an existing option.
A:
anytime you want to change an option, the chart must be redrawn
so it's easy as...
options.backgroundColor = 'cyan';
chart.draw(data, options);
you can also use the Chart Wrapper Class, which has a method setOption
but again, it must be redrawn afterwards
see following working snippet, which draws both...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: {position: 'bottom'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
google.visualization.events.addOneTimeListener(chart, 'ready', function () {
options.backgroundColor = 'cyan';
chart.draw(data, options);
});
chart.draw(data, options);
var wrapper = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'wrapper_div',
dataTable: data,
options: options
});
google.visualization.events.addOneTimeListener(wrapper, 'ready', function () {
wrapper.setOption('backgroundColor', 'magenta');
wrapper.draw();
});
wrapper.draw();
},
packages: ['corechart']
});
div {
padding: 8px;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<div id="wrapper_div"></div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should I include publications where I am a "team member" in my CV
Related to but different from Should I include a publication where I'm only acknowledged (and not one of the authors) in my CV?
I'm a part of some publications which officially are written by author A and B and then the Team Members. Should these publications be on my CV? I contributed to the project (hence the team co-authorship) but don't want to seem like I'm trying to pad my CV.
Currently I have my publication list broken up by sections: Journal, Talks, Technical Reports, and then Other, and I have the Team Member publications listed under Other.
Is this appropriated and/or reasonable, or should I remove them?
A:
Looking at the CV that's linked to your website, I don't see anything inappropriate about what you've done. The only thing to make sure of is that when you have a team listed explicitly as the author in a paper (e.g., "Author X, Author Y, and The A-Team"), you will need to make sure that there is a publicly available listing of the team members available for reference. This could be as a supplement to the paper online (as "supporting information"), or it can be on a permanent web site for the team's endeavors. However, people should be able to confirm that you are a member of this collaboration beyond just what's on your CV.
A:
If you are listed as an author in the paper, then you can always include the paper in your publications list.
If you are pruning your resume to be a 2-page one and if you have better publications (say where you are the lead author) to show, then have a single category titled "Selected Publications" and exclude this paper.
If you are making a very detailed list of publications, say one on a webpage, then do consider including the name of all authors in the same order as in the published paper.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How make QChar.unicode() report the utf-16 representation of combined characters?
I'm trying to write a codec for Code page 437. My plan was to just pass the ASCII characters through and map the remaining 128 characters in a table, using the utf-16 value as key.
For some combined charaters (letters with dots, tildes etcetera), the character appears to occupy two QChars.
A test program that prints the utf-16 values for the arguments to the program:
#include <iostream>
#include <QString>
using namespace std;
void print(QString qs)
{
for (QString::iterator it = qs.begin(); it != qs.end(); ++it)
cout << hex << it->unicode() << " ";
cout << "\n";
}
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; i++)
print(QString::fromStdString(argv[i]));
}
Some output:
$ ./utf16 Ç ü é
c3 87
c3 bc
c3 a9
I had expected
c387
c3bc
c3a9
Tried the various normalizationsforms avaialable in QString but no one had fewer bytes than the default.
Since QChar is 2 bytes it should be able to hold the value of the characters above in one object. Why does the QString use two QChars? How can I fetch the combined unicode value?
A:
QString::fromStdString expects an ASCII string and doesn't do any decoding. Use fromLocal8Bit instead.
Your expected output is wrong. For example, Ç is U+00C7, so you should expect C7, not the UTF-8 encoding of C3 87!
If you modify main() as below, you get the expected Unicode code points. For each character, the first line lists the local encoding (here: Utf-8), since fromStdString is essentially a no-op and passes everything straight. The second line lists the correctly decoded Unicode code point index.
$ ./utf16 Ç ü é
c3 87
c7
c3 bc
fc
c3 a9
e9
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; i++) {
print(QString::fromStdString(argv[i]));
print(QString::fromLocal8Bit(argv[i]));
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Stored procedure returned unknown execution result Unknown
I'm getting the below error when calling a Workflow Service hosted on your staging environment.
Stored procedure returned unknown execution result Unknown.
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at IWorkflow.InvokeWorkflowRequest(String id)
at WorkflowClient.InvokeWorkflowRequest(String id)
My configuration file
<system.serviceModel>
<services>
<service name="WorkflowService">
<endpoint binding="basicHttpBinding" contract="IWorkflow" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<sqlWorkflowInstanceStore connectionString="Data Source=.;Initial Catalog=Store;Integrated Security=True;Asynchronous Processing=True" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Locally the service works fine and even when pointing to my staging DB. I'll appreciate any help.
A:
I had a similar problem with Workflow Foundation 4.5 when a new instance was persisted without DefinitionIdentity.
An exception 'Stored procedure returned unknown execution result Unknown' was thrown and no inner exception was given.
The exception was thrown because SaveInstance procedure was returning 99 and was caused by a missing row in table [System.Activities.DurableInstancing].[DefinitionIdentityTable].
You can recreate the missing row with the following sql script :
INSERT [System.Activities.DurableInstancing].[DefinitionIdentityTable]
([SurrogateIdentityId], [DefinitionIdentityHash],
[DefinitionIdentityAnyRevisionHash], [Name], [Package], [Build],
[Major], [Minor], [Revision]) VALUES (1,
N'00000000-0000-0000-0000-000000000000',
N'00000000-0000-0000-0000-000000000000', NULL, NULL, NULL, NULL, NULL,
NULL)
I hope it helps someone
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Dynamic RadEditor Creation through HtmlHelper
I am using the Telerik RadEditor (Q1 2009 SP1) in our ASP.NET MVC (RTM) project. The editor works great when rendered as a hardcoded object on the page with a static id. But when extending with an HtmlHelper to do dynamic creation by passing in an Id it seems to render the html as all lowercase for the tag. Does the HtmlHelper object mess with this innately by chance? The attributes look upper and lowercase respectively but this seems strange. Here is my code....thanks in advance!
<% if (placeholder.Type.ToLower() == "richtext") { %>
<%= Html.RadEditor("placeholder_" + placeholder.Name) %>
<% } else { %>
<%= Html.TextBox("placeholder_" + placeholder.Name, null, new { @class = placeholder.Type }) %>
<% } %>
The helper looks like this....
public static string RadEditor(this HtmlHelper html, string Id)
{
var sb = new StringBuilder();
sb.Append("<telerik:RadEditor ID='" + Id + "' Runat='server' DialogHandlerUrl='~/Telerik.Web.UI.DialogHandler.axd'>");
sb.Append("<Content>");
sb.Append("</Content>");
sb.Append("</telerik:RadEditor>");
return sb.ToString();
}
A:
For the time being you cannot render RadEditor without having a valid Page object with a ScriptManager. We (Telerik that is) plan to add support for "standalone" rendering in the near future. Should be announced in a blog post so stay tuned.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Внешние ключи и FileTables
Есть первая таблица people, в ней есть столбец photo - uniqueidentifier.
Вторая - FileTable photo.
Первая таблица связана (photo) со второй (stream_id), и в случае, если фотография будет удалена, столбцу photo будет присвоен NULL.
А как сделать, чтобы в случае удаления человека из таблицы people удалялась и фотография? Пытался присвоить внешний ключ обычным способом, но не хочет.
A:
Первая таблица связана (photo) со второй (stream_id), и в случае, если
фотография будет удалена, то столбцу photo будет присвоен Null.
В таком случае обычный AFTER DELETE триггер должен сработать
CREATE TRIGGER people_afterDelete
ON people
AFTER DELETE
AS
BEGIN
SET NOCOUNT ON;
DELETE PH
FROM photo PH
JOIN DELETED D on D.photo = PH.stream_id;
END;
И то, что таблица photo является FileTable, никакой роли в данном случае не играет.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Rails, passenger, communicating between threads
I want to write in simple logger for my that puts messages in memory and, in background, every X seconds write it to a database.
Here is the buffered logger code:
module BufferedLogger
def buffer
@buffer ||= []
end
def log( message )
buffer << message
end
def write_buffer
while message = buffer.shift do
# save the message in nosql
end
end
def repeat_every( interval )
Thread.new do
loop do
start_time = Time.now
yield
elapsed = Time.now - start_time
sleep([interval - elapsed, 0].max)
end
end
end
extend self
thread = repeat_every(10) do
write_buffer
end
end
In development, this works fine, buffer() access to the same @buffer var in both log and write_buffer method. But as soon as I go to production or staging env, i.e. as soon as I'm behind passenger, this @buffer don't seem to be shared anymore.
Any pointer?
A:
Since passenger create separate process, and how these process will persists depends on passenger's algorithm, I guess it will not work well as you expect. (btw, I had bad experience in this regard using global variables/class variables.)
My suggestion to buffer the log is, use logger like fluentd as intermediate processor. Fluentd can monitor and gather the log. You can write a plugin to write the collected log to DB. I think this will suit your needs.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Numbers for diagnostics metrics of VM on portal.azure.com dashboard seem incorrect
On Azure, I have a Linux VM. I enable Diagnostics settings on this VM 3 days ago.
The virtual machine has a 30 GB disk of which 16 are used. But Azure Monitor chart for "Filesystem free space" showing that I have 149 GB free space and "Filesystem used space" 24.5 GB.
Why is that? Is it correct? Can I debug this?
A:
In this case this is the expected behaviour due to the temporary disk attached to azure vm
|
{
"pile_set_name": "StackExchange"
}
|
Q:
API data not being copied and stored into the state in react, how would I do this?
So I'm new to react and I have this predicament. I'm firstly using axios to get a "database" from JSONPlaceholder which I can then store in the state and then I want to call an API to fill in missing data that was not in the database. Just a quick run down of the code, I am using grabdata to grab the data that I need from JSONPlaceholder and put it in the array. Then I am using callsetcycle, which calls the setcycle method which should cycle through the array positions and get the data that I need and then store it in the array of suggesteddestinations too. My Problem is, is that the information in not called and stored and I don't understand why. Any help will be appreciated.
export class App extends Component {
state = {
suggesteddestinations : [],
scheduleddestinations : [],
loaded: false
}
componentDidMount = () =>{
this.grabData().then(
this.callsetCycle()
)
}
callsetCycle = () =>{
if (this.state.suggesteddestinations.length>0){
console.log("2")
this.setCycle().then(
this.setState({
loaded: true
}))
}
}
grabData = () =>{
return new Promise(() => {
var url = "https://my-json-server.typicode.com/dharquissandas/weatherApp/suggesteddestinations";
Axios.get(url)
.then(contents => this.setState({ suggesteddestinations: contents.data}))
});
}
setCycle = () => {
return new Promise(() => {
var i
if (this.state.suggesteddestinations.length > 0){
for (i = 0; i < this.state.suggesteddestinations.length; i++) {
console.log("5")
this.apiCallCurrentWeather(this.state.suggesteddestinations[i].name, i)
this.apiCallForcast(this.state.suggesteddestinations[i].name, i)
}
}
});
}
apiCallCurrentWeather = async (name, pos) => {
const apicall = await fetch("http://api.openweathermap.org/data/2.5/weather?q="+name+"&units=metric&APPID=5afdbd7139b98ae3f70a76b0dda2b43b")
await apicall.json()
.then(data =>
this.setState(
this.setCurrentWeatherProperties(data, pos)
)
)
}
setCurrentWeatherProperties = (data, pos) => {
this.state.suggesteddestinations[pos].temp = data.main.temp.toString()
this.state.suggesteddestinations[pos].desc = data.weather[0].main
this.state.suggesteddestinations[pos].tempmax = data.main.temp_max.toString()
this.state.suggesteddestinations[pos].tempmin = data.main.temp_min.toString()
this.state.suggesteddestinations[pos].feelslike = data.main.feels_like.toString()
this.state.suggesteddestinations[pos].pressure = data.main.pressure.toString()
this.state.suggesteddestinations[pos].windspeed = data.wind.speed.toString()
}
apiCallForcast = async (name, pos) => {
const apicall = await fetch("http://api.openweathermap.org/data/2.5/forecast?q="+name +"&units=metric&APPID=5afdbd7139b98ae3f70a76b0dda2b43b")
await apicall.json()
.then(data =>
this.formatForcast(data, pos)
)
}
formatForcast = (data, pos) => {
this.state.suggesteddestinations[pos].dayone = data.list[4]
this.state.suggesteddestinations[pos].daytwo = data.list[12]
this.state.suggesteddestinations[pos].daythree = data.list[20]
this.state.suggesteddestinations[pos].dayfour = data.list[28]
this.state.suggesteddestinations[pos].dayfive = data.list[36]
}
render (){
console.log(this.state.suggesteddestinations)
console.log(this.state.loaded)
if (this.state.loaded) return null;
return(
<div>
<BrowserRouter>
<div className="container">
<Header />
{/* <Route path="/" render={(props) =>
<Home {...props} suggesteddestinations={this.state.suggesteddestinations} />
} /> */}
<Route path="/home" component = {Home} exact />
<Route path="/CurrentWeather/:id" component = {CurrentWeather} />
<Route path="/EventSelection/:id" component = {EventSelection} />
<Route path="/Schedule" component = {Schedule} />
</div>
</BrowserRouter>
</div>
)
}
}
A:
There are a few issues in the code , State cannot be mutated meaning this.state cannot be set outside the constructor.The other issue is the code is over-engineered :)
Since you are learning react I would recommend that you understand how State Management / Props / Component life cycle methods from the react documentation
Nice try!
Here is the actual refactored code :
import React,{Component} from 'react'
export default class StackApp60663913 extends Component {
state = {
suggesteddestinations : [],
scheduleddestinations : [],
loaded: false
}
componentDidMount = () =>{
this.grabData()
}
grabData = async () =>{
let suggestionsApi = "https://my-json-server.typicode.com/dharquissandas/weatherApp/suggesteddestinations";
let suggestionFetch = await fetch(suggestionsApi)
let suggestionData = await suggestionFetch.json()
for (let index = 0; index < suggestionData.length; index++) {
let city = suggestionData[index]
let weatherFetch = await fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${city.name}&units=metric&APPID=5afdbd7139b98ae3f70a76b0dda2b43b`)
let weatherData = await weatherFetch.json()
let {main,weather,clouds,wind,sys} = weatherData.list[0]
suggestionData[index].temp = main.temp.toString()
suggestionData[index].desc = weather[0].description
suggestionData[index].tempmax = main.temp_max.toString()
suggestionData[index].tempmin = main.temp_min.toString()
suggestionData[index].feelslike = main.feels_like.toString()
suggestionData[index].pressure = main.pressure.toString()
suggestionData[index].windspeed = wind.speed.toString()
}
this.setState({
suggesteddestinations : suggestionData,
loaded:true
})
}
render (){
console.log(this.state.suggesteddestinations)
return(
<div>
{this.state.loaded ?
<div>
{
this.state.suggesteddestinations.map((element)=>
<li>
ID-{element.id},Name-{element.name},Temp-{element.temp},Desc-{element.desc},TempMin-{element.tempmin},TempMax-{element.tempmax}
</li>)
}
</div> : <div>Loading Data...</div>
}
</div>
)
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
List the files by giving the directory and a part of the file name along with extension
Efficient way of listing the files by giving the directory and part of the filename along with extension.
For Ex:- Directory = "/home/Dell/Projects/"
File Name Starts with = "sample_"
Extension = ".csv"
I may have the following files in the directory mentioned,
1. "/home/Dell/Projects/sample_1.csv"
2. "/home/Dell/projects/sample_2019_01_04.csv"
3. "/home/Dell/Projects/sample_2.pkl"
4. "/home/Dell/Projects/sample_3.txt"
Out of the above 4 files, I should get file.1 & file.2 from the above list in python.
A:
with the help of os & fnmatch libraries, the desired result can be obtained.
import os, fnmatch
listOfFiles = os.listdir('/home/Dell/Projects/')
pattern = "sample_*.csv"
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
print ("Entry :: ", entry)
The output will be,
Entry :: sample_1.csv
Entry :: sample_2019_01_04.csv
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to create a HTTPS login form easily?
I'm new to web programming. I've created a simple login form (with php). Now I want to turn this one into a HTTPS (with SSL) login form. What should I do to achieve this?
A:
Get an SSL certificate. Once you have HTTPS working on your server (work with your hosting company to get it working), you can use code similar to the following to force an HTTPS connection in PHP. .htaccess is another option, mentioned elsewhere.
<?
function current_protocol()
{
$protocol = 'http';
if ( array_key_exists( 'HTTPS', $_SERVER ) && $_SERVER['HTTPS'] === 'on' )
{
$protocol = 'https';
}
return $protocol;
}
//------------------------------------------------------------------------
function current_has_ssl()
{
return current_protocol() == 'https';
}
//------------------------------------------------------------------------
function force_https()
{
if ( current_has_ssl() == false )
{
header( "HTTP/1.1 301 Moved Permanently" );
header( 'Location: https://example.com' );
exit();
}
}
//------------------------------------------------------------------------
// Usage:
force_https(); // at the top of a script before any output.
A:
You will need to enable SSL, if it is not already enabled
If you are going to run this in production, you will also need to purchase and
install an SSL cert instead of a self-signed cert.
If SSL is enabled, then running your form with https instead of http as the comment above says will work
To force users to use the SSL version add something like the following to your .htaccess file
RewriteEngine On
Rewritebase /
RewriteCond %{HTTPS} off
RewriteRule ^login\.php https://yourdomain.com/login.php [L,R=301]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
WPF change cursor for TabControl header text in XAML
I have tried the following below but it always ends up setting the cursor for all of the elements instead of just the TabControl header text.
<TabControl Cursor="Hand"></TabControl>
<TabItem Cursor="Hand"></TabItem>
Thinking I might have to override some template of some sort?
Thanks in advance.
A:
Try defining the structure of the header and assigning the cursor pointer to that:
<TabItem>
<TabItem.Header>
<TextBlock Text="Header goes here..." Cursor="Hand" />
</TabItem.Header>
<Label Content="Content goes here..." />
</TabItem>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using file paths in import statements python
I have the file structure of:
mainprogram.py
/Scripts
Data.py
where the file Data.py is in the folder Scripts, and contains a set of functions and mainprogram.py is trying to import those functions.
If Data.py was in the same folder as the file mainprogram.py, then I could simply write from Data import * and i would have all the defined functions from the file.
However, i always get the error: ModuleNotFoundError: No module named '__main__.Scripts'; '__main__' is not a package if I try to import it from the Scripts folder.
I have tried various methods including: from .Scripts.Data import * and from \\Scripts\\Data import *
Am I missing something, or is there a better way to import Data.py from a sub-folder?
A:
Have a look at https://docs.python.org/2/tutorial/modules.html:
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or the Python Imaging Library from having to worry about each other’s module names.
You need a __init__.py file (empty) in your Scripts folder. Then, you should be able to import Scripts.Data.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
cxf - how to create a REST NO soap endpoint on top of another endpoint
I have one endpoint already that is soap and now would like to create a non-soap interface that delivers the body of the POST into my methods (and would like simple GETs to work where I can just return a body of xml). I ran into this example
http://svn.apache.org/viewvc/cxf/trunk/distribution/src/main/release/samples/jax_rs/basic/src/main/java/demo/jaxrs/server/Server.java?view=markup
but those methods don't seem to exist on the latest version. This was geared towards JSON I believe but looks like it might work for my purposes. Is this even possible? In addition, I already have one endpoint like so and want to add this new one as well...
JaxWsServerFactoryBean svrFactory = new JaxWsServerFactoryBean();
svrFactory.setServiceClass(EnrollmentService.class);
svrFactory.setAddress("http://0.0.0.0:9000/enrollment");
svrFactory.setServiceBean(enrollmentSvc);
Server svr = svrFactory.create();
A:
Have a look at CXF Rest
I think what you need is a jax rs service. It support POST and several json providers are also available.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HTML inline style vs style attributes (which is better)
I have encountered a simple question but can't find the answer. The question is that, when I want to use inline style, for example width and height for an element in HTML, is it better to do it by width attribute or by inline style width?
<div style="width:${widthx}; height:${heightx};"></div>
VS.
<div width="${widthx}" height="${heightx}"></div>
what about one of them being deprecated or better for SEO solutions?
A:
Based on this MDN link for HTML Attributes, you should use style as attributes for <div> (or elements that are not <canvas>, <embed>, <iframe>, <img>, <input>, <object>, <video>) are considered legacy.
From the linked MDN article:
Note: For all other instances, such as <div>, this is a legacy attribute, in which case the CSS width property should be used instead.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MongoDB Inserting audio
I have inserted one million documents containing text into mongodb database through javascript and php. I would like to know how to insert one million documents related to audio/image into the database.
The script I used for inserting text :
var minDate = new Date(2012, 0, 1, 0, 0, 0, 0);
var maxDate = new Date(2013, 0, 1, 0, 0, 0, 0);
var delta = maxDate.getTime() - minDate.getTime();
var job_id = arg2;
var documentNumber = arg1;
var batchNumber = 5 * 1000;
var job_name = 'Job#' + job_id
var start = new Date();
var batchDocuments = new Array();
var index = 0;
while(index < documentNumber) {
var date = new Date(minDate.getTime() + Math.random() * delta);
var value = Math.random();
var document = {
created_on : date,
value : value
};
batchDocuments[index % batchNumber] = document;
if((index + 1) % batchNumber == 0) {
db.randomData.insert(batchDocuments);
}
index++;
if(index % 100000 == 0) {
print(job_name + ' inserted ' + index + ' documents.');
}
}
print(job_name + ' inserted ' + documentNumber + ' in ' + (new Date() - start)/1000.0 + 's');
Can a similar script be used to insert Audio/Image as well?
Thanks.
A:
Yes, but you'll need a powerful interpreter to accomplish this. It is possible to insert binary data into MongoDB using BinData, which needs a base64 string and cat() doesn't convert binary to string besides it fails reading binary data.
A quick workaround could be get the base64 string, save to a file, then read with cat() in your script. Example in node.js:
var fs = require('fs');
var b64Str = fs.readFileSync('file.mp3','base64');
fs.writeFileSync('base64ContentFile',b64Str);
Do it for every file you want to put in the database, then run your script changing the following:
var document = {
created_on : date,
value : new BinData(0,cat('base64ContentFile'))
};
A better solution would be use another language, a mongodb driver and do everything there. Read one file, parse it to a base64 string then insert into db, loop.
https://docs.mongodb.org/manual/reference/mongodb-extended-json/#binary
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Laravel array with illuminate objects
I am trying to pass images from AJAX to back-end and upload them, save their names into the database.
My AJAX code:
var form_data = new FormData($('.updateForm')[0]);
$.ajax({
method: "POST",
url: "/updateMyPost",
data: form_data,
cache : false,
contentType: false,
processData: false,
success: function (result) {
console.log(result);
}
});
Laravel function to upload the files:
public function updateMyPost(Request $request){
$name = $request->input('text');
$images = $request->file('images');
foreach($images as $image){
$image_name = time() . $image->getClientOriginalName();
$path = public_path('images');
$img->move($path,$image_name);
}
}
And this is what $request->file("images") gives to me when I print it out.
Array
(
[0] => Illuminate\Http\UploadedFile Object
(
[test:Symfony\Component\HttpFoundation\File\UploadedFile:private] =>
[originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => images.jpg
[mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => image/jpeg
[error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
[hashName:protected] =>
[pathName:SplFileInfo:private] => C:\xampp\tmp\phpAB87.tmp
[fileName:SplFileInfo:private] => phpAB87.tmp
)
[1] => Illuminate\Http\UploadedFile Object
(
[test:Symfony\Component\HttpFoundation\File\UploadedFile:private] =>
[originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => iphonex-TA.jpg
[mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => image/jpeg
[error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0
[hashName:protected] =>
[pathName:SplFileInfo:private] => C:\xampp\tmp\phpAB88.tmp
[fileName:SplFileInfo:private] => phpAB88.tmp
)
)
How can I get each image name and also upload them?
A:
As you said you are uploading multiple images so your store() method should like below
public function updateMyPost(Request $r)
{
$images = $r->images;
foreach($images as $image)
{
$path = $image->store('public/images');
$image_name = $image->getClientOriginalName();
// to store data in your table
Model::create([
'path' => $path,
'name' => $image_name
])
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
2005 Civic Lower Control Arm replacement or Bushing?
My Front Passenger side compliance bushing is bad. I can get the bushing for $27, or I can get the entire control arm (including bushing) for $41.
Wouldn't it be worth it just to change out the entire arm (since i have to remove the arm to get to the bushing anyways)?
It just seems like its worth it (to me, at least) to pay the extra $14 so I wouldn't need to remove the bad bushing and press in the new one.
I've never changed out a compliance bushing (or control arm), so is there anything I should watch out for?
Any advice is appreciated.
A:
Most control arm bushings require some type of mechanical or hydraulic press to install then in to the control arm. If you don't have access to a press you will have to pay someone to do it. This requires you to remove the arm and bring it somewhere. The cost in labor is likely going raise the cost to higher than the price of the arm with the bushing installed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to populate dropdown menu with sorted array
I have an array and i want to sorted it. However; I have an empty dropdown menu and i want to populated. Im stuck. How can populate my dropdown menu with the sorted array.
enter code here
<select id="dropdownList">
<option></option>
</select>
enter code here
var array = ["vintage","frames","treats","engraved", "stickers", "jewelerybox", "flask"];
array.sort(function(val1 , val2){
return val1.localeCompare(val2);
});
console.log(array); // ["engraved", "flask", "frames", "jewelerybox", "stickers", "treats",
A:
You can do it with for loop,by writing it to innerHTML of the select
var array = ["vintage", "frames", "treats", "engraved", "stickers", "jewelerybox", "flask"];
array.sort(function(val1, val2) {
return val1.localeCompare(val2);
});
var select = document.getElementById("dropdownList");
for (var i = 0; i < array.length; i++) {
select.innerHTML += '<option>' + array[i] + '</option>';
}
<select id="dropdownList">
</select>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Neopixel led strip stops responding after change in brightness
I have an arduino UNO hooked up to a neopixel LED strip with 148 lights. Most of the time it works fine, but when I upload a program that changes the brightness frequently, particularly when I increase brightness, only the first 8 LEDs continue responding. The rest get stuck.
Here's an example of the kind of code that sets this issue off. To fix it, I usually have to restart the lights and the arduino and sometimes upload a blank program to the arduino.
I'm pretty new to arduino programming so and help would be really appreciated. Thank you.
#include "FastLED.h"
FASTLED_USING_NAMESPACE
// FAST LED definitions
#define DATA_PIN 3
#define LED_TYPE WS2812B
#define COLOR_ORDER GRB
#define NUM_LEDS 148
CRGB leds[NUM_LEDS];
#define DATA_PIN 3 // Output Pin to Data Line on Strip
int fadeAmount = 5;
int brightness = 0;
void setup()
{
FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
}
void loop()
{
for(int i = 0; i < NUM_LEDS; i++ )
{
leds[i].setRGB(0,255,0);
leds[i].fadeLightBy(brightness);
}
FastLED.show();
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if(brightness == 0 || brightness == 255)
{
fadeAmount = -fadeAmount ;
}
delay(20);
}
A:
After doing more research and getting feedback on the Adafruit forum here, it appears that the problem was a cracked solder joint. I managed to get access to the strip and wiggled it a little and the problem has gone away. The recommendation is to reflow the joint by adding a little solder over the data connection between where the LEDs stop being responsive.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linux : add android platform to cordova
When I add android platform to my project by issuing the command:
cordova platform add android
I get the following error :
Unable to fetch platform android: Error: EACCES, mkdir '/home/mo3tssem/tmp/npm-13061-R9BWhlB2'
A:
Okay, so your /home/ubuntu/tmp has wrong permissions. It happened because you did sudo npm install in the past, and npm doesn't handle this well enough.
Run sudo chown ubuntu /home/ubuntu/tmp -Rv to fix this issue, or just delete that folder.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I extract data as object not array from MongoDB using Node.js/Express?
I'm learning MongoDB and Node.js. While I'm trying to making small database, I encountered a problem. The result of data is shown as array, not object.
What I want to do : show the result of data as object.
Data: [{"_id":"59e06e1dbbeee5a09e8fb46b","id":"123","name":"Dog chew toy","price":10.99},{"_id":"59e06e1dbbeee5a09e8fb46c","id":"456","name":"Dog pillow","price":25.99}]
When I type localhost:3000/findToy?id=123, the following data is shown.
[{"_id":"59e06e1dbbeee5a09e8fb46b","id":"123","name":"Dog chew toy","price":10.99}]
The data is array. But I want to show it as object like the below.
{"_id":"59e06e1dbbeee5a09e8fb46b","id":"123","name":"Dog chew toy","price":10.99}
How can I accomplish this?
index.js
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
var Animal = require('./Animal.js');
var Toy = require('./Toy.js');
var router = express.Router();
app.get('/findToy?:id', (req, res) => {
var query = {};
if(req.query.id) {
query.id = {$regex: req.query.id };
}
if(Object.keys(query).length == 0){
res.json({});
}
Toy.find(req.query.id,(err, toys) => {
if(err) {
res.type('html').status(500);
res.send('Error:' + err);
}
else {
res.json(toys);
console.log(toys)
}
})
});
app.listen(3000, () => {
console.log('Listening on port 3000');
});
module.exports = app;
A:
You can use the findOne method instead of find()
findOne documentation
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP E-mail Form: Different E-mails For Dropdown Menu
I've set up a PHP e-mail form and everything works fine. However, I'm not sure how to make it so different subject selections will send to different e-mail addresses. Could anyone please help me? Thank you.
HTML:
<label><strong>Subject:</strong></label>
<select name="subject" size="1">
<option value="General Feedback">General Feedback</option>
<option value="Book Information">Book Information</option>
<option value="Business Inquiries">Business Inquiries</option>
<option value="Website Related">Website Related</option>
</select>
PHP:
<?php
if(isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "The Official Website of Ricky Tsang <[email protected]>";
$email_subject = $_REQUEST['subject'];
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['full_name']) ||
!isset($_POST['email']) ||
!isset($_POST['subject']) ||
!isset($_POST['message'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$full_name = $_POST['full_name'];
$email_from = $_POST['email'];
$subject = $_POST['subject'];
$message= $_POST['message'];
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The e-mail you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$full_name)) {
$error_message .= 'The name you entered does not appear to be valid.<br />';
}
if(strlen($message) < 2) {
$error_message .= 'The message you entered doee not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Full Name: ".clean_string($full_name)."\n";
$email_message .= "E-mail: ".clean_string($email_from)."\n";
$email_message .= "Subject: ".clean_string($subject)."\n";
$email_message .= "Message: ".clean_string($message)."\n";
$email_from = $full_name.'<'.$email_from.'>';
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
Thank you for contacting The Official Website of Ricky Tsang. We will be in touch with you very soon.
<?php
}
?>
A:
May I suggest something like this:
HTML Snippet
You could construct the select using the options in the array below if you wanted.
<label>
<strong>Subject:</strong>
</label>
<select name="subject" size="1">
<option value="1">General Feedback</option>
<option value="2">Book Information</option>
<option value="3">Business Inquiries</option>
<option value="4">Website Related</option>
</select>
PHP Snippet
<?php
$subjects = array(
1 => array(
'to' => '[email protected]',
'subject' => 'General Feedback'
),
2 => array(
'to' => '[email protected]',
'subject' => 'Book Information'
),
3 => array(
'to' => '[email protected]',
'subject' => 'Business Inquiries'
),
4 => array(
'to' => '[email protected]',
'subject' => 'Website Related'
)
);
$email_to = ! empty($subjects[$_REQUEST['subject']]['to']) ? $subjects[$_REQUEST['subject']]['to'] : '[email protected]';
$email_subject = ! empty($subjects[$_REQUEST['subject']]['subject']) ? $subjects[$_REQUEST['subject']]['subject'] : 'Unknown subject';
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do i set this ACL on the router
I was told in a previous answer to use
ip access-list extended TEST
deny ip host <PC0 address> host <PC5 address>
permit ip any any
But, whats the command to set it on the router interface?
Like you would usually use ip access-group 101 out.
A:
I'm not sure I understand your question, but you seem to have the answer in your question:
ip access-group 101 out
Although, with extended access lists like 101, you should put them as close to the source as possible, so you normally would put that on the inbound interface, rather than the outbound interface:
ip access-group 101 in
The same would hold true for a named ACL:
ip access-group TEST in
Put a standard ACL on the outbound interface as close to the destination as possible (the interface to the destination), and an extended ACL as close to the source as possible (the interface from the source). This will keep a standard ACL from blocking too much traffic, and an extended ACL has both a source and destination, so it will keep the routers from routing traffic that will be dropped anyway.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Am I allowed to make these kinds of substitutions?
I am trying to solve this:
Let $$\dfrac{u(x+1)+u(x-1)}{2} = f(x) \tag 1$$
and $$\dfrac{u(x+4)+u(x-4)}{2} = g(x) \tag 2$$
Express $u$ in terms of $f$ and $g$.
My question is if the following steps are justified (I think they're not):
Make the substitutions $x\to x+4$ and $x \to x+1$ in $(1)$ and $(2)$ respectively
Let $$\dfrac{u(x+5)+u(x+3)}{2} = f(x+4) \tag 3$$
$$\dfrac{u(x+5)+u(x-3)}{2} = g(x+1) \tag 4$$
Subtract $(4)$ from $(3)$:
$$\dfrac{u(x+3)-u(x-3)}{2} = f(x+4)-g(x+1) \tag 5$$
I continue and get the solution doing a few more of these substitutions, but I am just not quite sure if the substitutions are valid.
I don't think that I can just combine $3$ and $4$, this is just abuse of notation, right? Because actually I am setting $x=a+4$ and $x=b+1$, so I can't pretend like $a$ and $b$ are independent.
A:
Hint: $$u(x+4) + u(x-4) = (u(x+4) + u(x+2)) - (u(x+2) + u(x)) - (u(x) + u(x-2)) + (u(x-2) + u(x-4)) + 2 u(x)$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Check if URL contains different strings
The code it self is pretty self explanatory, however i do not think it is very efficient at all. Is there a better way to do this?
Its basically so i can track spam sites and save the sites into my honeypot db.
<?php
$site = $_GET['url'];
$con=mysqli_connect("localhost","_","","_");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Gambling
if (strpos($site, "betting") ||strpos($site, "blackjack") ||strpos($site, "casino") ||strpos($site, "craps") ||strpos($site, "football") ||strpos($site, "gamble") ||strpos($site, "gambling") ||strpos($site, "game") ||strpos($site, "gaming") ||strpos($site, "greyhound") ||strpos($site, "highroller") ||strpos($site, "lottery") ||strpos($site, "lotto") ||strpos($site, "odds") ||strpos($site, "poker") ||strpos($site, "racehorse") ||strpos($site, "racing") ||strpos($site, "roulette") ||strpos($site, "royalflush") ||strpos($site, "slotmachine") ||strpos($site, "slots") ||strpos($site, "slotsmachine") ||strpos($site, "sport") ||strpos($site, "wager") ||strpos($site, "paigow") ||strpos($site, "bingo") ||strpos($site, "baccarat"))
{
//Insert into gambling
$result = mysqli_query($con,"INSERT INTO `rocket_newsites`.`gambling` (`id`, `url`) VALUES (NULL, '$site');");
}
//Payday
if (strpos($site, "payday") ||strpos($site, "loan") ||strpos($site, "bank") ||strpos($site, "money") ||strpos($site, "wonga") ||strpos($site, "lender") ||strpos($site, "credit") ||strpos($site, "debt") ||strpos($site, "repayment") ||strpos($site, "mortgage"))
{
//Insert into payday
$result = mysqli_query($con,"INSERT INTO `rocket_newsites`.`payday` (`id`, `url`) VALUES (NULL, '$site');");
}
//Lawyer
if (strpos($site, "law") ||strpos($site, "solicitor") ||strpos($site, "government") ||strpos($site, "injury") ||strpos($site, "personal") ||strpos($site, "accident") ||strpos($site, "advice") ||strpos($site, "traffic"))
{
//Insert into lawyer
$result = mysqli_query($con,"INSERT INTO `rocket_newsites`.`lawyer` (`id`, `url`) VALUES (NULL, '$site');");
}
//Weight Loss
if (strpos($site, "weight") ||strpos($site, "loss") ||strpos($site, "pills") ||strpos($site, "diet") ||strpos($site, "garcinia") ||strpos($site, "cambogia") ||strpos($site, "acai") ||strpos($site, "berry") ||strpos($site, "raspberry") ||strpos($site, "ketone") ||strpos($site, "coffee") ||strpos($site, "tea") ||strpos($site, "health") ||strpos($site, "lose") ||strpos($site, "surgery") ||strpos($site, "fat") ||strpos($site, "dieting") ||strpos($site, "exercise") ||strpos($site, "workout") ||strpos($site, "gym") ||strpos($site, "hypnosis"))
{
//Insert into weight loss
$result = mysqli_query($con,"INSERT INTO `rocket_newsites`.`weightloss` (`id`, `url`) VALUES (NULL, '$site');");
}
//Insurance
if (strpos($site, "ppi") ||strpos($site, "insurance") ||strpos($site, "payment") ||strpos($site, "claim") ||strpos($site, "calculator") ||strpos($site, "finance") ||strpos($site, "mis-sold"))
{
//Insert into insurance
$result = mysqli_query($con,"INSERT INTO `rocket_newsites`.`insurance` (`id`, `url`) VALUES (NULL, '$site');");
}
mysqli_close($con);
exit();
?>
A:
Why did you create multiple tables for each category?
Surely it would be better to have 1 single table with something like:
id - int
category - enum(lawyer, insurance, etc.)
url - varchar
You might want to have a look at this answer from StackOverflow for a better strpos alternative to your requirements: https://stackoverflow.com/a/9220624/367708
A:
You have a large amount of duplication in your conditions. additionally you have helluva lot of hardcoded strings all over the place. I suggest you change your structure to be something like:
<?php
$gamblingStrings = ["betting", "blackjack", "casino", "football", /*... */];
//Same for your other categories and then
if (matchesCategory($site, $gamblingStrings))
{
//insert into gambling
}
//and the corresponding function
private function matchesCategory($site, $strings) {
foreach ($strings as $matcher)
{
if(strpos($site, $matcher) !== false)
{
return true;
}
}
return false;
}
Disclaimer: My PHP is extremely rusty, the provided samples could be quite borked. But I hope you get the gist of it ;)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is using your thumb for jazz barre chords 'bad technique'?
When I play barre chords using jazz voicings such as in the following chord chart:
I often wrap my thumb around the neck to fret the E string. I prefer this, rather than using my first finger, as it makes it easier to play more complex chords since it frees up an extra finger. I want to know whether this is considered 'bad technique' and whether this has any negative long term effects on playing.
A:
Using your thumb isn't "bad technique" per se. It's either appropriate or it isn't, given the context in which you do it. For example, if this chord is sandwiched between two others which require the first finger barre, maybe it would be better to leave the finger down through those chords.
Bad technique is what I did when I started playing years ago, saw Jimi Hendrix using his thumb, and decided I didn't need to learn how to barre properly!
A:
Who has the power to decide? Any technique that works for an individual cannot be a bad one. Yes, purists may disagree, but it's not them playing, it's you! As stated already, an extra digit is always an asset, particularly on extended guitar chords. I'm only jealous, having small hands...
A:
The traditional arguments against wrapping the thumb around to fret the sixth string are that it slows the hand down when you need to change fingerings, and that it brings the other fingers closer to the strings so they are more likely to mute other strings unintentionally. This matches my experience; but if you can play quickly and cleanly with your thumb wrapped around, those reasons needn't bother you.
I find that when I try to fret with my thumb, or even just have my palm on the back of the neck, my wrist and fingers are flexed more, and there's more tension in my hand. Even when playing a barre, my hand feels much more relaxed if I have only my thumb on the back of the neck. This make it easier to play for a long time without getting sore.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
combining C\C++ translation units state?
I have a main.c file which includes a guarded (#ifndef...) c header, called mydefinitions.h.
In the header i declare an extern function, lets call it CppMain, to which i then call from the main.c file.
The CppMain function is defined in cppmain.cpp file which includes the (guarded) mydefinitions.h file as an extern "C" header.
The problem i am encountering is that a certain function, INIT_Pfn, which is declared and defined in the mydefinitions.h file is being defined multiple times (compiler argues multiple definitions of said method).
to my understanding the compiler is processing cppmain.cpp as a result of the definition of the said extern CppMain function but reprocess the mydefinitions.h since it is outside the scope of main.c and therefore the guard (#ifndef...) is being reinitialized - which, to me, is totally reasonable.
The main gist of the issue is that i'm trying to implement some logic in C++ as opposed to doing it all in C, but to keep the global scope\state of the main.c program translation.
Is there any way to avoid taking out the INIT_Pfn out of the mydefinitions.h file? Any other way you might think of implementing this solution without affecting mydefinitions.h?
the file also defines a global variable which has dependencies all over the source...
EDITTED (added code snippets):
mydefinitions.h:
#ifndef MyDefinitions
#define MyDefinitions
unsigned int GLOBAL_STATE = 0;
extern void CppMain();
#endif // !MyDefinitions
MyCPPFile.cpp:
#ifndef MyCPPFile
#define MyCPPFile
extern "C" {
#include "mydefinitions.h"
}
extern "C" void CppMain()
{
// cpp code here
}
#endif // !MyCPPFile
main.c file:
#include "mydefinitions.h"
int main(int argc, char *argv[])
{
CppMain();
}
A:
What's happening is that every object file compiled from source contains both the integer GLOBAL_STATE as well as a runtime initialiser for it. You only need it defined once.
In the header file, declare the variable extern:
extern unsigned int GLOBAL_STATE;
In your main C file, define it:
unsigned int GLOBAL_STATE = 0;
You don't need the #define MyCPPFile malarky in the CPP file.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Delete duplicate rows using custom logic
I'm stuck to find a way to remove some duplicate rows in a MySQL database using some custom logic.
Actual datas :
id name population
1 CityA 1000
2 CityA 50
3 CityA 0
4 CityB 0
5 CityB 0
6 CityC 10
Desired result :
id name population
1 CityA 1000
4 CityB 0
6 CityC 10
I tried this query without success (it has deleted all rows for a city if all populations are equal to 0, like in the CityB example):
DELETE t
FROM table AS t, table AS t2
WHERE t.id != t2.id
AND t.population <= t2.population
Could any super hero solve this super problem ?
[EDIT] The working solution : http://sqlfiddle.com/#!9/ea3e3/2
A:
You can do a join with a subquery that returns the ID of the row with the highest population for each city.
DELETE t1
FROM YourTable AS t1
JOIN (SELECT name, MAX(id) AS maxid
FROM YourTable AS t2
JOIN (SELECT name, MAX(population) AS maxpop
FROM YourTable
GROUP BY name) AS t3
ON t2.name = t3.name AND t2.population = t3.maxpop
GROUP BY t2.name) AS t4
ON t1.name = t4.name AND t1.id != t4.maxid
I needed an extra level of subquery nesting because you have multiple rows with the same population for a name. So it first needs to get the max population for each name, then select a particular ID within that group with MAX(id).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Splicing image array (FITS file) using coordinates from header
I am trying to splice a fits array based on the latitudes provided from the Header. However, I cannot seem to do so with my knowledge of Python and the documentation of astropy. The code I have is something like this:
from astropy.io import fits
import numpy as np
Wise1 = fits.open('Image1.fits')
im1 = Wise1[0].data
im1 = np.where(im1 > *latitude1, 0, im1)
newhdu = fits.PrimaryHDU(im1)
newhdulist = fits.HDUList([newhdu])
newhdulist.writeto('1b1_Bg_Removed_2.fits')
Here latitude1 would be a value in degrees, recognized after being called from the header. So there are two things I need to accomplish:
How to call the header to recognize Galactic Latitudes?
Splice the array in such a way that it only contains values for the range of latitudes, with everything else being 0.
A:
I think by "splice" you mean "cut out" or "crop", based on the example you've shown.
astropy.nddata has a routine for world-coordinate-system-based (i.e., lat/lon or ra/dec) cutouts
However, in the simple case you're dealing with, you just need the coordinates of each pixel. Do this by making a WCS:
from astropy import wcs
w = wcs.WCS(Wise1[0].header)
xx,yy = np.indices(im.shape)
lon,lat = w.wcs_pix2world(xx,yy,0)
newim = im[lat > my_lowest_latitude]
But if you want to preserve the header information, you're much better off using the cutout tool, since you then do not have to manually manage this.
from astropy.nddata import Cutout2D
from astropy import coordinates
from astropy import units as u
# example coordinate - you'll have to figure one out that's in your map
center = coordinates.SkyCoord(mylon*u.deg, mylat*u.deg, frame='fk5')
# then make an array cutout
co = nddata.Cutout2D(im, center, size=[0.1,0.2]*u.arcmin, wcs=w)
# create a new FITS HDU
hdu = fits.PrimaryHDU(data=co.data, header=co.wcs.to_header())
# write to disk
hdu.writeto('cropped_file.fits')
An example use case is in the astropy documentation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Detect text changed on textbox whilst ignoring databindings
I have some textboxes bound to a bindingsource and bindingnavigator.
I want to detect when the values have changed and prompt the users to confrim if they want to update.
When the form is first initalised and when then binding navigator moves to the next record the text_changed event fires on textbox where I have a boolean to determine if things have changed.
Is there a way to set my boolean only when valid data changes have occured or a better way to detect if things have changed
A:
Typically the way to do this is to note when the backing property of the textbox has changed.
So instead of checking the UI event you would do something like
Public Class myClass
private _myString As String = ""
private _isDirty As Boolean
Public Property MyString(ByVal _newString As String) As String
Get
Return _myStrig
End Get
Set
If Not _newString.Equals(_myString) Then
_myString = _newString
_isDirty = true
End If
End Set
End Property
'You could also just put a property on IsDirty and check that
Public Sub CanSave()
Return _isDirty
End Sub
End Class
Basically you verify that a value has actually changed before setting it, and then when you need to check if the Object isDirty you just check the _isDirty field.
You could also make use of INotifyPropertyChanged
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regex to find emoji names with colon and skintone
I'm using EmojiMart for my parser.
I've seen this related question but it seem to be different from mine.
So I need to return the emoji names or :code: for them to be able to decode it.
So example I have this text:
:+1::skin-tone-6::man-pouting:Hello world:skin-tone-
6:lalalalla:person_with_pouting_face: :poop::skin-tone-11: mamamia
:smile: :skin-tone-6:
It should match the whole :+1::skin-tone-6:
and not a separate :+1:, :skin-tone-6:: - only if there’s no space between them. (notice the space between :smile: and :skin-tone-6: )
Conditions:
It should only match the :code::skintone: if skintone is 2-6
If I do str.split(regex) this is my expected result (array):
- :+1::skin-tone-6:
- :man-pouting:
- Hello world
- :skin-tone-6:
- lalalalla
- :person_with_pouting_face:
- :poop:
- :skin-tone-11:
- mamamia
- :smile:
- :skin-tone-6:
A:
You may use String#split() with the
/(:[^\s:]+(?:::skin-tone-[2-6])?:)/
regex. See the regex demo.
Details
: - a colon
[^\s:]+ - 1+ chars other than whitespace and :
(?:::skin-tone-[2-6])? - an optional sequence of
::skin-tone- - a literal substring
[2-6] - a digit from 2 to 6
: - a colon.
JS demo:
var s = ":+1::skin-tone-6::man-pouting:Hello world:skin-tone-6:lalalalla:person_with_pouting_face: :poop::skin-tone-11: mamamia :smile: :skin-tone-6:";
var reg = /(:[^\s:]+(?:::skin-tone-[2-6])?:)/;
console.log(s.split(reg).filter(x => x.trim().length !=0 ));
The .filter(x => x.trim().length !=0 ) removes all blank items from the resulting array. For ES5 and older, use .filter(function(x) { return x.trim().length != 0; }).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Running upstart jobs as unprivileged users
What's the canonical way to have an upstart job change its userid and run the script as an unprivileged user?
Obviously one can use su or sudo, but this seems hacky (and can generate needless log lines).
A:
With upstart v1.4, setuid and setgid are supported natively in config file.
A:
Asking on the #upstart channel on freenode, the official take on the matter is:
A future release of Upstart will have
native support for that, but for now,
you can use something like:
exec su -s /bin/sh -c 'exec "$0" "$@"' username -- /path/to/command [parameters...]
A:
How about using start-stop-daemon?
exec start-stop-daemon --start --chuid daemonuser --exec /bin/server_cmd
From Upstart cookbook:
The recommended method for Debian and Ubuntu systems is to use the helper utility start-stop-daemon. […] start-stop-daemon does not impose PAM ("Pluggable Authentication Module") limits to the process it starts.
Note: start-stop-daemon not supported in RHEL.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the purpose of creating a struct with only one field
On the project in my company I saw a couple of times people creating a struct that contains only one element.
the latest one is added, in this example ipAddr is another struct( a good explanation to the case when ipAddr is an array is given by 'Frerich Raabe' but unfortunately thats not the case here)
typedef struct
{
ipAddr ip;
} Record;
I guess if the code is changing and in its beginning this makes sense since more fields can be easily added and the code can be easily manipulated to support the new fields, but this is a project started a long time ago written according to a design so I dont think its the issue here.
Why would one create a struct of one field then?
A:
I can think of a couple reasons:
In case more fields may be needed later. This is somewhat common.
To deliberately make the outer type incompatible with the inner type.
For an example of the second, imagine this:
typedef struct
{
char postal_code[12];
} Destination;
In this case, the Destination is fully specified by the postal code, yet this will let us define functions like this:
int deliver(const char* message, const Destination* to);
This way, no user can inadvertently call the function with the two arguments reversed, which they could easily do if they were both plain strings.
A:
A common reason for a struct with just one field is that the single field is an array, and you'd like to be able to define functions returning such array values. Consider e.g.
typedef unsigned char ipAddr[4];
void f(ipAddr ip); /* OK */
ipAddr g(void); /* Compiler barfs: cannot return array. */
This can be resolved by introducing a struct with a single member of type ipAddr:
typedef unsigned char ipAddr[4];
typedef struct {
ipAddr ip;
} Record;
void f(Record ip); /* OK */
Record g(void); /* Also OK: structs can be returned by value. */
However, even passing arrays to functions is problematic: you don't actually pass the array, you pass a pointer (the type "decays" into a pointer). Imagine f declared above would need to create a copy of the given IP address:
typedef unsignd char ipAddr[4];
void f(ipAddr ip) {
ipAddr *a = malloc(sizeof(ip));
/* ... */
}
This only happens to work with 32bit builds because the size of a pointer is the same (4 bytes) as the size of an array of four unsigned char values. A 64bit build (or a differently sized array) would exhibit a bug, either allocating too much or too little memory. This happens because inside f, ip is of type unsigned char *, i.e.a pointer. A struct helps with this, since it doesn't decay.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to speed up a jquery/php/ajax chatroom?
I've created a small jquery and php chatroom with some .get and .post functions and php docs that read and write data to a sql server. It works fine, but the small problem is when someone posts something, it takes about half a second for it to appear (because of the lag).
I fear there's something wrong with my coding.
im using
setinterval (listen, 300)
as my continuous jquery function for reading new db entries, listen is a function with a .get inside. How does stackoverflow or facebook do it so that the user types something in and immediately it pops out?
A:
Maybe try displaying the inputted chat message immediately to the user who posted it, prior to posting it to the database.
Like this:
User enters message, submits
Update users chat window so they see it immediately
POST message to database
GET from db and update all chat windows
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does it mean when my fridge sounds like a machine gun?
I have a fridge that I believe to be 20 to 25 years old. (It came with the house.) Not always, but sometimes when it finishes its cooling cycle, it makes a loud rattle-like sound, almost like three or four shots of a machine gun. It's quite loud when it does it, especially when I'm trying to sleep.
The fridge itself is cool inside. I've checked it for level, and it's perfect side to side, a hair low in the front. There is no ice maker.
Is there anything else that can cause a fridge to make a rattling sound? Is it possible the fridge is on its last legs?
A:
There may be an accumulation of dust and debris behind the unit and near the compressor. Also the bolts or fasteners that hold it all together there may need a little tightening- give it a good cleaning and look for accumulated dust on the fan and fan blades.
A:
Our old one did this just as it was powering down - we traced it to one of the supports for the compressor being loose, allowing the compressor to vibrate, and as it spun down it went through a particular resonant frequency which induced a wobble giving it a few bashes off a metal guide - sounded just like you describe.
We connected another spring to the support on that side and all was well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to bind text alignment in GridViewColumn
I'm using MVVM in a WPF application. I've a UserControl whose DataContext is set to a ViewModel. The UserControl is a table with 3 columns.
This is the following ListView/GridView:
<DockPanel>
<ListView DockPanel.Dock="Top" ItemsSource="{Binding Items}" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ctrl:ListViewLayoutManager.Enabled="True">
<ListView.View>
<GridView>
<GridViewColumn Header="{Binding ColumnHeader1}"
CellTemplate="{StaticResource cellTemplateColumn1}">
<GridViewColumn.HeaderContainerStyle>
<Style BasedOn="{StaticResource {x:Type GridViewColumnHeader}}" TargetType="GridViewColumnHeader">
<Setter Property="TextBlock.TextAlignment" Value="{Binding Column1HAlignment}" />
</Style>
</GridViewColumn.HeaderContainerStyle>
</GridViewColumn>
<GridViewColumn Header="{Binding ColumnHeader2}"
CellTemplate="{StaticResource cellTemplateColumn2}">
<GridViewColumn.HeaderContainerStyle>
<Style BasedOn="{StaticResource {x:Type GridViewColumnHeader}}" TargetType="GridViewColumnHeader">
<Setter Property="TextBlock.TextAlignment" Value="{Binding Column2HAlignment}" />
</Style>
</GridViewColumn.HeaderContainerStyle>
</GridViewColumn>
<GridViewColumn Header="{Binding ColumnHeader3}"
CellTemplate="{StaticResource cellTemplateColumn3}"
ctrl:RangeColumn.IsFillColumn="True">
<GridViewColumn.HeaderContainerStyle>
<Style BasedOn="{StaticResource {x:Type GridViewColumnHeader}}" TargetType="GridViewColumnHeader">
<Setter Property="TextBlock.TextAlignment" Value="{Binding Column3HAlignment}" />
</Style>
</GridViewColumn.HeaderContainerStyle>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</DockPanel>
This is achieved by the following resources:
<Style TargetType="GridViewColumnHeader">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="GridViewColumnHeader">
<TextBlock Text="{TemplateBinding Content}" Margin="5" Width="{TemplateBinding Width}">
</TextBlock>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="FontSize" Value="14" />
</Style>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
<DataTemplate x:Key="cellTemplateColumn1">
<fa:ImageAwesome Icon="{Binding IconType}" Foreground="{Binding Status}" Width="10" />
</DataTemplate>
<DataTemplate x:Key="cellTemplateColumn2">
<TextBlock Text="{Binding SerialNumber, StringFormat='0'}" />
</DataTemplate>
<DataTemplate x:Key="cellTemplateColumn3">
<TextBlock Text="{Binding Action}" TextWrapping="Wrap" />
</DataTemplate>
The text alignments of each column is settable through the view model. I can do this easily for the headers:
<GridViewColumn.HeaderContainerStyle>
<Style BasedOn="{StaticResource {x:Type GridViewColumnHeader}}" TargetType="GridViewColumnHeader">
<Setter Property="TextBlock.TextAlignment" Value="{Binding Column1HAlignment}" />
</Style>
</GridViewColumn.HeaderContainerStyle>
But how can I pass the same parameter (Column1HAlignment) to align the cell's TextBlock contents?
Note the alignment of the 2nd column (where header is #) in the image above. The header is right aligned through data binding. I want the same binding for each cell content.
A:
You could bind the HorizontalAlignment property of the element in the CellTemplate to the Column1HAlignment source property using a {RelativeSource}:
<DataTemplate x:Key="cellTemplateColumn2">
<TextBlock Text="{Binding SerialNumber, StringFormat='0'}"
HorizontalAlignment="{Binding DataContext.Column1HAlignment,
RelativeSource={RelativeSource AncestorType=ListView}}"/>
</DataTemplate>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Single id is not allowed on composite primary key in entity using knp paginator
I have a question about knp paginator.
I use Symfony 2.8.
I made a table that has composite primary key, and corresponding list page using knp paginator.
I'm receiving the exception when I try to show.
"Single id is not allowed on composite primary key in entity"
I tried to inspect source files of knp paginator and doctrine.
So I found a workaround.
1)Set knp option "distinct" to false;
2)Set following hints to query.
set "knp_paginator.count" to rows count of query result.
set "knp_paginator.fetch_join_collection" to false -- this is neccessary.
Is this right way?
Are there potential problems?
A:
The problem you might encounter is posted here in this related issue on GitHUB:
The only "problem" is when your Paginator query calls for a fetch join to a collection. The work around for this is to use a regular join as mentioned above. The drawback is that your paginated entities will not be hydrated with the collection. The collection will have to be lazy-loaded when called upon.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Format Date In Controller
I have the following form :
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="col-md-2 col-sm-2 col-xs-2 form-label">
{{Form::label('date', 'Data')}}
</div>
<div class="col-md-8 col-sm-10 col-xs-10">
<div class="input-group">
<span class="input-group-addon" id="interval">Inicial</span>
{{Form::text('dateini', null, ['class' => 'form-control'])}}
<span class="input-group-addon" id="interval">Final</span>
{{Form::text('datefim', null, ['class' => 'form-control'])}}
</div>
</div>
</div>
How put the date in the format " d / m / Y " before the end of this check the controller?
public function Empenhos(Request $request)
{
$query = DB::table('empenho as emp')
->select('emp.nrEmpenho as a',DB::raw("DATE_FORMAT(emp.date, '%d/%m/%Y') as b"))
->orderby('emp.nrEmpenho');
if ($request->dateini) $query->where('emp.date', '>=', $request->dateini);
if ($request->datefim) $query->where('emp.date', '>=', $request->dateini)
->where('emp.date', '<=', $request->datefim);
$table = $query->paginate($request->perPage ? $request->perPage : 20);
$header = ['Numero', 'Data', 'Tipo', 'Credor', 'Ficha', 'Fonte', 'Valor'];
return view('results.planejamento.empenhos',
['perPage' => $request->perPage, 'title' => $this->title,
'title2' => $this->title2[6], 'header' => $header, 'table' => $table, 'return' => 'Empenhos']);
}
Ps: Any questions about the code I am available to provide any information necessary !
My english is very bad , sorry, i'm brazilian and i had to look for help here.
A:
Laravel's using Carbon\Carbon as an interface of Datetime, so You can use it by binding your input:
$dateinit = \Carbon\Carbon::parse($request->dateini);
$datefim = \Carbon\Carbon::parse($request->datefim);
Now You can use Carbon object like this:
$dateinit->format('d/m/Y');
so the complete example code be like this:
`
public function Empenhos(Request $request)
{
$dateinit = \Carbon\Carbon::parse($request->dateini);
$datefim = \Carbon\Carbon::parse($request->datefim);
$query = DB::table('empenho as emp')
->select('emp.nrEmpenho as a',DB::raw("DATE_FORMAT(emp.date, '%d/%m/%Y') as b"))
->orderby('emp.nrEmpenho');
if ($request->dateini) $query->where('emp.date', '>=', $dateinit->format('d/m/Y'));
if ($request->datefim) $query->where('emp.date', '>=', $dateinit->format('d/m/Y'))
->where('emp.date', '<=', $datefim->format('d/m/Y'));
$table = $query->paginate($request->perPage ? $request->perPage : 20);
$header = ['Numero', 'Data', 'Tipo', 'Credor', 'Ficha', 'Fonte', 'Valor'];
return view('results.planejamento.empenhos',
['perPage' => $request->perPage, 'title' => $this->title,
'title2' => $this->title2[6], 'header' => $header, 'table' => $table, 'return' => 'Empenhos']);
}
`
The only question is the default format of your Database timestamp and the date field type.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should you deploy django with wsgi?
Do you need to deploy django with wsgi? I am running Django on a Docker instance and it seems like often the recommended solution is just to use Django's development server, i.e. the command python manage.py runserver. When exactly is a web server such as wsgi needed -- and in this instance, in a containerized application, is the django development server enough for production applications?
A:
You answer your own question:
is the django development server enough for production applications ?
In the django documentation, you can read the following:
Now’s a good time to note: don’t use this server in anything resembling a production environment. It’s intended only for use while developing. (We’re in the business of making Web frameworks, not Web servers.)
And also this part:
DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through security audits or performance tests. (And that’s how it’s gonna stay. We’re in the business of making Web frameworks, not Web servers, so improving this server to be able to handle a production environment is outside the scope of Django.)
So no. Don't use the Django development server in production. Security risks, poor performances, etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to stop ringtone manager in firebase notification it is playing but not stoping
I have one FCM based notification when I am receiving notification I am playing custom mp3 from row folder. But once notification comes ringtone manager started playing mp3 but it doesn't stop.
A:
I have solved this issue. Once I am getting notification from FCM I set the sound to null and play custom notification through Ringtone manager. Please note size and length of notification should be small.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Count number of foreign key columns, ignore system tables, display against each tablename
We use foll. query to count no. of primary key columns in a database:-
SELECT t.name,is_primary_key
FROM sys.indexes i
INNER JOIN sys.tables t ON i.object_id = t.object_id AND
t.type = 'U'
LEFT JOIN sys.extended_properties AS EP ON EP.major_id = T.
[object_id]
WHERE (EP.class_desc IS NULL
OR (EP.class_desc <> 'OBJECT_OR_COLUMN'
AND EP.[name] <> 'microsoft_database_tools_support'))
It ignores the columns in system tables.
Now we want to query for the number of foreign keys in the database. This should ignore the system tables and display the count against each tablename. Is this possible?
Below query returns all foreign keys in db, but I want to ignore the systabes.. Just like above query.
SELECT COUNT(*) AS 'FOREIGN_KEY_CONSTRAINT'
FROM sys.objects
WHERE type_desc IN ('FOREIGN_KEY_CONSTRAINT')
A:
Run the below query. This will work for the required purpose:
SELECT KC.Column_Name, t.Table_Name, tc.Constraint_Name FROM information_schema.table_constraints tc
LEFT JOIN information_schema.tables t ON tc.Table_Name = t.Table_Name
LEFT JOIN information_schema.KEY_COLUMN_USAGE kc ON kc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE constraint_type = 'FOREIGN KEY' AND TABLE_TYPE = 'BASE TABLE'
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Deleting old git tags
When I need to create new tag, I do the following steps:
Run command git tag -l | sort -V
Look through the list trying to find the latest tag
The list is looking like this:
aftercare-1.1.0
...
rc-1.1.0
...
rc-1.2.0
...
rc-1.3.0
...
rc-1.11.0
...
release-1.1.0
...
release-1.11.1
Sometimes (depends on project) we have a lot of tags and I can miss something looking through list and create tag with wrong name. I have such error couple of times.
When I use command git describe, it give me the last tag name, but sometimes I need to create a tag from another sequence.
Do you delete not meaningful tags (e.g. very old rc tags)? Maybe you have another naming conventions and don't have such problems? How do you know what tag should be the next?
A:
Do you delete not meaningful tags (e.g. very old rc tags)?
No, and why should you? Tags use up nearly no space (they're just a small pointer to a commit, with its own name). And the same way you don't delete old commits, old tags are part of your project's history and should stay in your repo.
Maybe you have another naming conventions and don't have such problems? How do you know what tag should be the next?
Use a branching model that makes it easy to see where your next tag should be deduced from. For example, have one long-running branch on which there will only be stable versions, and have another branch (either long-running or newly created each time) on which your RC versions get integrated.
You can read Vincent Driessen's workflow article for a good example of a branch model and workflow. With that, you should be able to derive some guidelines that work for your project and team.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can we use the word "pierce" for making big holes in something?
To me, the word "pierce" means making holes in something but it also connotes that the hole being made is very narrow and tight, which is why it doesn't sound right to use it to talk about woodpeckers pecking on trees and making almost big holes. But what is a word we can use to talk about that kind of hole making in something? (I assume the word "puncture" is similar to "pierce")
Edit: I'm not looking for a word specific to making holes on trees by woodpeckers. I'm looking for a verb for making big holes in something, if there is such a verb.
A:
If talking about big holes, I would use bore:
[Merriam-Webster]
transitive verb
1 : to pierce with a turning or twisting movement of a tool
// bore a wooden post
2 : to make by boring or digging away material
// bored a tunnel
// use a drill to bore a hole through the board
intransitive verb
1 a : to make a hole by or as if by boring
// insects that bore into trees
1 b : to sink a mine shaft or well
// boring for oil
The example sentence of "insects that bore into trees" is particularly apt if making a comparison to woodpeckers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is gettimeofday() guaranteed to be of microsecond resolution?
I am porting a game, that was originally written for the Win32 API, to Linux (well, porting the OS X port of the Win32 port to Linux).
I have implemented QueryPerformanceCounter by giving the uSeconds since the process start up:
BOOL QueryPerformanceCounter(LARGE_INTEGER* performanceCount)
{
gettimeofday(¤tTimeVal, NULL);
performanceCount->QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec);
performanceCount->QuadPart *= (1000 * 1000);
performanceCount->QuadPart += (currentTimeVal.tv_usec - startTimeVal.tv_usec);
return true;
}
This, coupled with QueryPerformanceFrequency() giving a constant 1000000 as the frequency, works well on my machine, giving me a 64-bit variable that contains uSeconds since the program's start-up.
So is this portable? I don't want to discover it works differently if the kernel was compiled in a certain way or anything like that. I am fine with it being non-portable to something other than Linux, however.
A:
Maybe. But you have bigger problems. gettimeofday() can result in incorrect timings if there are processes on your system that change the timer (ie, ntpd). On a "normal" linux, though, I believe the resolution of gettimeofday() is 10us. It can jump forward and backward and time, consequently, based on the processes running on your system. This effectively makes the answer to your question no.
You should look into clock_gettime(CLOCK_MONOTONIC) for timing intervals. It suffers from several less issues due to things like multi-core systems and external clock settings.
Also, look into the clock_getres() function.
A:
High Resolution, Low Overhead Timing for Intel Processors
If you're on Intel hardware, here's how to read the CPU real-time instruction counter. It will tell you the number of CPU cycles executed since the processor was booted. This is probably the finest-grained counter you can get for performance measurement.
Note that this is the number of CPU cycles. On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds. Converting this to a double is quite handy.
When I run this on my box, I get
11867927879484732
11867927879692217
it took this long to call printf: 207485
Here's the Intel developer's guide that gives tons of detail.
#include <stdio.h>
#include <stdint.h>
inline uint64_t rdtsc() {
uint32_t lo, hi;
__asm__ __volatile__ (
"xorl %%eax, %%eax\n"
"cpuid\n"
"rdtsc\n"
: "=a" (lo), "=d" (hi)
:
: "%ebx", "%ecx");
return (uint64_t)hi << 32 | lo;
}
main()
{
unsigned long long x;
unsigned long long y;
x = rdtsc();
printf("%lld\n",x);
y = rdtsc();
printf("%lld\n",y);
printf("it took this long to call printf: %lld\n",y-x);
}
A:
@Bernard:
I have to admit, most of your example went straight over my head. It does compile, and seems to work, though. Is this safe for SMP systems or SpeedStep?
That's a good question... I think the code's ok.
From a practical standpoint, we use it in my company every day,
and we run on a pretty wide array of boxes, everything from 2-8 cores.
Of course, YMMV, etc, but it seems to be a reliable and low-overhead
(because it doesn't make a context switch into system-space) method
of timing.
Generally how it works is:
declare the block of code to be assembler (and volatile, so the
optimizer will leave it alone).
execute the CPUID instruction. In addition to getting some CPU information
(which we don't do anything with) it synchronizes the CPU's execution buffer
so that the timings aren't affected by out-of-order execution.
execute the rdtsc (read timestamp) execution. This fetches the number of
machine cycles executed since the processor was reset. This is a 64-bit
value, so with current CPU speeds it will wrap around every 194 years or so.
Interestingly, in the original Pentium reference, they note it wraps around every
5800 years or so.
the last couple of lines store the values from the registers into
the variables hi and lo, and put that into the 64-bit return value.
Specific notes:
out-of-order execution can cause incorrect results, so we execute the
"cpuid" instruction which in addition to giving you some information
about the cpu also synchronizes any out-of-order instruction execution.
Most OS's synchronize the counters on the CPUs when they start, so
the answer is good to within a couple of nano-seconds.
The hibernating comment is probably true, but in practice you
probably don't care about timings across hibernation boundaries.
regarding speedstep: Newer Intel CPUs compensate for the speed
changes and returns an adjusted count. I did a quick scan over
some of the boxes on our network and found only one box that
didn't have it: a Pentium 3 running some old database server.
(these are linux boxes, so I checked with: grep constant_tsc /proc/cpuinfo)
I'm not sure about the AMD CPUs, we're primarily an Intel shop,
although I know some of our low-level systems gurus did an
AMD evaluation.
Hope this satisfies your curiosity, it's an interesting and (IMHO)
under-studied area of programming. You know when Jeff and Joel were
talking about whether or not a programmer should know C? I was
shouting at them, "hey forget that high-level C stuff... assembler
is what you should learn if you want to know what the computer is
doing!"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to fetch the data and display it in a browser simultaneously using PHP and Smarty?
I'm using PHP, MySQL, Smarty, jQuery, AJAX, etc. for my website. Currently, I'm fetching a large amount of data (matching question IDs) from the MySQL database, do processing on it, assigning this data to the Smarty template and printing it on a webpage. As the amount of data to be fetched is too large and it's going under further processing, it's taking too much time in getting the final output data. In turn, it takes too much time to display whole data to the user.
I have one approach in my mind but not able to implement it. My approach is to run the two processes of fetching the single matching question_id and displaying it to the browser simultaneously and repeat this cycle until all the matching question ids are fetched and displayed. As the loaded data of single row is getting displayed a loader image should get display under that displayed record. When all the data gets printed the loader image should vanish.
But the major issue I'm facing is how I should continuously assign the data to the Smarty template and display the template as the Smarty Template Engine first loads all the content and only after completely having the content it prints it to the browser.
For your reference I'm putting below all my existing code from Controller, Model and View:
The PHP code of Controller (match_question.php) is as follows:
<?php
require_once("../../includes/application-header.php");
$objQuestionMatch = new QuestionMatch();
$request = empty( $_GET ) ? $_POST : $_GET ;
if($request['subject_id']!="")
$subject_id = $request['subject_id'];
if($request['topic_id']!="")
$topic_id = $request['topic_id'];
if($subject_id !='' && $topic_id !='')
$all_match_questions = $objQuestionMatch->GetSimilarQuestionsBySubjectIdTopicId($subject_id, $topic_id);
$smarty->assign('all_match_questions', $all_match_questions);
$smarty->display("match-question.tpl")
?>
The PHP code of Model(QuestionMatch.php) is as follows:
<?php
class QuestionMatch {
var $mError = "";
var $mCheck;
var $mDb;
var $mValidator;
var $mTopicId;
var $mTableName;
function __construct() {
global $gDb;
global $gFormValidation;
$this->mDb = $gDb;
$this->mValidator = $gFormValidation;
$this->mTableName = TBL_QUESTIONS;
}
/**
* This function is used to get all the questions from the given subject id and topic id
*/
function GetSimilarQuestionsBySubjectIdTopicId($subject_id, $topic_id) {
/*SQL query to find out questions from given subject_id and topic_id*/
$sql = " SELECT * FROM ".TBL_QUESTIONS." WHERE question_subject_id=".$subject_id;
$sql .= " AND question_topic_id=".$topic_id;
$this->mDb->Query($sql);
$questions_data = $this->mDb->FetchArray();
/*Same array $questions_data is assigned to new array $questions to avoid the reference mismatching*/
$questions = $questions_data;
/*Array of words to be excluded from comparison process
*For now it's a static array but when UI design will be there the array would be dynamic
*/
$exclude_words = array('which','who','what','how','when','whom','wherever','the','is','a','an','and','of','from');
/*This loop removes all the words of $exclude_words array from all questions and converts all
*converts all questions' text into lower case
*/
foreach($questions as $index=>$arr) {
$questions_array = explode(' ',strtolower($arr['question_text']));
$clean_questions = array_diff($questions_array, $exclude_words);
$questions[$index]['question_text'] = implode(' ',$clean_questions);
}
/*Now the actual comparison of each question with every other question stats here*/
foreach ($questions as $index=>$outer_data) {
/*Logic to find out the no. of count question appeared into tests*/
$sql = " SELECT count(*) as question_appeared_count FROM ".TBL_TESTS_QUESTIONS." WHERE test_que_id=";
$sql .= $outer_data['question_id'];
$this->mDb->Query($sql);
$qcount = $this->mDb->FetchArray(MYSQL_FETCH_SINGLE);
$question_appeared_count = $qcount['question_appeared_count'];
$questions_data[$index]['question_appeared_count'] = $question_appeared_count;
/*Crerated a new key in an array to hold similar question's ids*/
$questions_data[$index]['similar_questions_ids_and_percentage'] = Array();
$outer_question = $outer_data['question_text'];
$qpcnt = 0;
//foreach ($questions as $inner_data) {
/*This foreach loop is for getting every question to compare with outer foreach loop's
question*/
foreach ($questions as $secondIndex=>$inner_data) {
/*This condition is to avoid comparing the same questions again*/
if ($secondIndex <= $index) {
/*This is to avoid comparing the question with itself*/
if ($outer_data['question_id'] != $inner_data['question_id']) {
$inner_question = $inner_data['question_text'];
/*This is to calculate percentage of match between each question with every other question*/
similar_text($outer_question, $inner_question, $percent);
$percentage = number_format((float)$percent, 2, '.', '');
/*If $percentage is >= $percent_match only then push the respective question_id into an array*/
if($percentage >= 85) {
$questions_data[$index]['similar_questions_ids_and_percentage'][$qpcnt]['question_id'] = $inner_data['question_id'];
$questions_data[$index]['similar_questions_ids_and_percentage'][$qpcnt]['percentage'] = $percentage;
/*$questions_data[$secondIndex]['similar_questions_ids_and_percentage'][$qpcnt]['question_id'] = $outer_data['question_id'];
$questions_data[$secondIndex]['similar_questions_ids_and_percentage'][$qpcnt]['percentage'] = $percentage;*/
/*Logic to find out the no. of count question appeared into tests*/
$sql = " SELECT count(*) as question_appeared_count FROM ".TBL_TESTS_QUESTIONS." WHERE test_que_id=";
$sql .= $inner_data['question_id'];
$this->mDb->Query($sql);
$qcount = $this->mDb->FetchArray(MYSQL_FETCH_SINGLE);
$question_appeared_count = $qcount['question_appeared_count'];
$questions_data[$index]['similar_questions_ids_and_percentage'][$qpcnt]['question_appeared_count'] = $question_appeared_count;
$qpcnt++;
}
}
}
}
} //}
/*Logic to create the return_url when user clicks on any of the displayed matching question_ids*/
foreach ($questions_data as $index=>$outer_data) {
if(!empty($outer_data['similar_questions_ids_and_percentage'])) {
$return_url = ADMIN_SITE_URL.'modules/questions/match_question.php?';
$return_url .= 'op=get_question_detail&question_ids='.$outer_data['question_id'];
foreach($outer_data['similar_questions_ids_and_percentage'] as $secondIndex=>$inner_data) {
$return_url = $return_url.','.$inner_data['question_id'];
}
$questions_data[$index]['return_url'] = $return_url.'#searchPopContent';
}
}
/*This will return the complete array with matching question ids*/
return $questions_data;
}
}
?>
The code of View(match-question.tpl) is as follows:
<table width="100%" class="base-table tbl-practice" cellspacing="0" cellpadding="0" border="0">
<tr class="evenRow">
<th width="33%" style="text-align:center;" class="question-id">Que ID</th>
<th width="33%" style="text-align:center;" class="question-id">Matching Que IDs</th>
<th width="33%" style="text-align:center;" class="question-id">Percentage(%)</th>
</tr>
{if $all_match_questions}
{foreach from=$all_match_questions item=qstn key=key}
{if $qstn.similar_questions_ids_and_percentage}
{assign var=counter value=1}
<tr class="oddRow">
<td class="question-id" align="center" valign="top">
<a href="{$qstn.return_url}" title="View question" class="inline_view_question_detail">QUE{$qstn.question_id}</a>{if $qstn.question_appeared_count gt 0}-Appeared({$qstn.question_appeared_count}){/if}
</td>
{foreach from=$qstn.similar_questions_ids_and_percentage item=question key=q_no}
{if $counter gt 1}
<tr class="oddRow"><td class="question-id" align="center" valign="top"></td>
{/if}
<td class="question" align="center" valign="top">
{if $question.question_id!=''}
<a href="{$qstn.return_url}" title="View question" class="inline_view_question_detail">QUE{$question.question_id}</a>{if $question.question_appeared_count gt 0}-Appeared({$question.question_appeared_count}){/if}
{if $question.question_appeared_count eq 0}
<a id ="{$question.question_id}" href="#" class="c-icn c-remove delete_question" title="Delete question"> Delete</a>{/if}
{/if}
</td>
<td class="question" align="center" valign="top">
{if $question.percentage!=''}{$question.percentage}{/if}
{assign var=counter value=$counter+1}
</td>
</tr>
{/foreach}
{/if}
{/foreach}
{else}
<tr>
<td colspan="2" align="center"><b>No Questions Available</b></td>
</tr>
{/if}
</table>
Thanks for the spending some of your valuable time in understanding my issue.
A:
I believe the bottleneck is on the looping over SQL queries. There is a standard way to rank search results on MySQL. You can simply implement full-text search.
First, you need to create a table like search_results:
SQL:
CREATE TABLE `search_results` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`result_title` varchar(128) CHARACTER SET utf8 NOT NULL,
`result_content` text CHARACTER SET utf8 NOT NULL,
`result_short_description` text CHARACTER SET utf8,
`result_uri` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '',
`result_resource_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `result_title` (`result_title`,`result_content`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
You have to insert all relevant data from the table of questions (including questions, subjects, answers, and whatever you want to search through them) into result_title and result_content here, (also update this table whenever it needs to be updated). There is also backtrack pointer to the original record of the corresponding table on result_resource_id. With a pre-defined URI result_uri pointing to the defined URL of the result in your website, you make everything faster. You don't need to create a URL each time.
Now, you can create a simple SQL query for a search query 'question?' in NATURAL LANGUAGE MODE:
SQL:
SELECT `result_title`, `result_content`, `result_uri`
FROM `search_results` WHERE MATCH(result_title, result_content) AGAINST('question?');
You can also add the relevance measurement into your query string. There are other modes for a search like boolean. Read the documents here and find the best solution.
Full-text indexing is faster and also more accurate in these use-cases.
A:
Assuming you want your content to load in the browser while it is still being streamed from the server to the client, if you are using tables - as you do - you may run into the problem of the browser (due to layout issues) not being able to render the table until all data is loaded.
You can see these tips for authoring fast-loading HTML pages and learn about tables in the according section.
Some crucial points:
If the browser can immediately determine the height and/or width of your images and tables, it will be able to display a web page without having to reflow the content. This not only speeds the display of the page but prevents annoying changes in a page's layout when the page completes loading. For this reason, height and width should be specified for images, whenever possible.
And:
Tables should use the CSS selector:property combination:
table-layout: fixed;
... and should specify widths of columns using the COL and COLGROUP HTML tags.
As well as:
Tables are still considered valid markup, but should be used for displaying tabular data. To help the browser render your page quicker, you should avoid nesting your tables.
You might also want to look into methods of streaming output from PHP.
See this question for details.
A:
In general, templating engines do not load content piecemeal - you'd need to send data to the browser in chunks manually, and flush between each bit. Template libraries usually compose the whole document in memory, and then dump it to the browser in one go. It's worth checking the Smarty manual though, just in case.
As an alternative, you could render the page without the large amount of data, and then load it in sections via AJAX. Whilst making, say, 10 AJAX connections serially adds a small extra overhead, it sounds like that will be minimal in comparison to your current rendering time. Even though your total rendering time may be slightly longer, the perceived rendering time for the user will be much faster, and of course they have the benefit that they can see data arriving.
I would kick off the first AJAX operation in jQuery upon domready, and when each completes, it can fire off another request. If your server can answer in JSON rather than HTML, it will allow the server to return a more_available Boolean flag, which you can use to determine if you need to do another fetch.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
simplejson dumps and multi lines
I have a little question.
I use simplejson to dumps a string.
This string contains some new line characters ( \n ),
so when I print it on the server side, I get something like that :
toto
tata
titi
And I want that it displays the same way on the client side (html).
So I did simply :
return json.dumps(data.replace('\n','<br />'))
And it works, but I don't think it's the good way to do it.
Is here another method ?
Thanks.
A:
I don't know the specifics of your situation, so maybe this is fine, but in general I'd recommend that you replace \n in the client, not on the server side. If someone wants to use your JSON API for non-HTML client, having <br> will be pretty annoying, and they'll just have to parse that back out. The server should convey the actual data, and the client should be responsible for turning that into information relevant to their user, including changing the formatting or markup if necessary.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to suppress overfull hbox warnings up to some maximum?
I want LaTeX not to give warnings for overfull hboxes up to some maximum of say 2 pts. How to achieve this?
A:
Tested it, works! See also this Wiki.
\documentclass{article}
\hfuzz=5.002pt
\begin{document}
looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
\end{document}
where \hfuzz=length is a parameter that allows hbox's to be overfull by length before an overfull error occurs.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
when i use dataType json it shows elment ] is missing in my ajax script
trying to use datatype json to get the value in json format but when i add it into my script it shows error that elemet ] is missing what am i doing wrong?
$(document).ready(function(){
$(window).scroll(function(){
var lastID = $('.load-more').attr('lastID');
if ($(window).scrollTop() == $(document).height() - $(window).height() && lastID != 0){
$.ajax({
type:'POST',
url:'<?php echo base_url("user/get_all_post"); ?>',
data:"id="+lastID,
dataType:'json',
beforeSend:function(html){
$('.load-more').show();
},
success:function(html){
//alert(html);
var ParsedObject = JSON.stringify(html);
var json = $.parseJSON(ParsedObject);
//alert(json);
/*
var json =" [{'id':1,'name':'Test1'},{'id':2,'name':'Test2'}]";
var jsonArray = eval('(' + json + ')');
for (i in jsonArray)
{
alert(jsonArray[i]["name"]);
}
*/
// alert(json.id);
var jsonArray = eval('(' + json + ')');
$PostId=jsonArray[4]["id"];
// alert($PostId);
for(i in jsonArray)
{
$post_status=jsonArray[i]["status"];
$status_image=jsonArray[i]["status_image"];
$multimage=jsonArray[i]["multimage"];
//alert(Lastid);
//alert($post_status);
//alert($status_image);
//alert($multimage);
$('.load-more').attr('lastID',$PostId);
$('#result_table').append(jsonArray);
}
}
});
}
});
});
</script>
i want to access my json data so that i can display it but all the variable shows undefined when i access then in my view
A:
I think I found a solution for this i was just adding everything in my code where i just needed to access my json value for that i only needed to parse the json value and then i can access the array in for loop
hope it helps other too
<script type="text/javascript">
$(document).ready(function(){
$(window).scroll(function(){
var lastID = $('.load-more').attr('lastID');
if ($(window).scrollTop() == $(document).height() - $(window).height() && lastID != 0){
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/get_all_post"); ?>',
data: "id=" + lastID,
dataType: 'json',
beforeSend:function(html){
$('.load-more').show();
},
success:function(data){
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
$PostId=json[4]['id'];
for(i as json)
{
var post_status = json[i]['status'];
$status_image = json[i]['status_image'];
var multimage = json[i]['multimage'];
alert($status_image);
$("#status_data").append('<div style=" margin: 20px 50px 0px 40px; ">'+'<a>'+'<?php echo img($user_image); ?>' +'</a>'+'<a>'+ ' <?php echo $uname; ?>' +'</a>'+'<div>'+post_status+'</div>' +'</div>');
$("#status_data").append('<div style=" margin: 20px 50px 0px 40px; ">'+'<a>'+'<?php echo img($user_image); ?>' +'</a>'+'<a>'+ ' <?php echo $uname; ?>' +'</a>'+'<div>'+'<img src="'+<?php base_url('uploads/'); ?> status_image+'">'+'</div>' +'</div>');
}
$('.load-more').attr('lastID', $PostId);
}
});
}
});
});
</script>
this would work there is no need for eval or jsonArray. thanks to everyone for replying.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Gregory House about evolution and global warming
I just found this quote from House M.D. Season 3 Episode 5
Dr. James Wilson: Your real fear is me having a good relationship.
Dr. Gregory House: Yes, it keeps me up at night. That and the Loch Ness Monster, global warming, evolution, other fictional concepts.
This makes me confused as this implies House doesn't accept global warming and evolution. This really seems inconsistent with his character. I can accept that he doesn't have enough information for global warming, but doubting evolution?
Does he ever say something else on the subject? I only found one scene where he references Darwin's natural selection: "he's eight years old and he swallowed something stuck to a fridge? Darwin says - let him die!".
Does House accept evolution and global warming?
A:
Judging from House's character as exhibited throughout the series, I think the conclusion you draw from that quote is rather the other way around.
If we know anything about House, he's extremely rational (or thinks to be) in his approach to problems, very unsympathetic of those who aren't and who place their emotions beyond reason (as exhibited in his bevaiour to a variety of his understandably distraught patients who don't always make the sanest decisions), and not a stranger to sarcasm.
So first, from his beliefs and scientific approach to things I would firmly believe that he is a proponent of evolution, which is somewhat of a signpost in the whole conflict between supposedly rational and scientific people and people more driven by less scientifically-based ideals. (Global warming might be a little more controversial than evolution among even scientists and embassadors of ratio, though, but I feel he might have the same attitude towards that.)
And from his general character I would strongly assume that's just part of a sarcastic remark mocking people who don't believe in evolution (or global warming). He's just taking some controversial topics and throwing them in the mix with an actual unreasonable belief. So the sarcasm works doubly, by pretending to pretend those things don't exist. If anything, he's just playing with the controversiality of a topic and exaggerating that conflict.
At least that's what I'd gather from what we know about House, as you already explained in your question.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mousemove / scroll to next hash
I added the following code in order to scroll with my mouse (scroll on click+drag, not by the mousewheel). So far, so good - works like a charm:
var clicked = false, clickY;
$(document).on({
'mousemove': function(e) {
clicked && updateScrollPos(e);
},
'mousedown': function(e) {
clicked = true;
clickY = e.pageY;
},
'mouseup': function() {
clicked = false;
$('html').css('cursor', 'auto');
}
});
var updateScrollPos = function(e) {
$('html').css('cursor', 'row-resize');
$(window).scrollTop($(window).scrollTop() + (clickY - e.pageY));
}
I am trying to change this scroll behavior so that each directional click+drag mouse movement jumps to the next/closest hash after e.g. a 10px drag. In other words, a mouse scroll up should jump to the next hash above the current position, scrolling down should jump to the next one below.
This doesn't seem to be covered by any of the related questions.
Edit:
I think I need to replace
$(window).scrollTop($(window).scrollTop() + (clickY - e.pageY));
by parts of the solution in the link that follows. Unfortunately, this seems to be above my skill level:
how to get nearest anchor from the current mouse position on mouse move
Solution:
I used Saeed Ataee's answer, really happy about that code, but replaced the mouse-wheel code portion with the following one I had in place already, just happened to work better on my end (I am sure his is fine, just giving an alternative here):
$('#nav').onePageNav();
var $current, flag = false;
$('body').mousewheel(function(event, delta) {
if (flag) { return false; }
$current = $('div.current');
if (delta > 0) {
$prev = $current.prev();
if ($prev.length) {
flag = true;
$('body').scrollTo($prev, 1000, {
onAfter : function(){
flag = false;
}
});
$current.removeClass('current');
$prev.addClass('current');
}
} else {
$next = $current.next();
if ($next.length) {
flag = true;
$('body').scrollTo($next, 1000, {
onAfter : function(){
flag = false;
}
});
$current.removeClass('current');
$next.addClass('current');
}
}
event.preventDefault();
});
A:
I hope this helps you
let currentElement = 0,
maxLength = $("div[id^='section']").length;
$(document).ready(function() {
$(document).on("mousewheel", function(e) {
if (e.originalEvent.wheelDelta > 0) {
currentElement = (currentElement > 0) ? currentElement - 1 : 0;
$("html, body").animate({
scrollTop: $("#section-" + currentElement).offset().top
},
200
);
} else {
currentElement = (currentElement < maxLength - 1) ? currentElement + 1 : currentElement;
$("html, body").animate({
scrollTop: $("#section-" + currentElement).offset().top
},
200
);
}
});
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="section-0">Section 1</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="section-1">Section 2</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="section-2">Section 3</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="section-3">Section 4</div>
</body>
</html>
A:
I think this is your answer.
let currentElement = 0,
maxLength = $("div[id^='section']").length,
changeSw = false;
$(document).ready(function() {
var clicked = false,
clickY;
$(document).on({
mousemove: function(e) {
clicked && updateScrollPos(e);
},
mousedown: function(e) {
clicked = true;
changeSw = true;
clickY = e.pageY;
},
mouseup: function() {
clicked = false;
changeSw = false;
$("html").css("cursor", "auto");
}
});
var updateScrollPos = function(e) {
$("html").css("cursor", "row-resize");
// $(window).scrollTop($(window).scrollTop() + (clickY - e.pageY));
if (changeSw && clickY - e.pageY > 0) {
currentElement =
(currentElement < maxLength - 1) ? currentElement + 1 : currentElement;
changeSw = false;
clicked = false;
} else if (changeSw && clickY - e.pageY <= 0) {
currentElement = currentElement > 0 ? currentElement - 1 : 0;
changeSw = false;
clicked = false;
}
console.log(currentElement)
$("html, body").animate({
scrollTop: $("#section-" + currentElement).offset().top
},
200
);
};
$(document).on("mousewheel", function(e) {
if (e.originalEvent.wheelDelta > 0) {
currentElement = currentElement > 0 ? currentElement - 1 : 0;
$("html, body").animate({
scrollTop: $("#section-" + currentElement).offset().top
},
200
);
} else {
currentElement =
currentElement < maxLength - 1 ? currentElement + 1 : currentElement;
$("html, body").animate({
scrollTop: $("#section-" + currentElement).offset().top
},
200
);
}
});
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="section-0">Section 1</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="section-1">Section 2</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="section-2">Section 3</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="section-3">Section 4</div>
</body>
</html>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to assign permissions to ApplicationPoolIdentity account
In IIS 7 on Windows Server 2008, application pools can be run as the "ApplicationPoolIdentity" account instead of the NetworkService account.
How do I assign permissions to this "ApplicationPoolIdentity" account. It does not appear as a local user on the machine. It does not appear as a group anywhere. Nothing remotely like it appears anywhere. When I browse for local users, groups, and built-in accounts, it does not appear in the list, nor does anything similar appear in the list. What is going on?
I'm not the only one with this problem: see Trouble with ApplicationPoolIdentity in IIS 7.5 + Windows 7 for an example.
"This is unfortunately a limitation of the object picker on Windows Server 2008/Windows Vista - as several people have discovered it already, you can still manipulate the ACL for the app-pool identity using command line tools like icacls."
A:
Update: The original question was for Windows Server 2008, but the solution is easier for Windows Server 2008 R2 and Windows Server 2012 (and Windows 7 and 8). You can add the user through the NTFS UI by typing it in directly. The name is in the format of IIS APPPOOL\{app pool name}. For example: IIS APPPOOL\DefaultAppPool.
IIS APPPOOL\{app pool name}
Note: Per comments below, there are two things to be aware of:
Enter the string directly into the "Select User or Group" and not in the search field.
In a domain environment you need to set the Location to your local computer first.
Reference to Microsoft Docs article: Application Pool Identities > Securing Resources
Original response: (for Windows Server 2008) This is a great feature, but as you mentioned it's not fully implemented yet. You can add the app pool identity from the command prompt with something like icacls, then you can manage it from the GUI. For example, run something like this from the command prompt:
icacls c:\inetpub\wwwroot /grant "IIS APPPOOL\DefaultAppPool":(OI)(CI)(RX)
Then, in Windows Explorer, go to the wwwroot folder and edit the security permissions. You will see what looks like a group (the group icon) called DefaultAppPool. You can now edit the permissions.
However, you don't need to use this at all. It's a bonus that you can use if you want. You can use the old way of creating a custom user per app pool and assigning the custom user to disk. That has full UI support.
This SID injection method is nice because it allows you to use a single user but fully isolate each site from each other without having to create unique users for each app pool. Pretty impressive, and it will be even better with UI support.
Note: If you are unable to find the application pool user, check to see if the Windows service called Application Host Helper Service is running. It's the service that maps application pool users to Windows accounts.
A:
You have to make sure that the From this location field is set to the local machine and not the domain.
I had the same issue and once I changed that it worked fine.
A:
You should really be creating groups per "role" and assigning that group accesses on the filesystem. Then add the app pool to the role-specific groups as necessary. This way even if you remove the app pool later (and the virtual user goes poof), you dont have to worry about redoing all the permissions, you just add the replacement app pool to the existing group.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why jvm expands byte & short to int before pushing on stack?
java code : ,
byte a_b = 12;
short c_d = 14
replaces in bytecodes with
bipush 12 // expands byte1 (a byte type) to an int and pushes it onto the stack
sipush 14 // expands byte1, byte2 (a short type) to an int and pushes it onto the stack
Why jvm does that expansion, and not use byte & short ?
Also when i open bytecode of my file
EDIT : short var = 14 is replaced by bipush 14 rather than sipush 14
Is my understanding is not clear or is there a bug ?
I am using following version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing)
A:
Because (conceptually) the smallest unit of data on the JVM stack is 32 bits. So there is no way to increase the size of the stack with just 8 bits.
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.6.2
At any point in time, an operand stack has an associated depth, where
a value of type long or double contributes two units to the depth and
a value of any other type contributes one unit.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unexpected behaviour of user.authenticate() with Rails in test environment
I want to make an acceptance test for the signing in flow, and I'm experiencing an unexpected behaviour of user.authenticate method.
Authentication in development environment works as expected: a POST with email and plain password pair passes it perfectly. The problem arises when I run tests: authentication with plain password fails. But strangely it succeeds with password's hash.
Here's the code:
class SessionsController < ApplicationController
...
def create
user = User.find_by_email(params[:email].downcase)
logger.debug Rails.env
logger.debug "password #{params[:password]}"
logger.debug user.authenticate(params[:password]).to_yaml
...
And here are logs for different environments:
env development
password 123456
--- !ruby/object:User
env test
password 123456
--- false
env test
password $2a$10$70AlnpaXIMHtjDUei/1HU.OSEG4WVjW6ens3jzN04bC8SOxTv2Ftm
--- !ruby/object:User
Any idea what can I do so that authentication succeeds with plain passwords in the test environment?
I'm using bcrypt-ruby for passwords in ActiveModel objects.
Thanks.
A:
Here:
factory :user do
first_name "Gustav"
password { BCrypt::Password.create("123456") }
end
You're creating a password being digest for given string. Change it to:
password "123456"
password_confirmation { password }
and let BCrypt create the digest.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Target individual XCTest unit test cases in Xcode 5 to a specific iOS device for a universal app?
I'm building a universal iPhone/iPad application, and the UI is significantly different in some cases (i.e. on iPhone we use a Master/Detail paradigm with TableViews, whereas on iPad we're using a CollectionView with cells that contain the details).
Because the interfaces are so different, it changes how the unit tests for the view controllers are constructed. In the collection view, we'd have to test to make sure the cells get built correctly and contain all the detailed information, whereas on iPhone we'd need two sets of tests - one for the master list and one for the detail screen.
So my question is, in a universal application being built using Xcode 5 with XCTest framework, can you target individual unit test cases / classes to be run on specific physical devices?
I came across a similar question here - iOS Unit testing universal application - but the asker had different intentions and was using older technologies.
I've also seen recommendations to do a check in individual test functions for UserInterfaceIdiom but that seems really crude. Ideally, there would be an annotation that would designate specific tests run on specific devices, or be able to designate an entire test class for a specific device.
Thanks in advance for your suggestions.
--EDIT--
@TommieC led me down what seems to be the appropriate path, if a smidge manual. I created two new testing specific schemes, one for phone-sized devices, and one for tablet-sized devices. Inside those schemes, I edited the test portion and added in the core tests along with the device-specific tests.
I then have jenkins execute two build steps, targeting the appropriate devices to test for the particular scheme. The downside to this approach is two build steps. However, I plan to split up the jenkins job and run it on 2 slaves with the appropriate devices hooked to each to parallelize the testing.
AFAIK this will also be Xcode Build Services friendly, as it works based off of schemes in a project as well. It's really too bad there isn't something more elegant built into XCTest for this, considering this doesn't scale terribly well in the event a new device type comes into play (watch/tv/hair dryer/etc.)
A:
To target device specific tests one would need to edit the schemes for a project. Under Product > Scheme > Edit Schemes one can choose to select device specific tests per device.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to call a function with two arguments in python
i wanna ask about how to call a function with two arguments in python. for example,
code below is an example i want to call color function.
def color(object):
return '\033[1;34m'+object+'\033[1;m'
tes = 'this must be blue'
print color(tes)
but that's just for one argument alone.
then I want to make the two arguments together with a selection of different colors.
This below for my dummy code.
def color(object,arg2):
blue = '\033[1;34m'+object+'\033[1;m'
red = '\033[1;31m'+object+'\033[1;m'
tes = 'this must be blue'
tes_2 = 'i wanna this string into red!!'
print color(tes,red)
well, that's just my dummy code and which would be an error like this..
print color(tes,red)
NameError: name 'red' is not defined
Can you tell me how to make a well-functioning in python?? ty
A:
The small but fundamental errors in your second block:
Your arguments are object and arg2. objectis a reserved python word, both words are not so explanatory and (the real mistake) you never use arg2 in your function.
You don't used any return value in the function.
When you call the function, you use color(tes,red) when it should be color(tes,tes_2).
I have rewritten the block, take a look (with some modifications you can fine-tune later)
def color(color1,color2):
blue = '\033[1;34m'+color1+'\033[1;m'
red = '\033[1;31m'+color2+'\033[1;m'
return blue, red
tes = 'this must be blue'
tes_2 = 'i wanna this string into red!!'
for c in color(tes,tes_2):
print c
An alternate suggestion to achieve what you want would be:
def to_blue(color):
return '\033[1;34m'+color+'\033[1;m'
def to_red(color):
return '\033[1;31m'+color+'\033[1;m'
print to_blue('this is blue')
print to_red('now this is red')
EDIT: as requested (this is just the beginning ;oP . For example, you could use a dictionary of color names and color codes to call the function)
def to_color(string, color):
if color == "blue":
return '\033[1;34m'+color+'\033[1;m'
elif color == "red":
return '\033[1;31m'+color+'\033[1;m'
else:
return "Are you kidding?"
#should be 'raise some error etc etc.'
print to_color("this blue", "blue")
print to_color("this red", "red")
print to_color("his yellow", "yellow")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does Rust not allow the copy and drop traits on one type?
From the book:
Rust won’t let us annotate a type with the Copy trait if the type, or any of its parts, has implemented the Drop trait. If the type needs something special to happen when the value goes out of scope and we add the Copy annotation to that type, we’ll get a compile time error.
Why was the design decision made to disallow Copy and Drop on the same type?
A:
The Drop trait is used in an RAII context, typically when some resource needs to be released/closed when the object is destroyed.
In the other hand, a Copy type is a trivial type that can be copied with a memcpy only.
With those two descriptions, it is clearer that they are exclusive: it makes no sense to memcpy nontrivial data: what if we copy the data, and we drop one of the copies? The inner resource of the other copy will not be reliable anymore.
In fact, Copy in not even a "real" trait, in that it does not define any function. It is a special marker that says to the compiler: "you can duplicate myself with a simple bytes copy". So you cannot provide a custom implementation of Copy, because there is no implementation at all. However, you can mark a type as copyable:
impl Copy for Foo {}
or better, with a derive:
#[derive(Clone, Copy)]
struct Foo { /* ... */ }
This builds only if all the fields implement Copy. Otherwise, the compiler refuses to compile because this is unsafe.
For the sake of an example, let's suppose that the File struct implements Copy. Of course, this is not the case, and this example is wrong and cannot compile:
fn drop_copy_type<T>(T x)
where
T: Copy + Drop,
{
// The inner file descriptor is closed there:
std::mem::drop(x);
}
fn main() {
let mut file = File::open("foo.txt").unwrap();
drop_copy_type(file);
let mut contents = String::new();
// Oops, this is unsafe!
// We try to read an already closed file descriptor:
file.read_to_string(&mut contents).unwrap();
}
A:
Quoting the documentation.
[...] [A]ny type implementing Drop can't be Copy, because it's managing some resource besides its own size_of::<T> bytes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
'HTTP/1.1 301 Moved Permanently' EIdHTTPProtocolException
procedure TForm1.ExtractLinks(const URL: String; const StringList: TStringList);
{ Extract "href" attribute from A tags from an URL and add to a stringlist. }
var
i: Integer;
iDoc: IHTMLDocument2;
iHTML: String;
iv: Variant;
iLinks: OleVariant;
iDocURL: String;
iURI: TidURI;
iHref: String;
iIdHTTP: TidHTTP;
iListItem: TListItem;
begin
StringList.Clear;
ListView1.Clear;
iURI := TidURI.Create(URL);
try
iDocURL := 'http://' + iURI.Host;
if iURI.Path <> '/' then
iDocURL := iDocURL + iURI.Path;
finally
iURI.Free;
end;
iDoc := CreateComObject(Class_HTMLDOcument) as IHTMLDocument2;
try
iDoc.DesignMode := 'on';
while iDoc.ReadyState <> 'complete' do
Application.ProcessMessages;
iv := VarArrayCreate([0, 0], VarVariant);
iIdHTTP := TidHTTP.Create(nil);
try
iHTML := iIdHTTP.Get(URL);
finally
iIdHTTP.Free;
end;
iv[0] := iHTML;
iDoc.Write(PSafeArray(System.TVarData(iv).VArray));
iDoc.DesignMode := 'off';
while iDoc.ReadyState <> 'complete' do
Application.ProcessMessages;
iLinks := iDoc.All.Tags('A');
if iLinks.Length > 0 then
begin
ListView1.Items.BeginUpdate;
for i := 0 to -1 + iLinks.Length do
begin
iHref := iLinks.Item(i).href;
if (iHref[1] = '/') then
iHref := iDocURL + iHref
else if Pos('about:', iHref) = 1 then
iHref := iDocURL + Copy(iHref, 7, Length(iHref));
if (IsValidURL(iHref)) and (IsKnownFormat(iHref)) then
begin
StringList.Add(iHref);
iListItem := ListView1.Items.Add;
iListItem.Caption := iHref;
end;
ListView1.Items.EndUpdate;
end;
end;
finally
iDoc := nil;
end;
end;
procedure TForm1.GetLinks1Click(Sender: TObject);
var
iUrlList: TStringList;
begin
iUrlList := TStringList.Create;
try
{ Get the url list }
ExtractLinks(Url1.Text, iUrlList);
finally
iUrlList.Free;
end;
end;
On some websites this code produces a list of image urls but on some websites it produces a 'HTTP/1.1 301 Moved Permanently' EIdHTTPProtocolException. Is it possible to get a list of Img urls from a web page url or am I doing something incorrectly?
A:
Set iIdHTTP.HandleRedirects := True so it starts automatically handling redirects.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to limit access to various services per user using Django-mama-CAS?
I am using django-mama-cas module to implement Single Sign On for third-party apps. Is there a way to limit access to different services for each user ?
I know there is an option in the settings : MAMA_CAS_VALID_SERVICES to limit valid URLs but what I am interested in limiting access to some of these services per user.
A:
The simplest way to do this is to implement a custom callback. The callback is passed both the user object and the service URL, so you can limit access based on whatever combinations are required. If the test fails, raise PermissionDenied to abort the request (the same thing that is done if an invalid service is provided). If you do not require any custom attributes, simply return an empty dictionary on success.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Butterknife bind SearchView from Menu
In my current Android project I use the Butterknife library to bind views and use onClick annotations for them. This all works great even in fragments but now I'm at the point where I can't find a solution:
I use the new ToolBar as ActionBar and inflate a Menu with a SearchView in it. For this SearchView I want to use the @OnTextChanged annotation but when I call the bind method with the ActionView of the menu item Butterknife tries to reinstanciate all Views again and of course in the ActionView it can not find any other Views of the RootLayout.
So is there a way to add only one View with Butterknife or can I get a View which contains all Views from my RootLayout and the ToolBarView so I can pass this View to the bind method? For example in Activites I can call findViewById also for menu IDs but if I use getView() from my Fragment it does not work. Any ideas for this?
A:
I think this is not possible since the SearchView is a menu item. The id you are using in the menu declaration identifies this view within the menu, not the activity's view, thats probably why Butterknife is no able to bind it.
I'm afraid you will have to do:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.bookings_list_menu, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setOnSearchClickListener(...);
searchView.setOnCloseListener(...);
searchView.setOnQueryTextListener(...);
super.onCreateOptionsMenu(menu, inflater);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Wordpress Unexpected margin on html, body
I'm developing a WordPress Theme from Scratch. I'm new in WordPress theming, when I put my local website on wordpress I got an unexpected margin. Don't know where its come form.
Its look like this, Margin on top,
When I inspected, I got This, Can't understand from where the code comes,
Anyone please help me,
Note: I'm working on local, So that I can't provide any link or code.
A:
WordPress reserves this space for the Admin toolbar when you are logged in. It can be disabled in profile settings.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Hoare-Ramshaw (two dots) interval notation
In a Mma notebook math cell, how can one write an interval with Hoare-Ramshaw (two dots) interval notation? The obvious answer (\:2025) does not seem to work; two full stops produces odd spacing; and the inferior but crudely acceptable two full-stops surrounded by spaces produces an unwanted times symbol.
A:
You can type \:2025 to get the unicode character.
If you prefer to use a keyboard alias, evaluate
SetOptions[
SelectedNotebook[],
InputAliases ->
Join[Options[SelectedNotebook[], InputAliases][[1, 2]], {"hr" -> "\:2025"}]]
in your note book, then EschrEsc will insert the unicode character ‥ into the cell where you currently typing.
Either way you will be able to produce text cells like
$\qquad$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JS: Sum of span values in For loop
I have the following values within span tags:
<div id="aantallen">
<span>3</span>
<span>2</span>
</div>
In JS I want to get the sum of these values. So I made the following For Loop:
var div = document.getElementById("aantallen");
var spans = div.getElementsByTagName("span");
for(i=0;i<spans.length;i++)
{
var totaalPersonen = totaalPersonen + i;
alert(totaalPersonen);
}
However, the 3 and 2 are text, so I get Nan in the alerts. My question: how can in convert the 3 and 2 into strings so that I can make a sum of these values?
I tried with String(i) but couldn't get it to work.
A:
You need to convert the content of the DOM element to a Number.
Then, you can use reduce in order to calculate the sum.
const spans = document.querySelectorAll('#aantallen span');
const result = Array.from(spans).reduce((sum, spanElm) => sum + Number(spanElm.textContent), 0)
console.log(result);
<div id="aantallen">
<span>3</span>
<span>2</span>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to add a logo to this wordpress code
I downloaded this free WP Simple theme and is modifying mostly everything in the backend. Otherwise, I'll have to pay more and I heard from some people who said that they paid for this theme and didn't get all the features and support they wanted.
Anyway, I'm trying to add the logo to this code
<?php
$nimbus_image_logo = trim(nimbus_get_option('nimbus_image_logo'));
$nimbus_text_logo = trim(nimbus_get_option('nimbus_text_logo'));
if (empty($nimbus_image_logo)) {
if (!empty($nimbus_text_logo)) {
?>
<h1 class="text_logo"><a href="<?php echo esc_url(home_url('/')); ?>"><?php echo $nimbus_text_logo; ?></a></h1>
<?php
}
} else {
?>
<a class="" href="<?php echo esc_url(home_url('/')); ?>"><img class="image_logo" src="<?php echo $nimbus_image_logo; ?>" alt="<?php echo get_bloginfo('name', 'display'); ?>" /></a>
<?php
}
?>
The logo url is "<?php bloginfo('template_url');?>/images/Novalogo.png".
I tried adding it to $nimbus_image_logo = at top, but it's not working. I also tried to add and replace it at <?php echo $nimbus_image_logo; ?> but it's not working also.
How do I fix it?
A:
If you want a simple solution for an image only logo, replace everything with just this line.
<a class="" href="<?php echo esc_url(home_url('/')); ?>"><img class="image_logo" src="<?php bloginfo('template_url');?>/images/Novalogo.png" alt="<?php echo get_bloginfo('name', 'display'); ?>" /></a>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to add product in cart programmatically in prestashop
I am using prestashop 1.5.3 and i am developing a payment gateway problem is this i couldn't find how to add product programmatically in cart and order for adding payment fee
Please anyone help me
A:
Below is the code for adding multiple products programatically. Can be use to add one product also. Put these code in a file called test.php on your website root and then run it like this /test.php??products_ids=11,9,10 where 11, 9,10 are 3 products id. Hope this helps.
<?php
require(dirname(__FILE__).'/config/config.inc.php');
$context=Context::getContext();//new Cart();
$id_cart=$context->cookie->__get('id_cart');
$products_ids=$_GET['products_ids']; // comma seprated products id example : test.php?products_ids=1,2,3
$products_ids_array=explode(",",$products_ids);
if(count($products_ids_array)>0){
$cart=new Cart($id_cart);
$cart->id_currency=2;
$cart->id_lang=1;
foreach($products_ids_array as $key=>$id_product){
$cart->updateQty(1, $id_product);
}
}
?>
A:
you can place this code in a php file in your Root directory and use a simple form directing to this page containing product id & quantity.
Just change:
<?php
$idProduct= 19825 to $idProduct=$_POST["txtproductid"]
$qty=5 to $qty=$_POST["txtqty"];
$useSSL = true;
include('/config/config.inc.php');
include('/header.php');
global $params;
$errors = array();
$idProduct =19825;
$qty=5;
if ($cookie->isLogged())
{
/* Cart already exists */
if ((int)$cookie->id_cart)
{
$cart = new Cart((int)$cookie->id_cart);
}
if (!isset($cart) OR !$cart->id)
{
$cart = new Cart();
$cart->id_customer = (int)($cookie->id_customer);
$cart->id_address_delivery = (int) (Address::getFirstCustomerAddressId($cart->id_customer));
$cart->id_address_invoice = $cart->id_address_delivery;
$cart->id_lang = (int)($cookie->id_lang);
$cart->id_currency = (int)($cookie->id_currency);
$cart->id_carrier = 1;
$cart->recyclable = 0;
$cart->gift = 0;
$cart->add();
$cookie->id_cart = (int)($cart->id);
}
/* get product id and product attribure id */
$data = explode(",", $product);
$idProduct = $data[0]; */
$idProductAttribute = $data[1];
if ($qty != '')
{
$producToAdd = new Product((int)($idProduct), true, (int)($cookie->id_lang));
if ((!$producToAdd->id OR !$producToAdd->active) AND !$delete)
/* Product is no longer available, skip product */
continue;
/* Check the quantity availability */
if ($idProductAttribute > 0 AND is_numeric($idProductAttribute))
{
if (!$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) AND !Attribute::checkAttributeQty((int)$idProductAttribute, (int)$qty))
{
/* There is not enough product attribute in stock - set customer qty to current stock on hand */
$qty = getAttributeQty($idProductAttribute);
}
}
elseif (!$producToAdd->checkQty((int)$qty))
/* There is not enough product in stock - set customer qty to current stock on hand */
$qty = $producToAdd->getQuantity(idProduct);
$updateQuantity = $cart->updateQty((int)($qty), (int)($idProduct), (int)($idProductAttribute), NULL, 'up');
$cart->update();
}
/* redirect to cart
if (!sizeof($errors)) */
Tools::redirect('order.php');
}
else
{
Tools::redirect('/index.php');
}
$smarty->assign(array(
'id_customer' => (int)($cookie->id_customer),
'errors' => $errors
));
include_once('/footer.php');
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++ and when to use delete
I am re-reading some code from a while ago on C++ (I am learning Java in school right now),
and I am a little confused as to when I must use delete.
For example:
When declaring two objects:
Fraction* f1;
Fraction* f2;
And create f1 and f2 like this:
f1 = new Fraction(user_input1, user_input2);
f2 = new Fraction(user_input3, user_input4);
The next time I want to use new operator to create a new object, do I have to delete first? I am confused because I am used to having the garbage collector in java take care of objects and their deletion. Do I have to delete before using new again?
if (f1) delete f1;
if (f2) delete f2;
//initialize again...
A:
Rather then telling you when to use delete, I'll try to explain why you use pointers anyway. So you can decide when to use dynamic objects, how to use them and so when to call delete (and not).
Thumb of rules:
Use static objects where possible, then when needed create a pointer to that instance. No delete call needed.
If you create a pointer to a dynamic object, create clean up code. So when you write new also write delete somehwere at a suitable location (and make sure that is called).
For every new keyword there needs to be a delete keyword. Otherwise you are taking all the resources the machine has resulting in applications to crash or just stop. Also it will make the system slower.
Static creation of an object:
Fraction f1;
No need to delete anything, that is handled when exiting the scoop it is created in.
Dynamic creation of an object:
Fraction* f1;
Now you have this address to a memory block on the heap. It is an invalid one since you haven't assigned anything to it. Good practise would be - depending on where you declare it - to assign it a NULL (windows) or 0 (cross-platform).
Fraction* f1 = 0;
When to use delete
As soon as you create a dynamic object, thus calling the new operator, you need to call delete somewhere.
int main()
{
Fraction* f1 = 0; // Good practise to avoid invalid pointers
// An invalid pointer - if( f1 ){ Access violation }
f1 = new Fraction(); // Could have done this at the previous line
/* do whatever you need */
if( f1 )
{
delete f1;
f1 = 0; // not needed since we are leaving the application
}
return 0;
}
In some scenarios it could be usefull to have an array of Fraction, or pointers to it. Using an int for simplicity here, same as skipping error handling:
int arr[ 10 ];
int cur = -1;
int* Add( int fraction )
{
arr[++cur] = fraction;
return &arr[cur];
}
// Usage:
Add( 1 );
Add( 4 );
One thing happening here, no assignment to any memory through dynamic objects. They are freed automatically. The pointer returned by the function is a pointer to a static memory block.
When making the arr as pointers to int:
int* arr[ 10 ];
int cur = -1;
int* Add( int* fraction )
{
arr[++cur] = fraction;
return arr[cur];
}
// Usage:
int* test;
test = Add( new int( 1 ) );
test = Add( new int( 4 ) );
Now you have to memory blocks which are leaking since you have no clean up code.
When you call after each Add(...) the delete test, you have cleaned up the memory but you have lost the values you had stored within int* arr[ 10 ] as they are pointing to the memory holding the value.
You can create another function and call this after you are done with those values:
void CleanUp()
{
for( int a = 0; a < 10; ++a )
delete arr[ a ];
}
Small usage example:
int* test;
int test2;
test = Add( new int( 1 ) );
test2 = *Add( new int( 4 ) ); // dereference the returned value
/* do whatever you need */
CleanUp();
Why do we want to use pointers:
int Add( int val )
{
return val; // indeed very lame
}
When you call a function that needs a parameter (type), you are not passing in the instance but rather a copy of it. In the above function you are returning a copy of that copy. It will amount into a lot of duplication all memory involved and you make your application tremendously much slower.
Consider this:
class Test
{
int t;
char str[ 256 ];
}
If a function needs a type Test, you are copying the int and 256 chars. So make the function so it needs only a pointer to Test. Then the memory the pointer is pointing to is used and no copying is needed.
int Add( int val )
{
val++;
return val;
}
Within this last example, we are adding 1 to the copy of val and then returning a copy of that.
int i = Add( 1 );
result: i = 2;
void Add( int* val )
{
// mind the return type
*val++;
}
In this example you are passing the address to a value and then - after dereferencing - adding one to the value.
int i = 1;
Add( &i );
result: i = 2;
Now you have passed in the address to i, not making a copy of it. Within the function you directly adding 1 to the value at that memory block. You return nothing since you have altered the memory itself.
Nulling/testing for valid pointers
Sometime you encounter examples such as:
if( p != 0 ) // or if( p )
{
/* do something with p */
}
This is just to check if the pointer p is valid. However, an invalid address - thus not pointing to a memory you have reserved (the access violation) - will pass through too. For your code, an invalid pointer is a valid address.
Therefore, to use such a check you have to NULL (or 0) the pointer.
Fraction* f1 = 0;
When f1 == 0, it doesn't point to anything otherwise it points to whatever it points to.
This is usefull when you have a pointer in a 'main'-class which is or isn't created.
class Fraction
{
public:
int* basicFeature;
int* ExtendedFeature = 0; // NULL this pointer since we don't know if it
// will be used
Fraction( int fraction )
{
// Create a pointer owned by this class
basicFeature = new int( fraction );
}
Fraction( int fraction, int extended ) // mind the static
: Fraction( fraction )
{
// Create a pointer owned by this class
ExtendedFeature = new int( extended );
}
~Fraction()
{
delete basicFeature;
if( ExtendedFeature )
// It is assigned, so delete it
delete ExtendedFeature;
}
}
withing the ctors we are creating the two pointers, so within the dtor we are cleaning up those pointer. Only checking the ExtendedFeature since this one may or may not be created. basicFeature is always created.
You could replace the if statement including its scope within the dtor by calling a new function: removeExtendedFeature() where that function implementation would be:
Fraction::removeExtendedFeature()
{
if( ExtendedFeature )
{
// It is assigned, so delete it
delete ExtendedFeature;
// Now it is important to NULL the pointer again since you would
// get an access violation on the clean up of the instance of
// the class Fraction
ExtendedFeature = 0;
}
}
And the new dtor:
Fraction::~Fraction()
{
delete basicFeature;
removeExtendedFeature();
}
Another functionallity of nulling could be:
int Fraction::getValue()
{
int result = *basicFeature;
if( ExtendedFeature )
result += *ExtendedFeature;
return result;
}
My apologies for the lame class Fraction, with an ever more lame extended feature. But as an example it would serve the purpose.
A:
There are two main ways to create C++ options. One is on the stack (i.e. Fraction f1;), and that memory is automatically freed when that stack frame is popped. The second is on the heap (i.e. Fraction* f1 = new Fraction();. The key is the new keyword.
The basic summary is this: your news and deletes must match up. Every time you new something, you must delete it when you are done with it. "When you are done with it" is up to you to determine. However, if you reuse a variable (see below), you will need to delete first, otherwise you will have no way to get the original object back to delete.
Fraction* f1 = new Fraction(); // create memory on heap, will need to free
f1 = new Fraction(); // this is a memory leak because I didn't first free the
// original f1 object, which I can no longer access
A:
The rule of thumb is every new must have a corresponding delete.
Manually using new and delete isn't a common thing to do in C++. When you initialize things without using new or delete it is guaranteed to be dealt with for you by the upcoming }. Assuming everyone's doing their job and following RAII principles when it comes to objects.
Fraction f1(...);
instantiates a Fraction object called f1. Its destructor will get called upon reaching the end of scope.
The 'modern' approach is to handle things like above. In the rare instances where this approach wont work, you should be using smart pointers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mirror console output to file in c++
In C++, is there a smart way to mirror output from stdout to both the console and the file?
I'm hoping there is a way to do it like in this question.
Edit: It would be nice to be able to do this with just the standard libraries (ie: no boost)..
A:
Alternatively, just start your program so it's piped to the tee command.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What's the advantage of making a Sinatra/Rack app into a single, locally-executable file?
I was reading the description of Vegas, which is a gem that
aims to solve the simple problem of
creating executable versions of
Sinatra/Rack apps.
I didn't know this was a problem that needed to be solved.
The reason this seems of dubious benefit is because of this:
Now if you run ./my_app it should:
* find an appropriate rack handler (thin. mongrel)
* find an available port
* launch the app in a browser
* put itself in the background
* write a .pid and a .url file
Isn't it already extremely easy to run a Sinatra application? You just type
ruby my_app.rb
and all of those same things happen except for the app being a background process.
Why do you need an executable file for this?
A:
Sounds to me like a convenience wrapper around Sinatra/Rack, except for daemonizing (.pid and .url are most likely to "find" it again) and launching a browser this doesn't seem to have any advantage over bare Sinatra/Rack.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regex catch from the hash sign "#" to the next white space
I have a script line this :
#type1 this is the text of the note
I've tried this bu didn't workout for me :
^\#([^\s]+)
I watch to catch type in other words I to get whats between the hash sign "#" and the next white space, excluding the hash "#" sign, and the string that I want to catch is alphanumeric string.
A:
I've figured it out.
/^\#([^\s]+)+(.*)$/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Check special character in string?
i need to check existing of Character (*,&,$) in Given String using python command such as given below?
Eg: stringexample='mystri$ng&*'
check stringexample contains any special symbols like *,&,$ then return true?
shall i try with string method __contains__()
A:
>>> stringexample = 'mystri$ng&'
>>> '*' in stringexample
False
>>> '$' in stringexample
True
>>> '&' in stringexample
True
>>>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Creating a 2D texture array for depth view
Following my question here, I decided to create an 2D texture array for all of my depth screen texture so that I can use them for shadows for all my lights.
I'm having an issue setting it up, I'm getting an E_INVALIDARG when I try to create it.
This code is what I use to create the 2D array Texture
D3D11_TEXTURE2D_DESC sTexDesc;
sTexDesc.Width = this->Width; // 1024
sTexDesc.Height = this->Height;// 1024
sTexDesc.MipLevels = 0;
sTexDesc.ArraySize = arraySize; // The value is 25 here
sTexDesc.Format = DXGI_FORMAT_R24G8_TYPELESS;
sTexDesc.SampleDesc.Count = 1;
sTexDesc.SampleDesc.Quality = 0;
sTexDesc.Usage = D3D11_USAGE_DEFAULT;
sTexDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
sTexDesc.CPUAccessFlags = 0;
sTexDesc.MiscFlags = 0;
HRESULT hr = pd3dDevice->CreateTexture2D(&sTexDesc, NULL, &(this->shadowTexture));
if(FAILED(hr))
throw std::exception("Failed at creating texture array for shadows");
This is the code that I use to create the depth view
D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
ZeroMemory(&dsvDesc, sizeof(dsvDesc));
dsvDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY;
dsvDesc.Texture2DArray.ArraySize = arraySize; // The value is 25 here
dsvDesc.Texture2DArray.FirstArraySlice = index;
HRESULT hr = pd3dDevice->CreateDepthStencilView(shadowTexture, &dsvDesc, &pDepthMapDSV);
if(FAILED(hr)){ throw std::exception("Error creating 2d texture for shadow"); }
CreateDepthStencilView will return OK for the first texture but it crashes for the second.
What have I done wrong here?
A:
I found what the issue was.
dsvDesc.Texture2DArray.ArraySize = arraySize; // The value is 25 here
I thought that it wanted to know the full size of the array, but as I read the msdn article, it is actually the number of texture to use and so that value should be set to 1.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What DNS server is my Ubuntu 18.04 using?
I'm using Hyper-V to create a VM running Ubuntu 18.04. I'm having some issues with docker not resolving DNS requests properly. This guide suggests using nmcli to identify the DNS server.
$ nmcli dev show | grep 'IP4.DNS'
IP4.DNS[1]: 10.0.0.2
First of all, is nmcli installed by default? I don't think so, but even after installing it running this command doesn't show anything for IP4.DNS -- nor even DNS. Is there a better way of discovering what DNS server my installation is using?
A:
nmcli dev show is a good option.
File /etc/resolv.conf will have the nameservers actually configured for name resolution, so if you run cat /etc/resolv.conf you should see your current DNSs' servers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make a State Transition Table for an NFA?
I have done creating the Transition Table for a DFA by using a two dimensions array. For example, to store 10 states and two transitions.
transition = new int[10][2];
However, For the NFA, we have many possible transitions to go. The example below, you can go to S2 or S3 when the value 0 is coming. So, I don't know which structure of Java that I should use.
I am trying to create the Table for an NFA for a day but all the ways that I have done are so complicated. For example using, Hashtable, Set, etc.
Could you please share an example of code or any ideas?
A:
Use a bitset for each state, and use a bitwise or | for each transition. For example, S1 = 001, S2 = 010, and S3 = 100. Now S2 | S3 = 110, so your {S2, S3} transition is 110. This allows for up to 32 states if represented by an int or 64 states if represented by a long; for more states (or for easier-to-use bitwise operations), use a BitSet.
Incidentally, ANY NFA can be converted to a DFA, see e.g. http://www.cs.odu.edu/~toida/nerzic/390teched/regular/fa/nfa-2-dfa.html for a tutorial, so that may be another option depending on what you're trying to do here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Registros com datas recorrentes filtrados por um período
O Problema
Estou criando um sistema financeiro onde preciso registrar uma movimentação recorrente, como por exemplo, uma conta de luz que se repete todo mês. No sistema, esse tipo de movimentação é tratado como uma despesa/receita fixa.
A minha tabela possui a seguinte estrutura:
[tabela de movimentações]
- id // Código do registro (int, auto increment)
- title // Um título para a movimentação (var_char)
- description // Descrição da movimentação (text)
- type // Se é receita ou despesa (tinyint)
- repeat // Tipo de repetição (tinyint)
- is_recurring // Se é uma movimentação recorrente ou não (tinyint)
- start_date // Data de início (timestamp)
- value // valor da movimentação (decimal) só preenchido se for recorrente
O campo repeat grava um inteiro que representa o intervalo de repetição, sendo eles:
0 - Nunca
1 - Todos os dias
2 - Toda semana
3 - A cada duas semanas
4 - Todo mês
5 - A cada dois meses
6 - A cada três meses
7 - A cada seis meses
8 - Todo ano
Se a movimentação não for recorrente e tiver parcelas predefinidas, seja uma ou várias, já ficam gravadas em outra tabela que possui a seguinte estrutura:
[tabela de parcelas]
- id // Código do registro (int, auto increment)
- value // valor da movimentação (decimal)
- date // Data da parcela (date)
- status // Status da parcela (tinyint) pago, pendente...
- trasanction_id // Referencia á primeira tabela para conseguir recuperar todas as
// parcelas envolvidas em uma movimentação
Assim consigo recuperar todas as movimentações parceladas, mas o meu problema são as recorrentes, que só entram para a tabela de parcelas depois de serem efetivadas.
Como montar uma previsão de gastos futuros considerando essas movimentações recorrentes.
Não posso sair adicionando vários registros na tabela de parcelas até uma determinada data, pois se um relatório é gerado para um período superior ao do último registro, o usuário tomaria decisões erradas sem saber que aquela receita/despesa fixa não foi considerada.
A solução pode ser uma mescla de PHP e MySQL desde que não fique muito pesado.
Exemplo
Possuo uma receita de R$ 10,00 reais que recebo toda semana a partir de 04/08/2014.
A do dia 04/08/2014 já foi quitada e já foi registrada na tabela de parcelas como paga. As futuras ainda não.
Preciso listar todas as receitas no período de 01/08/2014 a 05/09/2014.
A receita acima deve aparecer nas datas 04/08, 11/08, 18/08, 25/08 e 01/09 nesta listagem
Soluções encontradas que não atenderam
Encontrei algumas soluções, que cito a seguir:
Possível solução 1
Nesta solução é usado uma tabela para armazenar quando os dados devem se repetir, usando um mecanismo semelhante ao cron. Funciona, porem a performance é horrível para casos de relatórios de vários dias.
A consulta usada na solução é baseada na conta sobre um dia específico, sendo assim, para montar um relatório mensal, irei realizar 30 consultar no banco, e para um relatório anual, 365 consultas.
Calendar Recurring/Repeating Events - Best Storage Method
Repeating calendar events and some final maths
Possível solução 2
Esta solução utiliza uma tabela calendário. Uma solução quebra galho, que pode trazer muitos problemas futuros de manutenção, como a falta de datas cadastradas na tabela calendário, volume de registros armazenados sem necessidade, etc.
Recorrência de Datas com MySQL
A:
Você pode gerar os registros novos à medida em que eles são necessários, utilizando uma estratégia lazy. Assim, se o usuário indicar que ele quer saber das despesas até maio do ano que vem, por exemplo, você gera. No entanto, há um problema chato de consistência que é o valor da despesas recorrente ser reajustado (por exemplo, meu condomínio aumentou).
Com isso, você pode manter sim as tabelas separadas e exibir sempre as despesas já confirmadas separadas das estimativas para despesas recorrentes.
Eu sugiro também que você use um par (número, unidade) em vez do seu modelo atual. Como está, você não consegue representar, por exemplo, 5 semanas ou 10 meses.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как выполнить UPDATE нескольких значений по данным из другой таблицы?
Есть 2 таблицы, мне нужно увеличить значение price стобца s_variants на 10% где brand_id = 84 и price < 1000.
Пробывал сделать через JOIN он не работает, попробывал через подзапрос
UPDATE `s_variants`
SET `s_variants`.`price`= `s_variants`.`price` * 1.1
WHERE `s_variants`.`price` < 1000
AND `s_variants`.`product_id` =
(SELECT `s_products`.`id` FROM `s_products` WHERE `s_products`.`brand_id` = 84)
Но, получаю ошибку, что подзапрос возвращает несколько вариантов.
Как правильно составить запрос, что бы выполнить задачу?
таблица s_products
| id | brand_id |
-------------------
| 1 | 21 |
| 5 | 84 |
| 235 | 84 |
таблица s_variants
| id | product_id | price |
----------------------------
| 38 | 1 | 545 |
| 25 | 5 | 158 |
| 35 | 235 | 999 |
A:
Абсолютно правильная ошибка, результат выполнения подзапроса - множество, значит знак равенства не подойдет. Вам нужно использовать in
UPDATE `s_variants`
SET `s_variants`.`price`= `s_variants`.`price` * 1.1
WHERE `s_variants`.`price` < 1000
AND `s_variants`.`product_id` IN
(SELECT `s_products`.`id` FROM `s_products` WHERE `s_products`.`brand_id` = 84)
пример на sqlfiddle
|
{
"pile_set_name": "StackExchange"
}
|
Q:
box2d + C# (Visual Studio 2008 or less). Need an example of code
All the examples I have ever seen are for visual studio 2010. Help me to find a simple older example please. And without of xna (if it is possible).
A:
I haven't found any code for old VS so I installed Visual Studio 2010 with the latest version of XNA.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Confuse of Push Notification in Android
I followed this Push Notification tutorial.
When I finish the tutorial, I found out that two classes did not use which were AuthenticationUtil and MessageUtil.
Moreover, Google Login, this link seem unworkable. Second, This is the token id for the Android device or the account only? i thought push notification is push message to token id of Android device.
On the others hand, i found out that the bundle.putExtra(key, value), all the keys did not use it. For example put "app" but in C2DMRegistrationReceiver() did not get the key.
In this sendRegistrationIdToServer(), it seem like never being call out.
I am being confused by this tutorial about push notification.
Who can guide me or give me workable tutorial or example about push notification?
I would like pro to point out what's my wrong.
This is my registration id
public static final String[] REGISTRATION_ID = {
"APA91bFV6MwoAH0UNop69PZ2liKpSBUHSHenIuPzh44_6GdGKzVCLvoH_NM31eMZMVLZi-SAIFwP4iZaE72dSWkIh3GaD0RQYpPm9zO0ARWmnoxFyyyreL_KpQ9Qd_p0broclT12RhA4Ymk0cBT00CmpsbSHIwyxig",
"APA91bEwmxgvs7zNbKC4p0n4DoTEM73DTihnQgBOP8Gxhf2sVW-fgltugDgS1Fh2S4KvN1wQHbMNJEIzieJ9F1nNPqs3NWeKGbB7IBYpKJq4xmN4Z7uzkjZQQUKGD8jW--AwfQY5McINBto9GAL_87_u5WkIq-kx3g",
"APA91bH63Zgxn1X_MZ56UzrlRpffvmiLAIsqxvBUTMUHP2O_MT_VU9Ork_edXKHlml-PZSkjKEqdk8EKv5HvxbPdK1Vva3WtmqsPZfhXzEbtNIrwrqIvvRf7hL835rDc4t2E8EKUBj1dX2ta0OxY5pY3Xlhkyb1sBg",
"APA91bGqT5Wo6eUaMdqT5r9TlGbKSX6GN2W6r-RjrRXz5T5v3j87flcQRyfSajmMNGXuPVe-fwZydRmvyYu63tWnYohDmpJyKkXOxs8Vx6P_FplFQ__ufR_hekwqGOspeUc6bfc8fhbMPGN3Ft9l-bfrghJwwk79jw"};
Messageutil
public static int sendMessage(String auth_token, String registrationId,
String message, String title) throws IOException {
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID).append("=")
.append(registrationId);
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=")
.append("0");
postDataBuilder.append("&").append("data.payload").append("=")
.append(URLEncoder.encode(message, UTF8));
postDataBuilder.append("&").append("data.title").append("=")
.append(URLEncoder.encode(title, UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
// Hit the dm URL.
URL url = new URL("https://android.clients.google.com/c2dm/send");
HttpsURLConnection
.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth="
+ auth_token);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
return responseCode;
}
private static class CustomizedHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
Messagesender
public static void main(String[] args) throws IOException {
String token = AuthenticationUtil.getToken(SecureStorage.USER,
SecureStorage.PASSWORD);
for (int i = 0; i < ServerConfiguration.REGISTRATION_ID.length; i++) {
MessageUtil.sendMessage(token,
ServerConfiguration.REGISTRATION_ID[i], "12358",
"印尼羽賽:馬2單1雙止步入選賽");
System.out.println(ServerConfiguration.REGISTRATION_ID[i]
.toString());
}
System.out.println(token);
}
A:
You should follow this tutorial for android c2dm implementation.
For server, you could use anything, some code sample available on internet. For server I used .NET library called "C2DM Sharp"
The process is very simple like...
First register your google email for c2dm on - https://developers.google.com/android/c2dm/signup
Run the android application on Android 2.2 or higher and send the registrationID which you can get in "C2DMReceiver" or get that ID by writting in LOG
Use the server code, for testing purpose paste your registrationID in Server code and you are ready to go.
The basic flow of C2DM is ...
Register Phone for C2DM -> Get registrationID -> Send registrationID to server -> Server usees google id to get auth token -> server use registrationID and auth token to send message.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to have a computed observable with parameters in Knockout
Possible Duplicate:
knockoutjs: can we create a dependentObservable function with a parameter?
In my viewmodel, I have a function that returns the sum of items based on the type of item:
var ViewModel = function(data) {
var self = this;
this.Results = ko.observableArray(data);
this.totalPerType = function(type) {
var total = 0;
for (var index in self.Results()) {
if (self.Results()[index].Type == type)
total += self.Results()[index].Quantity;
}
return total;
};
};
When the user edits one of the items, the total isn't updated automatically, because it isn't a computed observable. Is it possible to change the function totalPerType into a computed observable, without having to put the type parameter into the viewmodel (keeping it as a parameter)?
I created a Fiddle to make it easier to try some things: http://jsfiddle.net/7PK9r/
A:
I think this answers your question:
knockoutjs: can we create a dependentObservable function with a parameter?
(Note: dependentObservable is what computed observables used to be called prior to v2.0 of knockout.js)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Efficiency of searching files in a directory?
I am building a website with a user authentication system allowing each user to upload images to their account, essentially I am doing this as an experience in web development so please forgive my ignorance on the topic.
My question involves the efficiency of placing files into a directory. Is it more efficient to create a deeper directory structure or to place all files into one folder? The former seems obvious, but does it not depend on the search algorithm implemented by the file system?
For example:
root/user/2012/----------------A/
/2013/---------- A/ B/
/2014/------A/ B/ C/
B/ C/ D/
C/ D/
D/
Or dump all files into a single folder?
root/user/
When an image is retrieved, for example by an <img> tag, which way provides a more efficient result? I have searched Google for information on the topic, but couldn't find anything definitive or at my level of understanding.
A:
Accessing a single file should be roughly equivalent. A single directory or multiple choice really depends on how you are trying to use the file listing. If you expect the user to have thousands of files and you only display a single year at a time, it may make sense to break up the directory structure into multiple sections to keep file listings manageable. If you always show all the files, I suspect the single folder may be faster, since you will have to run through the whole directory listing doing multiple file listings. I would do a few tests based on what you expect your app to have to deal with. My guess would be a single directory should be fine, unless you expect large numbers of files and you can break the listing down.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
setForeground color in every component at one command java swing
When i write:
jLabel1.setForeground(Color.Red);
jTextArea1.setForeground(Color.Red);
it works.
But i want to set this color at an one command.
Suppose i write setForeground(Color.Red), it will set for all the components.
Is it Possible?
Thanks in advance.
A:
You can traverse through all components in a given container and invoke some operation (like color change) using the following code:
Component[] comps = yourPanel.getComponents();
for(Component comp : comps) {
if(comp instanceof JComponent) {
((JComponent)comp).setForeground(Color.Red);
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why fry rice before boiling?
Ordinarily when I make fried rice, the general process is:
Boil the rice until done.
Fry the cooked rice in oil.
However, I recently made a different rice recipe which flipped the order:
Lightly fry the dry rice in a pan.
Then boil the rice until done.
This struck me as being really strange. Why would I lightly fry the rice before cooking it? I usually associate frying rice with textural change, but after boiling it the texture wasn't notably different than if I hadn't fried it at all.
In both cases I was using a medium-grain white rice.
A:
This is sometimes called "pilaf style", though technically actual pilafs do not require the sauteeing step. It is, however, very common in pilaf and related dishes.
The main function of this is to change the composition of the starch on the surface of the rice. This reduces the starches that cross-link and make rice sticky. It helps your rice to cook up into separate grains.
While you're at it, it also adds some flavor to the rice, by caramelizing some of the starches. Plus, it adds oil, which can carry flavors of its own and help distribute fat-soluble flavors in the other ingredients.
The effect is very different from "fried rice", where the starches have already been cooked and gelatinized before frying. The goals are somewhat the same, adding browned flavors and distributing fat-soluble ingredients, but the chemical changes to the surface of the rice itself will be different.
A:
When the rice is dry its easier to get it toasted before you boil it because it has less moisture content. Packaged rice, like Rice-a-Roni have you do this method to get that toasted flavor of the rice.
A:
In addition to the other answers, toasting the rice first can reduce the cooking time considerably. When you toast rice first, not only are you heating your entire pan but the rice thoroughly. You are able to add your liquid and immediately begin simmering and steaming the rice.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Database schema for blog comment
I have a comment table on my blog.
comment
- id (PK)
- post_id (FK)
- user_id (FK)
- comment
Should I split into 3 tables and do it like this?
comment
- id (PK)
- comment
user_comment
- comment_id (PK, FK)
- user_id (PK, FK)
post_comment
- post_id (PK, FK)
- comment_id (PK, FK)
Would this be a better design? Any other suggestion is welcomed.
A:
Your original design is perfect; it models what is actually going on.
Also, it's good to avoid schema bloat.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Override Yii2 assetManager config in controller
I use yii-jui to add some UI elements in the views such as datePicker. In the frontend\config\main-local.php I set the following to change the theme used by the JqueryUI:
$config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'gjhgjhghjg87hjh8878878',
],
'assetManager' => [
'bundles' => [
'yii\jui\JuiAsset' => [
'css' =>
['themes/flick/jquery-ui.css'],
],
],
],
],
];
I tried the following to override this configuration item in the controller actions method:
public function actions() {
Yii::$app->components['assetManager'] = [
'bundles' => [
'yii\jui\JuiAsset' => [
'css' =>
['themes/dot-luv/jquery-ui.css'],
],
],
];
return parent::actions();
}
Also I tried to set the value of Yii::$app->components['assetManager'] shown above to the view itself (it is partial view of form _form.php) and to the action that calls this view (updateAction). However, all this trying doesn't be succeeded to change the theme. Is there in Yii2 a method like that found in CakePHP such as Configure::write($key, $value);?
A:
You should modify Yii::$app->assetManager->bundles (Yii::$app->assetManager is an object, not an array), e.g.
Yii::$app->assetManager->bundles = [
'yii\jui\JuiAsset' => [
'css' => ['themes/dot-luv/jquery-ui.css'],
],
];
Or if you want to keep other bundles config :
Yii::$app->assetManager->bundles['yii\jui\JuiAsset'] = [
'css' => ['themes/dot-luv/jquery-ui.css'],
];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Xcode 7 beta ios 9 giving error 'Application windows are expected to have a root view controller at the end of application launch'
This is my code . I am using MTStatusBarOverlay too.This code works properly when run using xcode 6. Application crashing and giving error
'Application windows are expected to have a root view controller at
the end of application launch' .
I have tried to set rootViewController in many different manners. I even tried overriding following code in MTStatusBarOverlay
- (UIViewController *)rootViewController {
ETAppDelegate *delegate = (ETAppDelegate *)[UIApplication sharedApplication].delegate;
return delegate.window.rootViewController;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
_didReceiveBackgroundNotification = NO;
[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge];
NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
MTStatusBarOverlay *overlay = [MTStatusBarOverlay sharedInstance];
overlay.animation = MTStatusBarOverlayAnimationNone;
overlay.hidesActivity = YES;
NSDictionary *bundleDictionary = [[NSBundle mainBundle] infoDictionary];
NSString *currentVersion = [NSString stringWithFormat:@"%@ (%@)", [bundleDictionary objectForKey:@"CFBundleShortVersionString"], [bundleDictionary objectForKey:@"CFBundleVersion"]];
[overlay postMessage:@"Test Application" stringByAppendingString:currentVersion]];
[self.window makeKeyAndVisible];
return YES;
}
- (UIWindow *)window{
if (_window) return _window;
_window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[_window setRootViewController:self.rootViewController];
return _window;
}
- (UIViewController *)rootViewController{
if (_rootViewController) return _rootViewController;
_rootViewController = [[ETNavigationController alloc] initWithNibName:nil bundle:nil];
ETHomeMenuViewController *homeViewController = [[ETHomeMenuViewController alloc] initWithNibName:nil bundle:nil];
((ETNavigationController*)_rootViewController).rootViewController = homeViewController;
homeViewController = nil;
return _rootViewController;
}
A:
Because MTStatusBarOverlay is a subclass of UIWindow, and Xcode 7 now specifies as the error message says:
Application windows are expected to have a root view controller at the end of application launch
This means you cannot instantiate a UIWindow without a root viewcontroller before application launch. So don't call [MTStatusBarOverlay sharedInstance] until after the application has launched.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What tool lets me see gzip's Huffman table and blocks?
What tool lets me see the Huffman table that gzip and some other compression algorithms create?
I know that programs like bzip2 and zpaq use additional compression techniques, but I believe gzip, zip, and the lz family of programs use Huffman tables, and I would like to see these.
I realize that a given file may have multiple Huffman tables, one for each "block" of data.
A:
infgen will show you the dynamic block headers in some detail. infgen -d will show you them in all their detail.
I don't know that that will help with what you are trying to do. It sounds like what you're looking for are preset dictionaries. In zlib you can use deflateSetDictionary() and inflateSetDictionary() to provide up to 32K that effectively precedes the data to be compressed and provides source material in which to find matching strings. If your files are similar, you may be able to construct a dictionary or more than one dictionary that is likely to have strings that match your data.
The Huffman tables are uniquely constructed to be optimal for each block, so it would reduce rather than improve compression to apply Huffman tables from a different block.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Choosing N when doing t-tests on bootstrapped samples
Specifically the Welch's T-Test, but probably any T-Test, requires a value for Mean, Variance and N to be used to calculate the T-statistic and the degrees of freedom. I am concerned about these values if the sample has been bootstrapped (re-sampled with replacement) before using the T-Test. Specifically, I'm concerned that the arbitrary choice of how many times to bootstrap (10K, 20K, 100K) will change the T-statistic even though the underlying distribution is the same.
For instance, if I have 100 sample values with an unknown distribution and I re-sample with replacement 10,000 times, then I use those 10,000 samples to calculate a mean, variance, and N for a t-test.
N: Should I use the sample size before the bootstrap or after the bootstrap? I'm concerned that my choice of how many times to run the bootstrap (10,000 is an arbitrary number) will make the distribution look more accurate than it is. Should I use n=10,000 or N=100?
Full disclosure: I have a fairly good knowledge of statistics, enough to use the terms, but perhaps not enough to ensure I have used them 100% correctly. Please excuse confusions of terminology.
A:
Normally each of your bootstrap samples would be the same size as your original. So if you have 100 in your original sample, your bootstrap samples should also be size 100 (or, some argue, 99). Not 10000. So then each of your samples would calculate the T using the sample size of 100. You can do 10000 bootstraps if you like (probably excessive for most questions) but I don't see much value in having bootstrap samples that are each bigger than the original sample. The aim of the bootstrap is to resemble the original sampling process as much as possible, hence you use the same size.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to stop thread in onBackPressed or onPause or OnResume
Here I'm using location to update longitude and latitude whenever I try to press back button or app is background or any Instance, i want the location_thread to be stopped from running it. Resume it when I switch to current activity.
location_thread = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(2000);
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("TAG",currentThread().getName()+" Running");
updateLatLongInfo();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
location_thread.setDaemon(false);
location_thread.start();
}
@Override
//whenever user press a backbutton thread must stoppped
public void onBackPressed() {
super.onBackPressed();
location_thread.stop();
Intent intent = new Intent(Logistic_ReportProblem.this, FPAgentHome.class);
startActivity(intent);
finish();
}
private void updateLatLongInfo() {
try {
int locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
latlongInfo.setBackgroundResource(R.drawable.latlng_info);
GradientDrawable drawable = (GradientDrawable) latlongInfo.getBackground();
if (locationMode == 0 || locationMode == 1 || locationMode == 2) {
latlongInfo.setText("Please enable high accuracy in your location settings");
drawable.setColor(Color.RED);
} else {
try {
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) this.getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
android.location.Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
param_latitude = df.format(lat).toString();
param_longitude = df.format(lng).toString();
// latlongInfo.setText("Latitude :" + Math.round(lat * 1000000.0) / 1000000.0 + " ," + " Longitude :" + Math.round(lng * 1000000.0) / 1000000.0);
latlongInfo.setText("Latitude : " + param_latitude + " ," + " Longitude : " + param_longitude);
latlongInfo.setGravity(Gravity.CENTER);
drawable.setColor(Color.GREEN);
} catch (SecurityException e) {
Log.e("Error", e.toString());
}
}
A:
Dont use Thread.stop() method its deprecated and unsafe
Best to way to stop thread is to complete it`s work
Create volatile variable, something like
public volatile boolean threadIsStopped;
Replace your
while (!isInterrupted())
to
while (!threadIsStopped)
And then just make it true
public void onBackPressed() {
super.onBackPressed();
threadIsStopped = true;
Intent intent = new Intent(Logistic_ReportProblem.this, FPAgentHome.class);
startActivity(intent);
finish();
}
Since your backpress starts another activity and finishes current its better to do such thing:
@Override
protected void onResume() {
super.onResume();
threadIsStopped = false;
//start thread here
}
@Override
protected void onPause() {
super.onResume();
threadIsStopped = true;
}
So theres no need to stop thread inonBackPressed` at all.
Notice that there is possible delay after threadIsStopped is set before thread will be stopped.
About resuming thread - in your case you just create new thread and start it.
Also notice that onPause and onResume will be called again if you change orientation of your device. Thats why strongly recommended to use IntentService for such things.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как загружать данные с Firebase, на Activity исходя из того какая кнопка была нажата на другом Activity?
Здравствуйте, у меня есть 2 Activity на одном RecyclerView на другом TextView.
В RecyclerView у меня 2 Itema при нажатии на которые активируется второе Activity, но данные загружаются так же, на сервере у меня подготовлены 2 разные информации, на данный момент я смог реализовать только загрузку 1 на обе кнопки, не могу различать их. Собственно в этом мой вопрос
Activity c RecyclerView .
rivate RecyclerView recyclerView;
private List<Hotel> result;
private HotelAdapter adapter;
private FirebaseDatabase database;
private DatabaseReference reference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
database = FirebaseDatabase.getInstance();
reference = database.getReference("Hotel");
result = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.hotel_list);
recyclerView.setHasFixedSize(true);
LinearLayoutManager lin = new LinearLayoutManager(this);
lin.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(lin);
adapter = new HotelAdapter(result);
recyclerView.setAdapter(adapter);
updateList();
}
private void updateList(){
reference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
result.add(dataSnapshot.getValue(Hotel.class));
adapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Hotel hotel = dataSnapshot.getValue(Hotel.class);
int index = getItemIndex(hotel);
result.set(index, hotel);
adapter.notifyItemChanged(index);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Hotel hotel = dataSnapshot.getValue(Hotel.class);
int index = getItemIndex(hotel);
result.remove(index);
adapter.notifyItemRemoved(index);
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private int getItemIndex(Hotel hotel){
int index = -1;
for(int i = 0; i < result.size(); i++){
if(result.get(i).key.equals(hotel.key)) {
index = i;
break;
}
}
return index;
}
}
Адаптер к этому Activiti
public class HotelAdapter extends RecyclerView.Adapter<HotelAdapter.UserViewHotel>{
private List<Hotel> list;
public HotelAdapter(List<Hotel> list) {
this.list = list;
}
@Override
public UserViewHotel onCreateViewHolder(ViewGroup parent, int viewType) {
return new UserViewHotel(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_hotel , parent, false));
}
@Override
public void onBindViewHolder(UserViewHotel holder, final int position) {
Hotel hotel = list.get(position);
holder.TvName.setText(hotel.name);
holder.TvStar.setText("star:"+hotel.star + "");
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), HotelViewActivity.class);
intent.putExtra(HotelViewActivity.EXTRA_POS, position);
view.getContext().startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return list.size();
}
class UserViewHotel extends RecyclerView.ViewHolder{
TextView TvName, TvStar;
Button btPodrob;
public UserViewHotel(View itemView) {
super(itemView);
TvName = (TextView) itemView.findViewById(R.id.TvName);
TvStar = (TextView) itemView.findViewById(R.id.TvStar);
btPodrob = (Button) itemView.findViewById(R.id.btPodrob);
}
}
}
Activity с View
public class HotelViewActivity extends AppCompatActivity {
static final String EXTRA_POS = "my_item_position";
private TextView TvDitalicHotel;
private FirebaseDatabase database;
private DatabaseReference reference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_view);
int my_item_position = (int) getIntent().getExtras().get(EXTRA_POS);
TvDitalicHotel = (TextView) findViewById(R.id.TvDitalicHotel);
database = FirebaseDatabase.getInstance();
reference = database.getReference("DitalicHotel");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
A:
Я внес изменение в строку .
reference = database.getReference("DitalicHotel");
изменил ее на
reference = database.getReference("DitalicHotel/" + my_item_position);
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.