qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
|---|---|---|---|---|---|
16,225,054
|
I have this bit of HTML:
```
<div class="clearfix wanted_item">
<div class="clearfix">
<div class="float_right"><img src="images/pin.png"></div>
<div class="float_right">
<h3>a</h3>
<div>abcd</div>
</div>
</div>
<div class="float_right more_details" style="display: block;">
<ul>
<li>some list</li> </ul>
<div class="application_link">
<a class="orange_button" href="volunteer.php?volunteer_type=1"><span>apply</span></a>
</div>
</div>
<a class="float_left clearfix more_details_link" href="javascript:void(0);">Show details</a>
</div>
```
And I have this jQuery code:
```
$(".less_details_link").click(function() {
$(this).parent().children(".more_details").slideUp(500);
$(this).text("Show details");
$(this).removeClass('less_details_link');
$(this).addClass('more_details_link');
});
$(".more_details_link").click(function() {
$(this).parent().children(".more_details").slideDown(500);
$(this).text("Hide details");
$(this).removeClass('more_details_link');
$(this).addClass('less_details_link');
});
```
For some reason when I click the 'show' link it works properly, I can also see that it changes the class to `less_details_link` but the second `click()` function fails to work without any output to the console log. When I click the 'Hide details' link it just doesn't do anything.
|
2013/04/25
|
[
"https://Stackoverflow.com/questions/16225054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407943/"
] |
***[`jsFiddle Demo`](http://jsfiddle.net/PjBYJ/)***
That is because when you add a class to an element, it does not bring the event handler with it unless you use on ([jQuery API: on](http://api.jquery.com/on/)) for the event handler
```
$("body").on("click",".less_details_link",function() {
$(this).parent().children(".more_details").slideUp(500);
$(this).text("Show details");
$(this).removeClass('less_details_link');
$(this).addClass('more_details_link');
});
$("body").on("click",".more_details_link",function() {
$(this).parent().children(".more_details").slideDown(500);
$(this).text("Hide details");
$(this).removeClass('more_details_link');
$(this).addClass('less_details_link');
});
```
|
This is way more complex than it needs to be. Its one link, just give it an extra class to denote if expanded or not, then do a simple if function to determine if active or not.
Thank you @Kacey for the `.slideToggle()` and `.toggleClass()` recommendation, even simpler.
```
$(".more_details_link").click(function() {
var $this = $(this);
$this
.toggleClass('active')
.prev()
.stop()
.slideToggle(500);
$this.hasClass('active') ? $this.text("Show details") : $this.text("Hide details");
});
```
Edited to use ternary if function for text.
|
16,225,054
|
I have this bit of HTML:
```
<div class="clearfix wanted_item">
<div class="clearfix">
<div class="float_right"><img src="images/pin.png"></div>
<div class="float_right">
<h3>a</h3>
<div>abcd</div>
</div>
</div>
<div class="float_right more_details" style="display: block;">
<ul>
<li>some list</li> </ul>
<div class="application_link">
<a class="orange_button" href="volunteer.php?volunteer_type=1"><span>apply</span></a>
</div>
</div>
<a class="float_left clearfix more_details_link" href="javascript:void(0);">Show details</a>
</div>
```
And I have this jQuery code:
```
$(".less_details_link").click(function() {
$(this).parent().children(".more_details").slideUp(500);
$(this).text("Show details");
$(this).removeClass('less_details_link');
$(this).addClass('more_details_link');
});
$(".more_details_link").click(function() {
$(this).parent().children(".more_details").slideDown(500);
$(this).text("Hide details");
$(this).removeClass('more_details_link');
$(this).addClass('less_details_link');
});
```
For some reason when I click the 'show' link it works properly, I can also see that it changes the class to `less_details_link` but the second `click()` function fails to work without any output to the console log. When I click the 'Hide details' link it just doesn't do anything.
|
2013/04/25
|
[
"https://Stackoverflow.com/questions/16225054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407943/"
] |
***[`jsFiddle Demo`](http://jsfiddle.net/PjBYJ/)***
That is because when you add a class to an element, it does not bring the event handler with it unless you use on ([jQuery API: on](http://api.jquery.com/on/)) for the event handler
```
$("body").on("click",".less_details_link",function() {
$(this).parent().children(".more_details").slideUp(500);
$(this).text("Show details");
$(this).removeClass('less_details_link');
$(this).addClass('more_details_link');
});
$("body").on("click",".more_details_link",function() {
$(this).parent().children(".more_details").slideDown(500);
$(this).text("Hide details");
$(this).removeClass('more_details_link');
$(this).addClass('less_details_link');
});
```
|
When your jQuery loads, there's no `.less_details_link` available, so it can't hook the `.click()` function to it. What you want to do is set your functions up like so:
```
$(".less_details_link").on("click", function() { ... }
$(".more_details_link").on("click", function() { ... }
```
|
16,225,054
|
I have this bit of HTML:
```
<div class="clearfix wanted_item">
<div class="clearfix">
<div class="float_right"><img src="images/pin.png"></div>
<div class="float_right">
<h3>a</h3>
<div>abcd</div>
</div>
</div>
<div class="float_right more_details" style="display: block;">
<ul>
<li>some list</li> </ul>
<div class="application_link">
<a class="orange_button" href="volunteer.php?volunteer_type=1"><span>apply</span></a>
</div>
</div>
<a class="float_left clearfix more_details_link" href="javascript:void(0);">Show details</a>
</div>
```
And I have this jQuery code:
```
$(".less_details_link").click(function() {
$(this).parent().children(".more_details").slideUp(500);
$(this).text("Show details");
$(this).removeClass('less_details_link');
$(this).addClass('more_details_link');
});
$(".more_details_link").click(function() {
$(this).parent().children(".more_details").slideDown(500);
$(this).text("Hide details");
$(this).removeClass('more_details_link');
$(this).addClass('less_details_link');
});
```
For some reason when I click the 'show' link it works properly, I can also see that it changes the class to `less_details_link` but the second `click()` function fails to work without any output to the console log. When I click the 'Hide details' link it just doesn't do anything.
|
2013/04/25
|
[
"https://Stackoverflow.com/questions/16225054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407943/"
] |
This is way more complex than it needs to be. Its one link, just give it an extra class to denote if expanded or not, then do a simple if function to determine if active or not.
Thank you @Kacey for the `.slideToggle()` and `.toggleClass()` recommendation, even simpler.
```
$(".more_details_link").click(function() {
var $this = $(this);
$this
.toggleClass('active')
.prev()
.stop()
.slideToggle(500);
$this.hasClass('active') ? $this.text("Show details") : $this.text("Hide details");
});
```
Edited to use ternary if function for text.
|
When your jQuery loads, there's no `.less_details_link` available, so it can't hook the `.click()` function to it. What you want to do is set your functions up like so:
```
$(".less_details_link").on("click", function() { ... }
$(".more_details_link").on("click", function() { ... }
```
|
28,073,337
|
I've written a function that goes through the text file and reads all the data's and prints them out, but the format of displaying data's are wrong and it just prints out data line by line, like this:
```
james
c 18 6 endah regal
male
0104252455
rodgo.james
kilkil
```
and what i'm looking for displaying data is something like this (which is not currently happening ):
```
Name : james
Address : c 18 6
Gender : Male
Contact : 0104252455
Username : rodgo.james
Password : kilkil
```
and here is the function :
```
int molgha() {
ifstream in("owner.txt");
if (!in) {
cout << "Cannot open input file.\n";
return 1;
}
char str[255];
while (in) {
in.getline(str, 255); // delim defaults to '\n'
if (in) cout << str << endl;
}
system("pause");
in.close();
}
```
keep in mind that this text file contains the records of owners registered to the system, hence we may need to print out maybe 3 sets of owner data's with the same pattern without any errors, hence what is the best way to display data's like that continuously ?
|
2015/01/21
|
[
"https://Stackoverflow.com/questions/28073337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4464910/"
] |
You're not printing out the desired labels of Name,Address etc in your code. You have two options -
1) Write out the labels before the data in the actual file itself, and leave the printing code as-is
2) Have a struct or a class with the members name, address etc and a function to print the contents
```
struct FileEntry{
string name;
string address;
.
.
.
void printContents(){
cout << "Name: " << name << endl;
cout << "Address: " << address << endl;
// etc etc
}
}
```
If you want to have varying numbers of records per file just put a number at the top of the file, i.e if the file holds 100 records put 100 as the first piece of data to read in and use it in your processing
```
int numRecords;
ifstream in;
if(in.open("owners,txt")){
numRecords << in;
for(int record = 0; record < numRecords; records++){
//read the info and output it here
}
```
|
So to re-state your question :
How can I add the fields Name: , Address: , etc to the output.
I would suggest the following approach :
Declare the field names in a static array :
```
const char* fieldNamesArray[6] = { "Name","Address","Gendre", "Contact","Username","Password"};
```
Inside your read / write function , consume each non-empty lines and assume that all entries have 6 fields and all time in the same order :
```
int curField=0;
while(in)
{
in.getLine(str,255);
if (strlen(str)>0)
{
cout<< fieldsNamesArray[curField] << " : " << str;
curField++;
}
if (curField>=6)
{
curField=0;
}
}
```
|
28,073,337
|
I've written a function that goes through the text file and reads all the data's and prints them out, but the format of displaying data's are wrong and it just prints out data line by line, like this:
```
james
c 18 6 endah regal
male
0104252455
rodgo.james
kilkil
```
and what i'm looking for displaying data is something like this (which is not currently happening ):
```
Name : james
Address : c 18 6
Gender : Male
Contact : 0104252455
Username : rodgo.james
Password : kilkil
```
and here is the function :
```
int molgha() {
ifstream in("owner.txt");
if (!in) {
cout << "Cannot open input file.\n";
return 1;
}
char str[255];
while (in) {
in.getline(str, 255); // delim defaults to '\n'
if (in) cout << str << endl;
}
system("pause");
in.close();
}
```
keep in mind that this text file contains the records of owners registered to the system, hence we may need to print out maybe 3 sets of owner data's with the same pattern without any errors, hence what is the best way to display data's like that continuously ?
|
2015/01/21
|
[
"https://Stackoverflow.com/questions/28073337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4464910/"
] |
Just add a array of labels, and print them based on the line you are getting from the file.
```
const string labels[6] = {
"Name", "Address", "Gender", "Contact", "Username", "Password"
};
int i = 0;
while (in) {
in.getline(str, 255); // delim defaults to '\n'
if (in) {
if (i == 6) i = 0;
cout << labels[i++] << " : " << str << endl;
}
}
```
|
So to re-state your question :
How can I add the fields Name: , Address: , etc to the output.
I would suggest the following approach :
Declare the field names in a static array :
```
const char* fieldNamesArray[6] = { "Name","Address","Gendre", "Contact","Username","Password"};
```
Inside your read / write function , consume each non-empty lines and assume that all entries have 6 fields and all time in the same order :
```
int curField=0;
while(in)
{
in.getLine(str,255);
if (strlen(str)>0)
{
cout<< fieldsNamesArray[curField] << " : " << str;
curField++;
}
if (curField>=6)
{
curField=0;
}
}
```
|
28,073,337
|
I've written a function that goes through the text file and reads all the data's and prints them out, but the format of displaying data's are wrong and it just prints out data line by line, like this:
```
james
c 18 6 endah regal
male
0104252455
rodgo.james
kilkil
```
and what i'm looking for displaying data is something like this (which is not currently happening ):
```
Name : james
Address : c 18 6
Gender : Male
Contact : 0104252455
Username : rodgo.james
Password : kilkil
```
and here is the function :
```
int molgha() {
ifstream in("owner.txt");
if (!in) {
cout << "Cannot open input file.\n";
return 1;
}
char str[255];
while (in) {
in.getline(str, 255); // delim defaults to '\n'
if (in) cout << str << endl;
}
system("pause");
in.close();
}
```
keep in mind that this text file contains the records of owners registered to the system, hence we may need to print out maybe 3 sets of owner data's with the same pattern without any errors, hence what is the best way to display data's like that continuously ?
|
2015/01/21
|
[
"https://Stackoverflow.com/questions/28073337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4464910/"
] |
You want to store your output names names, something like this:
```
std::vector<std::string> names { "Name", "Address", "Gender", "Contact", "Username", "Password" };
```
take an interator to it:
```
auto it = names.begin();
```
and print in your `while` loop:
```
if (in) cout << *it++ << " : " << str << endl;
```
|
So to re-state your question :
How can I add the fields Name: , Address: , etc to the output.
I would suggest the following approach :
Declare the field names in a static array :
```
const char* fieldNamesArray[6] = { "Name","Address","Gendre", "Contact","Username","Password"};
```
Inside your read / write function , consume each non-empty lines and assume that all entries have 6 fields and all time in the same order :
```
int curField=0;
while(in)
{
in.getLine(str,255);
if (strlen(str)>0)
{
cout<< fieldsNamesArray[curField] << " : " << str;
curField++;
}
if (curField>=6)
{
curField=0;
}
}
```
|
47,296,298
|
I'm trying to work out how to make a row of images responsive to the window width. So far I have:
```
<div class="image-slider">
<div><img src="/img1.jpg"></div>
<div><img src="/img2.jpg"></div>
<div><img src="/img3.jpg"></div>
<div><img src="/img4.jpg"></div>
<div><img src="/img5.jpg"></div>
</div>
```
and...
```
.image-slider {
display: flex;
overflow-y: scroll;
}
.image-slider div {
flex: 1;
margin: 5px
}
.image-slider div img {
width: 100%;
height: auto;
min-width: 125px;
}
```
This works nicely but what I want now is to make the fifth image disappear when the window is less than 880px and have the remaining four images resize to take up the remaining space.
I've tried adding a `wide-only` class to the fifth `div` tag:
```
<div class="wide-only"><img src="/img5.jpg"></div>
```
and then added a few media rules as shown below but it isn't quite working:
```
.image-slider div img.wide-only {
display:none;
}
@media(min-width:880px) {
.image-slider div img.wide-only {
flex: 1 /* not sure what this should be - tried display: flex too */
}
}
```
|
2017/11/14
|
[
"https://Stackoverflow.com/questions/47296298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1003632/"
] |
You added `display:none` so in the media query your should add `display:block` (i also corrected some CSS selector as you were not targeting the correct tag) :
```
.image-slider .wide-only {
display:none;
}
@media(min-width:880px) {
.image-slider .wide-only {
display:block;
flex: 1 /* not sure what this should be - tried display: flex too */
}
}
```
a full code :
```css
.image-slider {
display: flex;
overflow-y: scroll;
}
.image-slider div {
flex: 1;
margin: 5px
}
.image-slider div img {
width: 100%;
height: auto;
min-width: 125px;
}
.image-slider .wide-only {
display: none;
}
@media(min-width:880px) {
.image-slider .wide-only {
display: block;
flex: 1/* not sure what this should be - tried display: flex too */
}
}
```
```html
<div class="image-slider">
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div class="wide-only"><img src="https://lorempixel.com/400/400/"></div>
</div>
```
|
If you want to avoid adding additional classes in your html markup you can accomplish this with the `nth-child` pseudo selector and keep your markup cleaner and more maintainable.
`.image-slider div:nth-child(n+5);` is going to match the 5th, 6th, and so on child divs of image slider.
As an example below there are two of your 'sliders' one containing 5 elements and one containing 9 elements. Below 880px it will only show 4. Above that all will show.
An approach like this is more scalable because you can simply add additional media queries with a higher `nth-child` value, for instance if you wanted to show 6 at 1024 or something, 8 at 1280, etc. And you don't have to edit your HTML *and* your CSS to do it.
You'll notice I also reversed the media query to use max-width, so that we start with small screens, and improve the experience as they get larger. Sort of a mobile first approach.
(Obviously, view the snippet full screen)
```css
.image-slider {
display: flex;
margin-bottom: 1rem;
}
.image-slider div {
flex: 1;
margin: 3px;
}
.image-slider div img {
width: auto;
max-width: 100%;
}
@media(max-width:879px) {
.image-slider div:nth-child(n+5) {
display: none;
}
}
```
```html
<div class="image-slider">
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
</div>
<div class="image-slider">
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
<div><img src="https://lorempixel.com/400/400/"></div>
</div>
```
|
20,982,387
|
I am using oracle client 11.2.0
Dll version 4.112.3.0
We have a page in our application where people can give a sql statement and retreive results. basically do an oracle command.executereader
Recently one of my team members gave an update statement as a test and it actually performed an update on a record!!!!
Anyone who has encountered this?
Regards
Sid.
|
2014/01/07
|
[
"https://Stackoverflow.com/questions/20982387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1076100/"
] |
It is a normal (albeit a bit unsettling) behavior. ExecuteReader is expected to execute the sql command provided as CommandText and build a DbDataReader that you use to loop over the results.
If the command doesn't return any row to read is not something that the reader should prevent in any case. And so it is not expected that it checks if your command is really a SELECT statement.
Think for example if you pass a stored procedure name or if you have multiple sql batch to execute. (INSERT followed by a SELECT)
I think that the biggest problem here is the fact that you allow an arbitrary sql command typed by your users to reach the database engine. A very big hole in security. You should, at least, execute some analysis on the query text before submitting the code to the database engine.
|
I agree with Steve. Your reader will execute any command, and might get a bit confused if it's not a select and doesn't return a result set.
To prevent people from modifying anything, create a new user, grant select only (no update, no delete, no insert) on your tables to that user (`grant select on tablename to seconduser`). Then, log in as seconduser, and, create synonyms for your tables (`create synonym tablename for realowner.tablename`). Have your application use the seconduser when connecting to the DB. This should prevent people from "hacking" your site. If you want to be of the safe side, grant no permissions but `create session` to the second user to prevent him from creating tables, dropping your views and similar stuff (I'd guess your executereader won't allow DDL, but test it to make sure).
|
42,833,241
|
I am trying to add 2 complex numbers together, but i am getting the errors:
no operator "+" matches these operands
no operator "<<" matches these operands
```
#include <iostream>
using namespace std;
class complex
{
public:
double get_r() { return r; }
void set_r(double newr) { r=newr; }
double set_i() { return i; }
void set_i(double newi) { i = newi; }
private:
double r, i;
};
int main()
{
complex A, B;
A.set_r(1.0);
A.set_i(2.0);
B.set_r(3.0);
B.set_i(2.0);
complex sum = A+B;
cout << "summen er: " << sum << endl;
system("PAUSE");
return 0;
};
```
I'm very new to programming, but i can't see why it won't add these numbers together. What have I done wrong?
|
2017/03/16
|
[
"https://Stackoverflow.com/questions/42833241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7720995/"
] |
You must overload operators + and << (and each one in your need) for your defined classes. Note that operators are no more than specific functions with specific definition syntax (operator+, for example: C = A + B could be understood as C = A.sum(B)). Here a link about <http://en.cppreference.com/w/cpp/language/operators>
|
Complex numbers are part of the C++ standard. Here is the example from <http://en.cppreference.com/w/cpp/numeric/complex>.
```
#include <iostream>
#include <iomanip>
#include <complex>
#include <cmath>
int main()
{
using namespace std::complex_literals;
std::cout << std::fixed << std::setprecision(1);
std::complex<double> z1 = 1i * 1i;
std::cout << "i * i = " << z1 << '\n';
std::complex<double> z2 = std::pow(1i, 2);
std::cout << "pow(i, 2) = " << z2 << '\n';
double PI = std::acos(-1);
std::complex<double> z3 = std::exp(1i * PI);
std::cout << "exp(i * pi) = " << z3 << '\n';
std::complex<double> z4 = 1. + 2i, z5 = 1. - 2i;
std::cout << "(1+2i)*(1-2i) = " << z4*z5 << '\n';
}
```
Trying to implement a class complex yourself would require you define addition, equality, and ostream. And you would only have 5% of a fully implemented class. Looking at the header itself will reveal how those that wrote the C++ standard library implemented the whole thing.
|
42,833,241
|
I am trying to add 2 complex numbers together, but i am getting the errors:
no operator "+" matches these operands
no operator "<<" matches these operands
```
#include <iostream>
using namespace std;
class complex
{
public:
double get_r() { return r; }
void set_r(double newr) { r=newr; }
double set_i() { return i; }
void set_i(double newi) { i = newi; }
private:
double r, i;
};
int main()
{
complex A, B;
A.set_r(1.0);
A.set_i(2.0);
B.set_r(3.0);
B.set_i(2.0);
complex sum = A+B;
cout << "summen er: " << sum << endl;
system("PAUSE");
return 0;
};
```
I'm very new to programming, but i can't see why it won't add these numbers together. What have I done wrong?
|
2017/03/16
|
[
"https://Stackoverflow.com/questions/42833241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7720995/"
] |
You must overload operators + and << (and each one in your need) for your defined classes. Note that operators are no more than specific functions with specific definition syntax (operator+, for example: C = A + B could be understood as C = A.sum(B)). Here a link about <http://en.cppreference.com/w/cpp/language/operators>
|
All the arithmetic operators like plus, minus, multiply or divide only work with pre defined data types, like int, char, float etc.
Now if you want to add something in a class, you have to use the fundamental aspect of OO programming that is operator overloading.
Here is how you can achieve it.
```
#include <iostream>
using namespace std;
class complex
{
float x, y;
public:
complex()
{
}
complex(float real, float img)
{
x = real;
y = img;
}
friend complex operator+(complex,complex);
void display(void);
};
complex operator+(complex c,complex d)
{
complex t;
t.x = d.x + c.x;
t.y = d.y + t.y;
return(t);
};
void complex::display(void)
{
cout << x << "+i" << y << endl;
}
int main()
{
complex c1, c2, c3;
c1 = complex(2.5, 3.5);
c2 = complex(1.5, 5.5);
c3 = c1 + c2;//c3=opra+(c1,c2)
cout << "C1:" << endl;
c1.display();
cout << "C2:" << endl;
c2.display();
cout << "C3:" << endl;
c3.display();
}
```
|
42,833,241
|
I am trying to add 2 complex numbers together, but i am getting the errors:
no operator "+" matches these operands
no operator "<<" matches these operands
```
#include <iostream>
using namespace std;
class complex
{
public:
double get_r() { return r; }
void set_r(double newr) { r=newr; }
double set_i() { return i; }
void set_i(double newi) { i = newi; }
private:
double r, i;
};
int main()
{
complex A, B;
A.set_r(1.0);
A.set_i(2.0);
B.set_r(3.0);
B.set_i(2.0);
complex sum = A+B;
cout << "summen er: " << sum << endl;
system("PAUSE");
return 0;
};
```
I'm very new to programming, but i can't see why it won't add these numbers together. What have I done wrong?
|
2017/03/16
|
[
"https://Stackoverflow.com/questions/42833241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7720995/"
] |
Operator + is defined for builtin types and for some types from the standard library. As `complex` is here a custom class, you **must** define all operators that should act on it.
`operator +` could be defined as:
```
class complex {
...
complex operator + (const complex& other) {
return complex(get_r() + other.get_r(), get_i() + other.get_i());
}
...
};
```
Beware that does allow neither `A++` nor `A-B`. They would require (resp.) `complex & operator ++()` or `complex operator - (const complex &)`.
For stream insertion, the first parameter is the stream itself, so you must define a friend operator with 2 parameters outside the class:
```
outstream& opererator << (outstream &out, const complex& val) {
// output it the way you want
return out;
}
```
|
Complex numbers are part of the C++ standard. Here is the example from <http://en.cppreference.com/w/cpp/numeric/complex>.
```
#include <iostream>
#include <iomanip>
#include <complex>
#include <cmath>
int main()
{
using namespace std::complex_literals;
std::cout << std::fixed << std::setprecision(1);
std::complex<double> z1 = 1i * 1i;
std::cout << "i * i = " << z1 << '\n';
std::complex<double> z2 = std::pow(1i, 2);
std::cout << "pow(i, 2) = " << z2 << '\n';
double PI = std::acos(-1);
std::complex<double> z3 = std::exp(1i * PI);
std::cout << "exp(i * pi) = " << z3 << '\n';
std::complex<double> z4 = 1. + 2i, z5 = 1. - 2i;
std::cout << "(1+2i)*(1-2i) = " << z4*z5 << '\n';
}
```
Trying to implement a class complex yourself would require you define addition, equality, and ostream. And you would only have 5% of a fully implemented class. Looking at the header itself will reveal how those that wrote the C++ standard library implemented the whole thing.
|
42,833,241
|
I am trying to add 2 complex numbers together, but i am getting the errors:
no operator "+" matches these operands
no operator "<<" matches these operands
```
#include <iostream>
using namespace std;
class complex
{
public:
double get_r() { return r; }
void set_r(double newr) { r=newr; }
double set_i() { return i; }
void set_i(double newi) { i = newi; }
private:
double r, i;
};
int main()
{
complex A, B;
A.set_r(1.0);
A.set_i(2.0);
B.set_r(3.0);
B.set_i(2.0);
complex sum = A+B;
cout << "summen er: " << sum << endl;
system("PAUSE");
return 0;
};
```
I'm very new to programming, but i can't see why it won't add these numbers together. What have I done wrong?
|
2017/03/16
|
[
"https://Stackoverflow.com/questions/42833241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7720995/"
] |
Operator + is defined for builtin types and for some types from the standard library. As `complex` is here a custom class, you **must** define all operators that should act on it.
`operator +` could be defined as:
```
class complex {
...
complex operator + (const complex& other) {
return complex(get_r() + other.get_r(), get_i() + other.get_i());
}
...
};
```
Beware that does allow neither `A++` nor `A-B`. They would require (resp.) `complex & operator ++()` or `complex operator - (const complex &)`.
For stream insertion, the first parameter is the stream itself, so you must define a friend operator with 2 parameters outside the class:
```
outstream& opererator << (outstream &out, const complex& val) {
// output it the way you want
return out;
}
```
|
All the arithmetic operators like plus, minus, multiply or divide only work with pre defined data types, like int, char, float etc.
Now if you want to add something in a class, you have to use the fundamental aspect of OO programming that is operator overloading.
Here is how you can achieve it.
```
#include <iostream>
using namespace std;
class complex
{
float x, y;
public:
complex()
{
}
complex(float real, float img)
{
x = real;
y = img;
}
friend complex operator+(complex,complex);
void display(void);
};
complex operator+(complex c,complex d)
{
complex t;
t.x = d.x + c.x;
t.y = d.y + t.y;
return(t);
};
void complex::display(void)
{
cout << x << "+i" << y << endl;
}
int main()
{
complex c1, c2, c3;
c1 = complex(2.5, 3.5);
c2 = complex(1.5, 5.5);
c3 = c1 + c2;//c3=opra+(c1,c2)
cout << "C1:" << endl;
c1.display();
cout << "C2:" << endl;
c2.display();
cout << "C3:" << endl;
c3.display();
}
```
|
5,287,516
|
For those who used apt-get, you know that everytime you install / uninstall something, you get the notificatons saying you need / no longer need certain dependencies.
I'm trying to understand the theory behinds this and potentially implement my own version of this. I've done some googling, came up with mostly coupling stuff. From what I understand, coupling is 2 classes/modules that depends on each other. This is not exactly what I'm looking for. What I'm looking for is more like a dependencies tree generation, where I can find the least dependent module (I've already made a recursive way of doing this), and (this being the part i haven't done) finding what's no longer needed after removing a node.
Also, would learning about graph theory help? And is there any tutorials on that preferably using Python as a language?
|
2011/03/13
|
[
"https://Stackoverflow.com/questions/5287516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396183/"
] |
Graph theory is the way to go.
A graph is just a bunch of places (vertices) with roads (edges) between them, and in particular we're talking about a directed graph, which means one-way roads. Figuring out dependencies means, basically, finding out all the places that can reach a particular town along the one-way roads.
So now, you've got you bunch of modules, which become your vertices. Let's say we have A and B, and we know B depends on A, so there's a directed edge -- a "one way road" -- from A to B.
If C depends on B, then you have A→B→C.
Formally, a graph is just a collection of vertices and (ordered) pairs of vertices, called the edges. You want an graph algorithm called "topological sort", and now you've got some stuff to read.
|
1. Walk the old dependency tree. Build a `set` of all of the elements in it.
2. Walk the new dependency tree. Do the same as before.
3. Subtract the latter `set` from the former. The result is your answer.
Alternatively:
1. Walk the old dependency tree. At each node, store the number of things that depend on (point to) that node.
2. Remove the item you're wanting to remove. Follow all of its dependencies and decrement their usage count by 1. If decrementing this way lowers the count for a node to 0, it is no longer necessary.
The former is simpler to implement, but less efficient. The latter is efficient, but harder to implement.
|
5,287,516
|
For those who used apt-get, you know that everytime you install / uninstall something, you get the notificatons saying you need / no longer need certain dependencies.
I'm trying to understand the theory behinds this and potentially implement my own version of this. I've done some googling, came up with mostly coupling stuff. From what I understand, coupling is 2 classes/modules that depends on each other. This is not exactly what I'm looking for. What I'm looking for is more like a dependencies tree generation, where I can find the least dependent module (I've already made a recursive way of doing this), and (this being the part i haven't done) finding what's no longer needed after removing a node.
Also, would learning about graph theory help? And is there any tutorials on that preferably using Python as a language?
|
2011/03/13
|
[
"https://Stackoverflow.com/questions/5287516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396183/"
] |
I did wrote a tool for finding and drawing the dependencies between Python packages on PyPi. It's [gluttony](http://pypi.python.org/pypi/Gluttony)
And I did use to analysis the dependencies of some library I'm using. Here are some of diagrams:


I'm not sure is this what you want. If it is, you can read the source code [here](https://bitbucket.org/victorlin/gluttony), it is an open source project. For more dependencies diagrams, you can view the [gallery](http://code.google.com/p/python-gluttony/wiki/Gallery)
Talking about how I implement it, for finding package dependencies, I use [pip](http://www.pip-installer.org/en/latest/) as backend. For drawing diagrams, I use [Networkx](http://networkx.lanl.gov/).
|
1. Walk the old dependency tree. Build a `set` of all of the elements in it.
2. Walk the new dependency tree. Do the same as before.
3. Subtract the latter `set` from the former. The result is your answer.
Alternatively:
1. Walk the old dependency tree. At each node, store the number of things that depend on (point to) that node.
2. Remove the item you're wanting to remove. Follow all of its dependencies and decrement their usage count by 1. If decrementing this way lowers the count for a node to 0, it is no longer necessary.
The former is simpler to implement, but less efficient. The latter is efficient, but harder to implement.
|
5,287,516
|
For those who used apt-get, you know that everytime you install / uninstall something, you get the notificatons saying you need / no longer need certain dependencies.
I'm trying to understand the theory behinds this and potentially implement my own version of this. I've done some googling, came up with mostly coupling stuff. From what I understand, coupling is 2 classes/modules that depends on each other. This is not exactly what I'm looking for. What I'm looking for is more like a dependencies tree generation, where I can find the least dependent module (I've already made a recursive way of doing this), and (this being the part i haven't done) finding what's no longer needed after removing a node.
Also, would learning about graph theory help? And is there any tutorials on that preferably using Python as a language?
|
2011/03/13
|
[
"https://Stackoverflow.com/questions/5287516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396183/"
] |
[This](http://code.activestate.com/recipes/576570-dependency-resolver/) might be of some interest:
```
def dep(arg):
'''
Dependency resolver
"arg" is a dependency dictionary in which
the values are the dependencies of their respective keys.
'''
d=dict((k, set(arg[k])) for k in arg)
r=[]
while d:
# values not in keys (items without dep)
t=set(i for v in d.values() for i in v)-set(d.keys())
# and keys without value (items without dep)
t.update(k for k, v in d.items() if not v)
# can be done right away
r.append(t)
# and cleaned up
d=dict(((k, v-t) for k, v in d.items() if v))
return r
if __name__=='__main__':
d=dict(
a=('b','c'),
b=('c','d'),
e=(),
f=('c','e'),
g=('h','f'),
i=('f',)
)
print dep(d)
```
|
1. Walk the old dependency tree. Build a `set` of all of the elements in it.
2. Walk the new dependency tree. Do the same as before.
3. Subtract the latter `set` from the former. The result is your answer.
Alternatively:
1. Walk the old dependency tree. At each node, store the number of things that depend on (point to) that node.
2. Remove the item you're wanting to remove. Follow all of its dependencies and decrement their usage count by 1. If decrementing this way lowers the count for a node to 0, it is no longer necessary.
The former is simpler to implement, but less efficient. The latter is efficient, but harder to implement.
|
5,287,516
|
For those who used apt-get, you know that everytime you install / uninstall something, you get the notificatons saying you need / no longer need certain dependencies.
I'm trying to understand the theory behinds this and potentially implement my own version of this. I've done some googling, came up with mostly coupling stuff. From what I understand, coupling is 2 classes/modules that depends on each other. This is not exactly what I'm looking for. What I'm looking for is more like a dependencies tree generation, where I can find the least dependent module (I've already made a recursive way of doing this), and (this being the part i haven't done) finding what's no longer needed after removing a node.
Also, would learning about graph theory help? And is there any tutorials on that preferably using Python as a language?
|
2011/03/13
|
[
"https://Stackoverflow.com/questions/5287516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396183/"
] |
Graph theory is the way to go.
A graph is just a bunch of places (vertices) with roads (edges) between them, and in particular we're talking about a directed graph, which means one-way roads. Figuring out dependencies means, basically, finding out all the places that can reach a particular town along the one-way roads.
So now, you've got you bunch of modules, which become your vertices. Let's say we have A and B, and we know B depends on A, so there's a directed edge -- a "one way road" -- from A to B.
If C depends on B, then you have A→B→C.
Formally, a graph is just a collection of vertices and (ordered) pairs of vertices, called the edges. You want an graph algorithm called "topological sort", and now you've got some stuff to read.
|
I did wrote a tool for finding and drawing the dependencies between Python packages on PyPi. It's [gluttony](http://pypi.python.org/pypi/Gluttony)
And I did use to analysis the dependencies of some library I'm using. Here are some of diagrams:


I'm not sure is this what you want. If it is, you can read the source code [here](https://bitbucket.org/victorlin/gluttony), it is an open source project. For more dependencies diagrams, you can view the [gallery](http://code.google.com/p/python-gluttony/wiki/Gallery)
Talking about how I implement it, for finding package dependencies, I use [pip](http://www.pip-installer.org/en/latest/) as backend. For drawing diagrams, I use [Networkx](http://networkx.lanl.gov/).
|
5,287,516
|
For those who used apt-get, you know that everytime you install / uninstall something, you get the notificatons saying you need / no longer need certain dependencies.
I'm trying to understand the theory behinds this and potentially implement my own version of this. I've done some googling, came up with mostly coupling stuff. From what I understand, coupling is 2 classes/modules that depends on each other. This is not exactly what I'm looking for. What I'm looking for is more like a dependencies tree generation, where I can find the least dependent module (I've already made a recursive way of doing this), and (this being the part i haven't done) finding what's no longer needed after removing a node.
Also, would learning about graph theory help? And is there any tutorials on that preferably using Python as a language?
|
2011/03/13
|
[
"https://Stackoverflow.com/questions/5287516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396183/"
] |
Graph theory is the way to go.
A graph is just a bunch of places (vertices) with roads (edges) between them, and in particular we're talking about a directed graph, which means one-way roads. Figuring out dependencies means, basically, finding out all the places that can reach a particular town along the one-way roads.
So now, you've got you bunch of modules, which become your vertices. Let's say we have A and B, and we know B depends on A, so there's a directed edge -- a "one way road" -- from A to B.
If C depends on B, then you have A→B→C.
Formally, a graph is just a collection of vertices and (ordered) pairs of vertices, called the edges. You want an graph algorithm called "topological sort", and now you've got some stuff to read.
|
[This](http://code.activestate.com/recipes/576570-dependency-resolver/) might be of some interest:
```
def dep(arg):
'''
Dependency resolver
"arg" is a dependency dictionary in which
the values are the dependencies of their respective keys.
'''
d=dict((k, set(arg[k])) for k in arg)
r=[]
while d:
# values not in keys (items without dep)
t=set(i for v in d.values() for i in v)-set(d.keys())
# and keys without value (items without dep)
t.update(k for k, v in d.items() if not v)
# can be done right away
r.append(t)
# and cleaned up
d=dict(((k, v-t) for k, v in d.items() if v))
return r
if __name__=='__main__':
d=dict(
a=('b','c'),
b=('c','d'),
e=(),
f=('c','e'),
g=('h','f'),
i=('f',)
)
print dep(d)
```
|
5,287,516
|
For those who used apt-get, you know that everytime you install / uninstall something, you get the notificatons saying you need / no longer need certain dependencies.
I'm trying to understand the theory behinds this and potentially implement my own version of this. I've done some googling, came up with mostly coupling stuff. From what I understand, coupling is 2 classes/modules that depends on each other. This is not exactly what I'm looking for. What I'm looking for is more like a dependencies tree generation, where I can find the least dependent module (I've already made a recursive way of doing this), and (this being the part i haven't done) finding what's no longer needed after removing a node.
Also, would learning about graph theory help? And is there any tutorials on that preferably using Python as a language?
|
2011/03/13
|
[
"https://Stackoverflow.com/questions/5287516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396183/"
] |
Graph theory is the way to go.
A graph is just a bunch of places (vertices) with roads (edges) between them, and in particular we're talking about a directed graph, which means one-way roads. Figuring out dependencies means, basically, finding out all the places that can reach a particular town along the one-way roads.
So now, you've got you bunch of modules, which become your vertices. Let's say we have A and B, and we know B depends on A, so there's a directed edge -- a "one way road" -- from A to B.
If C depends on B, then you have A→B→C.
Formally, a graph is just a collection of vertices and (ordered) pairs of vertices, called the edges. You want an graph algorithm called "topological sort", and now you've got some stuff to read.
|
I think the step you're looking for is to differentiate between packages you has explicitly installed, and those that are dependencies. Once you have done this you can build dependency trees of all *requested* packages, and compare the set of these packages with the set of *installed* packages. XORing these, assuming all requested packages are installed, should give you the set of all packages which are no longer depended on.
|
5,287,516
|
For those who used apt-get, you know that everytime you install / uninstall something, you get the notificatons saying you need / no longer need certain dependencies.
I'm trying to understand the theory behinds this and potentially implement my own version of this. I've done some googling, came up with mostly coupling stuff. From what I understand, coupling is 2 classes/modules that depends on each other. This is not exactly what I'm looking for. What I'm looking for is more like a dependencies tree generation, where I can find the least dependent module (I've already made a recursive way of doing this), and (this being the part i haven't done) finding what's no longer needed after removing a node.
Also, would learning about graph theory help? And is there any tutorials on that preferably using Python as a language?
|
2011/03/13
|
[
"https://Stackoverflow.com/questions/5287516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396183/"
] |
I did wrote a tool for finding and drawing the dependencies between Python packages on PyPi. It's [gluttony](http://pypi.python.org/pypi/Gluttony)
And I did use to analysis the dependencies of some library I'm using. Here are some of diagrams:


I'm not sure is this what you want. If it is, you can read the source code [here](https://bitbucket.org/victorlin/gluttony), it is an open source project. For more dependencies diagrams, you can view the [gallery](http://code.google.com/p/python-gluttony/wiki/Gallery)
Talking about how I implement it, for finding package dependencies, I use [pip](http://www.pip-installer.org/en/latest/) as backend. For drawing diagrams, I use [Networkx](http://networkx.lanl.gov/).
|
I think the step you're looking for is to differentiate between packages you has explicitly installed, and those that are dependencies. Once you have done this you can build dependency trees of all *requested* packages, and compare the set of these packages with the set of *installed* packages. XORing these, assuming all requested packages are installed, should give you the set of all packages which are no longer depended on.
|
5,287,516
|
For those who used apt-get, you know that everytime you install / uninstall something, you get the notificatons saying you need / no longer need certain dependencies.
I'm trying to understand the theory behinds this and potentially implement my own version of this. I've done some googling, came up with mostly coupling stuff. From what I understand, coupling is 2 classes/modules that depends on each other. This is not exactly what I'm looking for. What I'm looking for is more like a dependencies tree generation, where I can find the least dependent module (I've already made a recursive way of doing this), and (this being the part i haven't done) finding what's no longer needed after removing a node.
Also, would learning about graph theory help? And is there any tutorials on that preferably using Python as a language?
|
2011/03/13
|
[
"https://Stackoverflow.com/questions/5287516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396183/"
] |
[This](http://code.activestate.com/recipes/576570-dependency-resolver/) might be of some interest:
```
def dep(arg):
'''
Dependency resolver
"arg" is a dependency dictionary in which
the values are the dependencies of their respective keys.
'''
d=dict((k, set(arg[k])) for k in arg)
r=[]
while d:
# values not in keys (items without dep)
t=set(i for v in d.values() for i in v)-set(d.keys())
# and keys without value (items without dep)
t.update(k for k, v in d.items() if not v)
# can be done right away
r.append(t)
# and cleaned up
d=dict(((k, v-t) for k, v in d.items() if v))
return r
if __name__=='__main__':
d=dict(
a=('b','c'),
b=('c','d'),
e=(),
f=('c','e'),
g=('h','f'),
i=('f',)
)
print dep(d)
```
|
I think the step you're looking for is to differentiate between packages you has explicitly installed, and those that are dependencies. Once you have done this you can build dependency trees of all *requested* packages, and compare the set of these packages with the set of *installed* packages. XORing these, assuming all requested packages are installed, should give you the set of all packages which are no longer depended on.
|
38,731,854
|
My question is very simple, but I did not found an answer (sorry if it is somewhere and just did not found it).
How `sharedpreferences.editor.apply()` works?
To be clear, I have this code for example:
```
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.apply();
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
```
This works in my project. But is it better regarding performance to use this above or this below?
```
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
```
Basically, the code above is correct?
Will it work for all the `putSomething` above or `apply()` works just for one `putSomething`?
|
2016/08/02
|
[
"https://Stackoverflow.com/questions/38731854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5403137/"
] |
The last one for sure. Both `apply()` and `commit()` will save all changes. Why would you even want to apply the changes multiple times? Although the last one is better for performance, you won't really notice because `apply()` is aSync. Yet, don't do unnecessary stuff. However `commit()` will decrease performance because it is not aSync.
|
calling apply() once saves all the changes made with the editor object. So the code in below is the correct one. =)
|
38,731,854
|
My question is very simple, but I did not found an answer (sorry if it is somewhere and just did not found it).
How `sharedpreferences.editor.apply()` works?
To be clear, I have this code for example:
```
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.apply();
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
```
This works in my project. But is it better regarding performance to use this above or this below?
```
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
```
Basically, the code above is correct?
Will it work for all the `putSomething` above or `apply()` works just for one `putSomething`?
|
2016/08/02
|
[
"https://Stackoverflow.com/questions/38731854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5403137/"
] |
The last one for sure. Both `apply()` and `commit()` will save all changes. Why would you even want to apply the changes multiple times? Although the last one is better for performance, you won't really notice because `apply()` is aSync. Yet, don't do unnecessary stuff. However `commit()` will decrease performance because it is not aSync.
|
The code above is the best one, the method apply() will save all the SharedPreferences.Editor changes, and is unnecessary call it every time.
void apply ()
Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.
Note that when two editors are modifying preferences at the same time, the last one to call apply wins.
If you want to know the best way to use SharedPreferences visit this site:
[Best Practices](http://blog.yakivmospan.com/best-practices-for-sharedpreferences/)
And a little bit documentation:
[Documentation](https://developer.android.com/reference/android/content/SharedPreferences.Editor.html)
|
38,731,854
|
My question is very simple, but I did not found an answer (sorry if it is somewhere and just did not found it).
How `sharedpreferences.editor.apply()` works?
To be clear, I have this code for example:
```
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.apply();
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
```
This works in my project. But is it better regarding performance to use this above or this below?
```
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
```
Basically, the code above is correct?
Will it work for all the `putSomething` above or `apply()` works just for one `putSomething`?
|
2016/08/02
|
[
"https://Stackoverflow.com/questions/38731854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5403137/"
] |
apply vs commit
The main different of using apply() and commit()
`.apply()` will save your changed in background thread.
`.commit()` will save your changed in main thread.
These two methods will produce same result.
|
calling apply() once saves all the changes made with the editor object. So the code in below is the correct one. =)
|
38,731,854
|
My question is very simple, but I did not found an answer (sorry if it is somewhere and just did not found it).
How `sharedpreferences.editor.apply()` works?
To be clear, I have this code for example:
```
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.apply();
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.apply();
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
```
This works in my project. But is it better regarding performance to use this above or this below?
```
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.putInt(somestring, someint);
MainActivity.editor.putString(somestring,somestring);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putLong(somestring, somelong);
MainActivity.editor.putBoolean(somestring, someboolean);
MainActivity.editor.apply();
```
Basically, the code above is correct?
Will it work for all the `putSomething` above or `apply()` works just for one `putSomething`?
|
2016/08/02
|
[
"https://Stackoverflow.com/questions/38731854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5403137/"
] |
apply vs commit
The main different of using apply() and commit()
`.apply()` will save your changed in background thread.
`.commit()` will save your changed in main thread.
These two methods will produce same result.
|
The code above is the best one, the method apply() will save all the SharedPreferences.Editor changes, and is unnecessary call it every time.
void apply ()
Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.
Note that when two editors are modifying preferences at the same time, the last one to call apply wins.
If you want to know the best way to use SharedPreferences visit this site:
[Best Practices](http://blog.yakivmospan.com/best-practices-for-sharedpreferences/)
And a little bit documentation:
[Documentation](https://developer.android.com/reference/android/content/SharedPreferences.Editor.html)
|
12,087,360
|
I would like to add elements in a loop to a list in such a way that the loop body will execute also for them. I know that this technique is very common in order to prevent `ConcurrentModificationException`:
```
List<Element> thingsToBeAdd = new ArrayList<Element>();
for(Iterator<Element> it = mElements.iterator(); it.hasNext();) {
Element element = it.next();
if(...) {
//irrelevant stuff..
if(element.cFlag){
// mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
thingsToBeAdd.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
element.cFlag = false;
}
}
}
mElements.addAll(thingsToBeAdd );
```
Unfortunately it doesn't execute the loop for the new elements.
Edit:
```
List<Element> thingsToBeAdd = new ArrayList<Element>();
for(Iterator<Element> it = mElements.iterator(); it.hasNext();) {
Element element = it.next();
if(...) {
//irrelevant stuff..
if(element.cFlag){
// mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
thingsToBeAdd.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
element.cFlag = false;
}
}
mElements.addAll(thingsToBeAdd );
}
```
This will result in `ConcurrentModificationException`.
|
2012/08/23
|
[
"https://Stackoverflow.com/questions/12087360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1243996/"
] |
```
container.RegisterType<ITest>(
new ContainerControlledLifetimeManager(),
new InjectionFactory(o => Helper.GetITestIntance()));
```
|
According to this: <http://social.msdn.microsoft.com/Forums/en/wpf/thread/b71665b9-cc71-4c88-9776-6ccb4f871819> there does not seem to be a direct way. You can either register an instance that will be used, or register a "Type" that the container will instantiate on his own at some moments when it is required. There does not seem to be any way to register a "factory", nor the Type-registering methods do not take any delegates/callbacks..
There **could** be some way with use of Container Extensions - maybe you will be able to intercept the query for an instance and then provide your own response.. I think this a good place to start reading on it:
<http://visualizationtools.net/default/unity-objectbuilder-part-i/>
<http://visualizationtools.net/default/unity-objectbuilder-part-ii/>
edit: sorry, sorry, I've overlooked the `LifetimeManager` registration paramter. It seems this is exactly what you are looking for: <http://tavaresstudios.com/Blog/post/Writing-Custom-Lifetime-Managers.aspx>
So, write a factory in form of LifetimeManager, the creation would be done in GetValue method, and register a Type with your this Manager - and the Unity will ask the manager for object instances.
|
304,948
|
Firefox 21.0 won't start on my Ubuntu 12.04 system with error message:
```
Your Firefox profile cannot be loaded. It may be missing or inaccessible.
```
I have tried everything including removing the `~/.mozilla` folder, reinstalling firefox,
setting the *owner* and *user* rights of the `~/.mozilla` folder. Nothing works!
What am I missing? Is there any other system folder I have to change the user rights on?
|
2013/06/06
|
[
"https://askubuntu.com/questions/304948",
"https://askubuntu.com",
"https://askubuntu.com/users/-1/"
] |
I found that both my `~/.cache/mozilla` and `~/.mozilla` directory trees were owned by `root:root` and should have owned by username:group. This was coming off a fresh install of 12.04 LTS therefore I suspect a bug in a setup script.
Make sure you are in your home directory and your own userid:
```
cd
sudo chown -R YourUsername:YourGroupname ./.mozilla
sudo chown -R YourUsername:YourGroupname ./.cache/mozilla
```
Replace YourUsername with your own username, and YourGroupname with your preferred group which by default is the same name as your username.
The .mozilla directory was easy to find, however the .cache directory was not obvious to me. I was able find firefox was looking at the .cache directory by starting firefox and leaving that error message dialog up, and while firefox was still running in a terminal entering: `lsof | grep firefox`
|
Although you seem to have set **permissions** it sounds exactly like a permission problem. Have a look at this thread and the official *Firefox Support* forum with the same problem:
[Firefox won't start](http://ubuntuforums.org/showthread.php?t=1931125)
[Use the Profile Manager to create and remove Firefox profiles](https://support.mozilla.org/en-US/kb/profile-manager-create-and-remove-firefox-profiles)
|
304,948
|
Firefox 21.0 won't start on my Ubuntu 12.04 system with error message:
```
Your Firefox profile cannot be loaded. It may be missing or inaccessible.
```
I have tried everything including removing the `~/.mozilla` folder, reinstalling firefox,
setting the *owner* and *user* rights of the `~/.mozilla` folder. Nothing works!
What am I missing? Is there any other system folder I have to change the user rights on?
|
2013/06/06
|
[
"https://askubuntu.com/questions/304948",
"https://askubuntu.com",
"https://askubuntu.com/users/-1/"
] |
I found that both my `~/.cache/mozilla` and `~/.mozilla` directory trees were owned by `root:root` and should have owned by username:group. This was coming off a fresh install of 12.04 LTS therefore I suspect a bug in a setup script.
Make sure you are in your home directory and your own userid:
```
cd
sudo chown -R YourUsername:YourGroupname ./.mozilla
sudo chown -R YourUsername:YourGroupname ./.cache/mozilla
```
Replace YourUsername with your own username, and YourGroupname with your preferred group which by default is the same name as your username.
The .mozilla directory was easy to find, however the .cache directory was not obvious to me. I was able find firefox was looking at the .cache directory by starting firefox and leaving that error message dialog up, and while firefox was still running in a terminal entering: `lsof | grep firefox`
|
1. Delete your `.mozilla/` folder.
2. Download the Firefox zip file from Mozilla: <http://www.getfirefox.com/>
3. Unzip it
4. Run `./firefox` from the terminal
This will automatically generate a new profile for you. Close Firefox.
You can now click on the Firefox icon and be able to use it as before.
|
304,948
|
Firefox 21.0 won't start on my Ubuntu 12.04 system with error message:
```
Your Firefox profile cannot be loaded. It may be missing or inaccessible.
```
I have tried everything including removing the `~/.mozilla` folder, reinstalling firefox,
setting the *owner* and *user* rights of the `~/.mozilla` folder. Nothing works!
What am I missing? Is there any other system folder I have to change the user rights on?
|
2013/06/06
|
[
"https://askubuntu.com/questions/304948",
"https://askubuntu.com",
"https://askubuntu.com/users/-1/"
] |
I found that both my `~/.cache/mozilla` and `~/.mozilla` directory trees were owned by `root:root` and should have owned by username:group. This was coming off a fresh install of 12.04 LTS therefore I suspect a bug in a setup script.
Make sure you are in your home directory and your own userid:
```
cd
sudo chown -R YourUsername:YourGroupname ./.mozilla
sudo chown -R YourUsername:YourGroupname ./.cache/mozilla
```
Replace YourUsername with your own username, and YourGroupname with your preferred group which by default is the same name as your username.
The .mozilla directory was easy to find, however the .cache directory was not obvious to me. I was able find firefox was looking at the .cache directory by starting firefox and leaving that error message dialog up, and while firefox was still running in a terminal entering: `lsof | grep firefox`
|
Close your firefox and then run the following in the terminal:
```
sudo chown -R $USER:$USER ~/.mozilla
```
|
304,948
|
Firefox 21.0 won't start on my Ubuntu 12.04 system with error message:
```
Your Firefox profile cannot be loaded. It may be missing or inaccessible.
```
I have tried everything including removing the `~/.mozilla` folder, reinstalling firefox,
setting the *owner* and *user* rights of the `~/.mozilla` folder. Nothing works!
What am I missing? Is there any other system folder I have to change the user rights on?
|
2013/06/06
|
[
"https://askubuntu.com/questions/304948",
"https://askubuntu.com",
"https://askubuntu.com/users/-1/"
] |
I found that both my `~/.cache/mozilla` and `~/.mozilla` directory trees were owned by `root:root` and should have owned by username:group. This was coming off a fresh install of 12.04 LTS therefore I suspect a bug in a setup script.
Make sure you are in your home directory and your own userid:
```
cd
sudo chown -R YourUsername:YourGroupname ./.mozilla
sudo chown -R YourUsername:YourGroupname ./.cache/mozilla
```
Replace YourUsername with your own username, and YourGroupname with your preferred group which by default is the same name as your username.
The .mozilla directory was easy to find, however the .cache directory was not obvious to me. I was able find firefox was looking at the .cache directory by starting firefox and leaving that error message dialog up, and while firefox was still running in a terminal entering: `lsof | grep firefox`
|
You dont have to do anything only need to delete firefox folder from .mozilla/ (Home/.mozila)
And then just try to run firefox it will automaticaly recreat the new profile in same location and your firefox will run.
Thanks,
Sandesh Joshi
|
304,948
|
Firefox 21.0 won't start on my Ubuntu 12.04 system with error message:
```
Your Firefox profile cannot be loaded. It may be missing or inaccessible.
```
I have tried everything including removing the `~/.mozilla` folder, reinstalling firefox,
setting the *owner* and *user* rights of the `~/.mozilla` folder. Nothing works!
What am I missing? Is there any other system folder I have to change the user rights on?
|
2013/06/06
|
[
"https://askubuntu.com/questions/304948",
"https://askubuntu.com",
"https://askubuntu.com/users/-1/"
] |
I found that both my `~/.cache/mozilla` and `~/.mozilla` directory trees were owned by `root:root` and should have owned by username:group. This was coming off a fresh install of 12.04 LTS therefore I suspect a bug in a setup script.
Make sure you are in your home directory and your own userid:
```
cd
sudo chown -R YourUsername:YourGroupname ./.mozilla
sudo chown -R YourUsername:YourGroupname ./.cache/mozilla
```
Replace YourUsername with your own username, and YourGroupname with your preferred group which by default is the same name as your username.
The .mozilla directory was easy to find, however the .cache directory was not obvious to me. I was able find firefox was looking at the .cache directory by starting firefox and leaving that error message dialog up, and while firefox was still running in a terminal entering: `lsof | grep firefox`
|
Remove current profile by using following command:
```
~/.mozilla/firefox# rm profiles.ini
```
after that create new profile as:
```
~/.mozilla/firefox# firefox -P
```
and follow the wizard's instructions.
|
2,184,411
|
Consider the following function.
$g(x, y)=e^{−8x^2−6y^2+24y}$
(a) Find the critical point of g.
(b) Using your critical point in (a), find the value of D(a, b) from the Second Partials test that is used to classify the critical point.
(c) Use the Second Partials test to classify the critical point from (a).
For C, the options are either
Saddle Point, Relative Minimum, Relative Maximum, or Inconclusive
I could really used some help finding the critical point. I separated them into $f\_x$ and $f\_y$ and set them equal to 0 and got (24,0). I'm not sure if this answer is right and what I am supposed to do to find b.
|
2017/03/13
|
[
"https://math.stackexchange.com/questions/2184411",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/422674/"
] |
Without derivatives:
$g(x,y)=\exp(-8x^2-6(y-2)^2+24 ) \le \exp(24)=g(0,2)$
|
Your answer is not right ! We have
$g\_x(x,y)=g(x,y)(-16x)=0 \iff x=0$
and
$g\_y(x,y)=g(x,y)(-12y+24)=0 \iff y=2$.
|
2,184,411
|
Consider the following function.
$g(x, y)=e^{−8x^2−6y^2+24y}$
(a) Find the critical point of g.
(b) Using your critical point in (a), find the value of D(a, b) from the Second Partials test that is used to classify the critical point.
(c) Use the Second Partials test to classify the critical point from (a).
For C, the options are either
Saddle Point, Relative Minimum, Relative Maximum, or Inconclusive
I could really used some help finding the critical point. I separated them into $f\_x$ and $f\_y$ and set them equal to 0 and got (24,0). I'm not sure if this answer is right and what I am supposed to do to find b.
|
2017/03/13
|
[
"https://math.stackexchange.com/questions/2184411",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/422674/"
] |
Without derivatives:
$g(x,y)=\exp(-8x^2-6(y-2)^2+24 ) \le \exp(24)=g(0,2)$
|
If we write this function as
$$ g(x,y) \ \ = \ \ e^{−8x^2−6y^2+24y} \ \ = \ \ e^{−(8x^2+6y^2-24y)} \ \ = \ \ e^{−[8x^2 \ + \ 6(y-2)^2 \ + 24]} \ \ = \ \ e^{−8x^2} · e^{−6(y-2)^2} · e^{24} \ \ , $$
one thing we can see is that the level curves are ellipses $ \ 8x^2 \ + \ 6(y-2)^2 \ = \ C \ \ , \ \ C \ \ge \ 0 \ $ centered on $ \ (0,2) \ \ , $ using "completing the square" as **Fred** shows. Since we can express $ \ g \ $ as an "exponentially-decaying" function, we would expect there to be a maximum value for the function $ \ g(0,2) \ = \ e^{24} \ . $ [The graph is only worth plotting with *extreme* vertical scale compression, since $ \ e^{24} \ = \ (e^3)^8 \ \approx \ 20^8 \ \approx \ 2.6 · 10^{10} \ . $ ]
You didn't show what you found for the first partial derivatives, so it isn't possible to see why you found the result you did. We work out the relevant partial derivatives here to see up the Hessian matrix:
$$ f\_x \ \ = \ \ e^{24} \ · \ (-16x) · e^{−8x^2} \ · \ e^{−6(y-2)^2} \ \ , \ \ f\_y \ \ = \ \ e^{24} \ · \ e^{−8x^2} \ · \ [-6·2·(y-2)]·e^{−6(y-2)^2} \ \ ; $$
[the second partial derivatives require the application of the Product Rule]
$$ f\_{xx} \ \ = \ \ e^{24} \ · \ \left[ \ (-16) · e^{−8x^2} \ + \ (-16x) · (-16x) · e^{−8x^2} \ \right] \ · \ e^{−6(y-2)^2} \ \ , $$
$$ f\_{yy} \ \ = \ \ e^{24} \ · \ (-16) · e^{−8x^2} \ · \ \left[ \ (-12) · e^{−6(y-2)^2} \ + \ [-6·2·(y-2)]^2·e^{−6(y-2)^2} \right]\ \ , $$
$$ f\_{xy} \ \ = \ \ e^{24} \ · \ (-16) · e^{−8x^2} \ · \ [-12·(y-2)]·e^{−6(y-2)^2} \ . $$
Simplifying the expressions, the Hessian matrix is then
$$ \mathcal{H} \ \ = \ \ \left| \begin{array}{cc} -16·(1-16x^2) & 16·12·(y-2) \\
16·12·(y-2) & 12^2·(y-2)^2 \ - \ 12 \end{array} \right| \ · \ e^{−8x^2} · e^{−6(y-2)^2} · e^{24} $$
[there is no compelling need to "pretty up" the entries, as it is easier to see what the evaluation will be in this form] .
At the critical point,
$$ \mathcal{H} \ |\_{(0,2)} \ \ = \ \ \left| \begin{array}{cc} -16·(1-0) & 16·12·(2-2) \\
16·12·(2-2) & 12^2·(2-2)^2 \ - \ 12 \end{array} \right| \ · \ e^0 · e^0 · e^{24} $$
$$ = \ \ \left| \begin{array}{cc} -16 & 0 \\
0 & -12 \end{array} \right| · \ e^{24} \ \ > \ \ 0 \ \ . $$
This shows that the critical point is a local extremum. Since
$$ f\_{xx} \ |\_{(0,2)} \ \ = \ \ e^{24} \ · \ \left[ \ (-16) · e^0 \ + \ 0 · 0 · e^0 \ \right] \ · \ e^0 \ \ = \ \ (-16) · e^{24} \ \ < \ \ 0 , $$
it is a **local maximum**, as we anticipated.
|
1,062,450
|
in web-based application, which method is prefered? I also need some examples about this issue.
Thanks in advance.
|
2009/06/30
|
[
"https://Stackoverflow.com/questions/1062450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61156/"
] |
If you're going to update a large number of records then it would be advisable to use bulk/batch updates. Modern database systems support special bulk update facility. The main benefit of using bulk updates is high performance. Bulk update facility generally reduces the amount of data being transmitted across the the network and does a number of optimizations for multiple record updates.
|
This really varies between all different cases. You can't expect a general and correct answer to this question. Different measures for different needs, etc.
|
69,033,385
|
I have a dataframe (see below) and I am having some troubles when I try to clean it.
Row dataset looks like this:
```
df <- data.frame(
id = c(1, 1, 1, 2, 2),
company_name = c("aaa", NA, NA, "ccc", NA),
directors = c(NA, "xxx", "bbb", NA, "ooo"),
year = c(2001, 2001, 2001, 2002, 2002)
)
> df
id company_name directors year
1 1 aaa <NA> 2001
2 1 <NA> xxx 2001
3 1 <NA> bbb 2001
4 2 ccc <NA> 2002
5 2 <NA> ooo 2002
```
and I need it to look like this:
```
df_fixed <- data.frame(
id = c(1, 1, 1, 2, 2),
company_name = c("aaa", "aaa", "aaa", "ccc", "ccc"),
directors = c(NA, "xxx", "bbb", NA, "ooo"),
year = c(2001, 2001, 2001, 2002, 2002)
)
> df_fixed
id company_name directors year
1 1 aaa <NA> 2001
2 1 aaa xxx 2001
3 1 aaa bbb 2001
4 2 ccc <NA> 2002
5 2 ccc ooo 2002
```
Then I can delete all data without director names.
I think it can be done by some matching. I tried to store a unique list of ids to select company names, but it doesn't work well. I greatly appreciate it if you have any suggestions!
|
2021/09/02
|
[
"https://Stackoverflow.com/questions/69033385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16814345/"
] |
We can use `fill` from `tidyr`
```
library(tidyr)
library(dplyr)
df %>%
fill(company_name)
```
-output
```
id company_name directors year
1 1 aaa <NA> 2001
2 1 aaa xxx 2001
3 1 aaa bbb 2001
4 2 ccc <NA> 2002
5 2 ccc ooo 2002
```
---
Or if it is grouped by 'id', 'year'
```
df %>%
group_by(id, year) %>%
fill(company_name, .direction = 'downup') %>%
ungroup
```
|
I'm not fully sure from your question if that was what you were asking, but if you want to fill all NA in the column V1 of a dataframe df with a value "val", you can do it with
```
df$V1[is.na(df$V1)] <- "val"
```
|
69,033,385
|
I have a dataframe (see below) and I am having some troubles when I try to clean it.
Row dataset looks like this:
```
df <- data.frame(
id = c(1, 1, 1, 2, 2),
company_name = c("aaa", NA, NA, "ccc", NA),
directors = c(NA, "xxx", "bbb", NA, "ooo"),
year = c(2001, 2001, 2001, 2002, 2002)
)
> df
id company_name directors year
1 1 aaa <NA> 2001
2 1 <NA> xxx 2001
3 1 <NA> bbb 2001
4 2 ccc <NA> 2002
5 2 <NA> ooo 2002
```
and I need it to look like this:
```
df_fixed <- data.frame(
id = c(1, 1, 1, 2, 2),
company_name = c("aaa", "aaa", "aaa", "ccc", "ccc"),
directors = c(NA, "xxx", "bbb", NA, "ooo"),
year = c(2001, 2001, 2001, 2002, 2002)
)
> df_fixed
id company_name directors year
1 1 aaa <NA> 2001
2 1 aaa xxx 2001
3 1 aaa bbb 2001
4 2 ccc <NA> 2002
5 2 ccc ooo 2002
```
Then I can delete all data without director names.
I think it can be done by some matching. I tried to store a unique list of ids to select company names, but it doesn't work well. I greatly appreciate it if you have any suggestions!
|
2021/09/02
|
[
"https://Stackoverflow.com/questions/69033385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16814345/"
] |
We can use `fill` from `tidyr`
```
library(tidyr)
library(dplyr)
df %>%
fill(company_name)
```
-output
```
id company_name directors year
1 1 aaa <NA> 2001
2 1 aaa xxx 2001
3 1 aaa bbb 2001
4 2 ccc <NA> 2002
5 2 ccc ooo 2002
```
---
Or if it is grouped by 'id', 'year'
```
df %>%
group_by(id, year) %>%
fill(company_name, .direction = 'downup') %>%
ungroup
```
|
There are a number of ways to do this. One really easy one is to use the `na.locf` function from the `zoo` package.
```
library(zoo)
df$company_name <- na.locf(df$company_name)
> df
id company_name directors year
1 1 aaa <NA> 2001
2 1 <NA> xxx 2001
3 1 <NA> bbb 2001
4 2 ccc <NA> 2002
5 2 <NA> ooo 2002
```
A base R way that assumes that the map of ID and company\_name is what dictates the values is to merge the unique ID/company name set back into the data frame.
```
company_ids <- unique(df[!is.na(df$company_name), c("id", "company_name")])
df_new <- merge(
x = df[c("id", "directors", "year")],
y = company_ids
)
> df_new
id directors year company_name
1 1 <NA> 2001 aaa
2 1 xxx 2001 aaa
3 1 bbb 2001 aaa
4 2 <NA> 2002 ccc
5 2 ooo 2002 ccc
```
This is a blunt approach using a `for` loop (often frowned upon but not actually that big of a deal).
```
val <- NA
for (x in seq_len(nrow(df))) {
if (!is.na(df[x, "company_name"])) {
val <- df[x, "company_name"]
} else {
df[x, "company_name"] <- val
}
}
> df
id company_name directors year
1 1 aaa <NA> 2001
2 1 aaa xxx 2001
3 1 aaa bbb 2001
4 2 ccc <NA> 2002
5 2 ccc ooo 2002
```
|
19,769,141
|
With SimpleMembership you can add an icon to the external authentication provider buttons like this:
SimpleMembership:
```
Dictionary<string, object> FacebooksocialData = new Dictionary<string, object>();
FacebooksocialData.Add("Icon", "/content/images/gui/loginFacebook.png");
OAuthWebSecurity.RegisterFacebookClient(
appId: "x",
appSecret: "x",
displayName: "Facebook",
extraData: FacebooksocialData);
```
And then display them like this in your view:
```
@foreach (AuthenticationClientData p in Model)
{
<button class="externalLoginService" style="cursor:pointer;color:transparent;border:none;background:url(@p.ExtraData["Icon"]);width:94px;height:93px;margin-right:20px;" type="submit" name="provider" value="@p.AuthenticationClient.ProviderName" title="Log in with @p.DisplayName">@p.DisplayName</button>
}
```
ASP.NET Identity(?):
```
app.UseFacebookAuthentication(
appId: "x",
appSecret: "x");
```
How to achieve the same thing using ASP.NET Identity (controller and view)?
|
2013/11/04
|
[
"https://Stackoverflow.com/questions/19769141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/687549/"
] |
Another way of doing it:
Took some of what is in this blog (uses zocial icons but I found those to be overkill - see css file and you'll know what I mean):
<http://www.beabigrockstar.com/pretty-social-login-buttons-for-asp-net-mvc-5/>
And did it like this:
`Startup.Auth.cs` (no extra nothing, just the standard default stuff from an MVC 5 app)
```
app.UseFacebookAuthentication(appId: "x", appSecret: "x");
app.UseGoogleAuthentication();
```
CSS:
```
.socialLoginButton {
cursor:pointer;color:transparent;border:none;width:94px;height:93px;margin-right:20px;
}
.socialLoginButton.facebook {
background:url(/content/images/gui/loginFacebook.png);
}
.socialLoginButton.google {
background:url(/content/images/gui/loginGoogle.png);
}
```
View:
```
<button type="submit" class="externalLoginService socialLoginButton @p.AuthenticationType.ToLower()" id="@p.AuthenticationType" name="provider" value="@p.AuthenticationType" title="Log in with @p.Caption">@p.AuthenticationType</button>
```
Using classes instead of the not so elegant style attribute in the other solution/answer above.
|
You can still do something similar, basically in Startup.Auth.cs you will need to add extra data to the AuthenticationDescription when you enable the auth provider:
```
var desc = new AuthenticationDescription();
desc.Caption = "Google";
desc.AuthenticationType = "Google";
desc.Properties["Img"] = "<img>";
app.UseGoogleAuthentication(new GoogleAuthenticationOptions() { Description = desc });
```
And then use the @p.Properties["Img"] in your button like you were doing before inside of the \_ExternalLoginListPartial view
```
<legend>Use another service to log in.</legend>
<p>
@foreach (AuthenticationDescription p in loginProviders) {
<button type="submit" class="btn" id="@p.AuthenticationType" name="provider" value="@p.AuthenticationType" title="Log in using your @p.Caption account">@p.AuthenticationType</button>
}
</p>
```
|
4,781,379
|
**Sql query:**
**select \* from test\_mart
where replace(replace(replace(replace(replace(replace(lower(name),'+'),'\_'),'the '),' the'),'a '),' a')='tariq'**
I can fire following query very easy, if I have to use simply Sqlite... but In current project I am using Core Data so not familiar about NSPredicate much.
The functionality talks about removing all BUT alphanumeric characters, which means removing special characters.
The characters that should be valid in the comparison would be
ABCDEFGHIJKLMNOPQRESTUVWXYZ1234567890
But we should not fail the comparison for the following characters
:;,~`!@#$%^&\*()\_-+="'/?.>,<|\
Or for the following words
'the' 'an' 'a'
Some examples:
1. 'Walmart' would be seen as the same payee as 'Wal-Mart'
2. 'The Shoe Store' would be seen as the same payee as 'Shoe Store'
3. 'Domino's Pizza' would be seen as the same payee as 'Dominos Pizza'
4. 'Test Payee;' would be seen as the same payee as 'Test Payee'
Can any one suggest appropriate Predicates/Regular Expression ?
Thanks
|
2011/01/24
|
[
"https://Stackoverflow.com/questions/4781379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/213532/"
] |
Setting the locale to a specific value chosen by the programmer in order to process a particular character set is incorrect usage. Not only are locale names implementation-specific; they're also intended to reflect the user's or system's character encoding.
If you need to programmatically process a particular character encoding, the `iconv` interface exists for this purpose. Use `iconv_open("WCHAR_T", "GB18030");` to obtain a conversion descriptor, and convert a couple kb at a time into a throwaway buffer on the stack, summing up the number of output characters obtained from each run.
|
Your line:
```
if (setlocale(LC_ALL, "") == 0)
```
will reset the LOCALE to the values set in environment variables, so maybe not the chinese character set anymore. Try to remove it or check environment variables values.
|
160,497
|
This program uses the C language. What's used are two points, and the usage of the inverse tan function finds the angle of the line between the two points. Afterward, it finds the cardinal direction on the plane. -y is south, +y is north. It seems to work quite well. However, I want to find what is unconventional of my program. I want to learn to write good code and this is a good step towards it.
```
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265
int cardinal(double degrees)
{
// 0 is North
// 1 is North-east
// 2 is East
// 3 is South-east
// 4 is South
// 5 is South-west
// 6 is West
// 7 is North-west
int cardinal;
if (degrees >= -22.5 && degrees <= 22.5)
cardinal = 0;
if (degrees > 22.5 && degrees < 67.5)
cardinal = 1;
if (degrees >= 67.5 && degrees <= 112.5)
cardinal = 2;
if (degrees > 112.5 && degrees < 157.5)
cardinal = 3;
if (degrees >= -157.5 && degrees <= 157.5)
cardinal = 4;
if (degrees > -157.5 && degrees < -112.5)
cardinal = 5;
if (degrees >= -112.5 && degrees <= -67.5)
cardinal = 6;
if (degrees > -67.5 && degrees < -22.5)
cardinal = 7;
return cardinal;
}
char* direction(int cardinal)
{
if (cardinal == 0)
return "north";
if (cardinal == 1)
return "northeast";
if (cardinal == 2)
return "east";
if (cardinal == 3)
return "southeast";
if (cardinal == 4)
return "south";
if (cardinal == 5)
return "southwest";
if (cardinal == 6)
return "west";
if (cardinal == 7)
return "northwest";
}
int main()
{
int xpl = 494, ypl = 105;
int xcom = 152, ycom = -168;
double degrees;
double radians;
int num;
double CONS = 180.0 / PI;
int xo = xcom - xpl;
int yo = ycom - ypl;
radians = atan2(yo, xo);
degrees = radians * CONS;
num = cardinal(degrees);
printf("The angle to travel in is %f (degrees) %f (radians)\n", degrees, radians);
printf("Numerical direction: %d", num);
printf("\nDirection: %s", direction(num));
return 0;
}
```
|
2017/04/12
|
[
"https://codereview.stackexchange.com/questions/160497",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/111228/"
] |
Two suggestions:
1. in the `cardinal` function, return the number rather than setting a variable, so you shortcut all the other `if` statements. You could further optimize that by doing a binary rather than a linear search.
2. your `direction` function could be replaced by an array: `int directions[8] = {"north", "northeast", ... };`. Then the lookup is simply `directions[cardinal]`
|
### Bug #1
Your program doesn't give the correct answer because `atan2()` returns 0 to mean "east" but your program interprets 0 to mean "north". You need to adjust your `cardinal()` function to match the meaning of `atan2()`'s return value..
### Bug #2
Your `cardinal()` function has an additional bug in that it doesn't handle angles greater than 157.5 or less than -157.5 correctly. In other words, your function will never return "south" (which actually would be "west" after you fix the first bug). Your logic for that case is actually reverse of what it should be.
|
160,497
|
This program uses the C language. What's used are two points, and the usage of the inverse tan function finds the angle of the line between the two points. Afterward, it finds the cardinal direction on the plane. -y is south, +y is north. It seems to work quite well. However, I want to find what is unconventional of my program. I want to learn to write good code and this is a good step towards it.
```
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265
int cardinal(double degrees)
{
// 0 is North
// 1 is North-east
// 2 is East
// 3 is South-east
// 4 is South
// 5 is South-west
// 6 is West
// 7 is North-west
int cardinal;
if (degrees >= -22.5 && degrees <= 22.5)
cardinal = 0;
if (degrees > 22.5 && degrees < 67.5)
cardinal = 1;
if (degrees >= 67.5 && degrees <= 112.5)
cardinal = 2;
if (degrees > 112.5 && degrees < 157.5)
cardinal = 3;
if (degrees >= -157.5 && degrees <= 157.5)
cardinal = 4;
if (degrees > -157.5 && degrees < -112.5)
cardinal = 5;
if (degrees >= -112.5 && degrees <= -67.5)
cardinal = 6;
if (degrees > -67.5 && degrees < -22.5)
cardinal = 7;
return cardinal;
}
char* direction(int cardinal)
{
if (cardinal == 0)
return "north";
if (cardinal == 1)
return "northeast";
if (cardinal == 2)
return "east";
if (cardinal == 3)
return "southeast";
if (cardinal == 4)
return "south";
if (cardinal == 5)
return "southwest";
if (cardinal == 6)
return "west";
if (cardinal == 7)
return "northwest";
}
int main()
{
int xpl = 494, ypl = 105;
int xcom = 152, ycom = -168;
double degrees;
double radians;
int num;
double CONS = 180.0 / PI;
int xo = xcom - xpl;
int yo = ycom - ypl;
radians = atan2(yo, xo);
degrees = radians * CONS;
num = cardinal(degrees);
printf("The angle to travel in is %f (degrees) %f (radians)\n", degrees, radians);
printf("Numerical direction: %d", num);
printf("\nDirection: %s", direction(num));
return 0;
}
```
|
2017/04/12
|
[
"https://codereview.stackexchange.com/questions/160497",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/111228/"
] |
Two suggestions:
1. in the `cardinal` function, return the number rather than setting a variable, so you shortcut all the other `if` statements. You could further optimize that by doing a binary rather than a linear search.
2. your `direction` function could be replaced by an array: `int directions[8] = {"north", "northeast", ... };`. Then the lookup is simply `directions[cardinal]`
|
Code needs more robust testing. Some mods to create easier testing are below. With such testing, the **functional error** would be readily noticed. Not so surprisingly, test code can be harder and longer to write than the code-under-test.
```
void mainxy(int xo, int yo) {
double CONS = 180.0 / PI;
double radians = atan2(yo, xo);
double degrees = radians * CONS;
int num = cardinal(degrees);
printf("Angle is %11f (degrees) %9f (radians) ", degrees, radians);
printf("Numerical dir.: %2d ", num);
printf("Dir.: %s\n", direction(num));
}
int main() {
for (double degrees = -360.0; degrees < 361.0; degrees += 360.0 / 8) {
mainxy(100 * cos(degrees * PI / 360), 100 * sin(degrees * PI / 360));
}
}
```
Output
```
Angle is 180.000000 (degrees) 3.141593 (radians) Numerical dir.: 0 Dir.: north
Angle is -157.557247 (degrees) -2.749893 (radians) Numerical dir.: 0 Dir.: north
Angle is -135.000000 (degrees) -2.356194 (radians) Numerical dir.: 5 Dir.: southwest
Angle is -112.442753 (degrees) -1.962496 (radians) Numerical dir.: 6 Dir.: west
Angle is -90.000000 (degrees) -1.570796 (radians) Numerical dir.: 6 Dir.: west
Angle is -67.557247 (degrees) -1.179096 (radians) Numerical dir.: 6 Dir.: west
Angle is -45.000000 (degrees) -0.785398 (radians) Numerical dir.: 7 Dir.: northwest
Angle is -22.442753 (degrees) -0.391700 (radians) Numerical dir.: 4 Dir.: south
Angle is 0.000000 (degrees) 0.000000 (radians) Numerical dir.: 4 Dir.: south
Angle is 22.442753 (degrees) 0.391700 (radians) Numerical dir.: 4 Dir.: south
Angle is 45.000000 (degrees) 0.785398 (radians) Numerical dir.: 4 Dir.: south
Angle is 67.557247 (degrees) 1.179096 (radians) Numerical dir.: 4 Dir.: south
Angle is 90.000000 (degrees) 1.570796 (radians) Numerical dir.: 4 Dir.: south
Angle is 112.442753 (degrees) 1.962496 (radians) Numerical dir.: 4 Dir.: south
Angle is 135.000000 (degrees) 2.356194 (radians) Numerical dir.: 4 Dir.: south
Angle is 157.557247 (degrees) 2.749893 (radians) Numerical dir.: 0 Dir.: north
Angle is 180.000000 (degrees) 3.141593 (radians) Numerical dir.: 0 Dir.: north
```
---
No need to code `PI` to some approximation that might or might not be the best for an implementation when a one-time calculation can solve that.
```
// double CONS = 180.0 / PI;
double CONS = 180.0/acos(-1.0);
```
|
160,497
|
This program uses the C language. What's used are two points, and the usage of the inverse tan function finds the angle of the line between the two points. Afterward, it finds the cardinal direction on the plane. -y is south, +y is north. It seems to work quite well. However, I want to find what is unconventional of my program. I want to learn to write good code and this is a good step towards it.
```
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265
int cardinal(double degrees)
{
// 0 is North
// 1 is North-east
// 2 is East
// 3 is South-east
// 4 is South
// 5 is South-west
// 6 is West
// 7 is North-west
int cardinal;
if (degrees >= -22.5 && degrees <= 22.5)
cardinal = 0;
if (degrees > 22.5 && degrees < 67.5)
cardinal = 1;
if (degrees >= 67.5 && degrees <= 112.5)
cardinal = 2;
if (degrees > 112.5 && degrees < 157.5)
cardinal = 3;
if (degrees >= -157.5 && degrees <= 157.5)
cardinal = 4;
if (degrees > -157.5 && degrees < -112.5)
cardinal = 5;
if (degrees >= -112.5 && degrees <= -67.5)
cardinal = 6;
if (degrees > -67.5 && degrees < -22.5)
cardinal = 7;
return cardinal;
}
char* direction(int cardinal)
{
if (cardinal == 0)
return "north";
if (cardinal == 1)
return "northeast";
if (cardinal == 2)
return "east";
if (cardinal == 3)
return "southeast";
if (cardinal == 4)
return "south";
if (cardinal == 5)
return "southwest";
if (cardinal == 6)
return "west";
if (cardinal == 7)
return "northwest";
}
int main()
{
int xpl = 494, ypl = 105;
int xcom = 152, ycom = -168;
double degrees;
double radians;
int num;
double CONS = 180.0 / PI;
int xo = xcom - xpl;
int yo = ycom - ypl;
radians = atan2(yo, xo);
degrees = radians * CONS;
num = cardinal(degrees);
printf("The angle to travel in is %f (degrees) %f (radians)\n", degrees, radians);
printf("Numerical direction: %d", num);
printf("\nDirection: %s", direction(num));
return 0;
}
```
|
2017/04/12
|
[
"https://codereview.stackexchange.com/questions/160497",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/111228/"
] |
Your implementation misses a few things when coming to good coding practices, but let us first restate your goal: *Calculate a degree based on line coordinates. Return a cardinal number evenly **dividing** the circle, and/or return a text related to the cardinal number.*
Code review
-----------
* *OK structure* – The structure of your program is OK, and it easy enough to read.
* *Enclose blocks in braces* – I'm not a fan of *not* enclosing the `if` block in braces. Your indentation is good, and they are single statements so it is legal, but still this will lead to an error somewhere along the road. Please enclose `if` blocks in braces.
* *Degree calculation not a function?* – Why haven't you made the actual calculation into a function? Wouldn't it be natural to have a `double line2degree(x1, y1, x2, y2)` function in your program?
* *Use correct return types* – Your `direction()` function returns `char *`, which I read as a char pointer to something I can change. What will happen if you start changing it? Use `const char *` to properly announce this is a constant string.
* *"Wrong" declaration of `main()`* - Please use a more standard version for declaring your `main` function, like `int main(int argc, char** argv)`. Even though you don't use it right now, it's better practice to do this.
* *Strip down `main()` to the bare minimum* – In my opinion it should only contain some argument checks (if needed), and then call of other functions. This will make it easier later on to extend your program either as a standalone program, or as part of a library, and so on.
* *No error checking* – You don't check that the `degrees` are within the expected range of -180 to 180. You don't check that `cardinal` is between 0 and 7. Both cases leading to unexpected results, or no results.
* *Use of magic numbers* – In general to sprinkle bare constants all over your code is not considered good practices. This both applies to the degrees in `cardinal()`, and the actual `cardinal` number (0-7). What if you want to change it to another range? Like 0-15? Or 0-9?. In general it would be better to declare these as constants, like you did for `PI`, and use the constants in your program. Or find a way to avoid using the specific numbers overall.
* *Extensive use of multiple `if` statements* – Whenever you find yourself writing more than a few `if` statements back to back, you need to reconsider whether there are better ways of tackling the issue.
Code refactor
-------------
Here are some ideas for refactoring your code.
* *Add `line2degree()`* – This seems like a natural extension to your code
* *Do error checking!* – Either normalize the input values to be within your expected range, or do some error handling when input values are outside of the range
* *Calculate the cardinal number* – What would happen if you did `(degrees + 180.0 + 22.5)/ 45`? You can rather easily calculate the cardinal number by recognising that you've divided the circle into even 45 degree parts. This would also restrain the need of constants. Now you could have `DEGREE_OFFSET = 202.5` and `DIVIDING_ANGLE = 45`. Probably you could do the calculation in `int`'s also.
* *Use an array for the `direction` texts* – As suggested in another post, you could easily return the cardinal text from an array (after checking array boundaries).
* **New feature:** *Extend the main to allow for entering new inputs* – If you look into it, you could rather easily allow for the new coordinates to be entered on the command line, making it easier to test multiple conditions.
I don't have time to code this, but I hope you get the gist of it, and come back with another version in a little while!
|
### Bug #1
Your program doesn't give the correct answer because `atan2()` returns 0 to mean "east" but your program interprets 0 to mean "north". You need to adjust your `cardinal()` function to match the meaning of `atan2()`'s return value..
### Bug #2
Your `cardinal()` function has an additional bug in that it doesn't handle angles greater than 157.5 or less than -157.5 correctly. In other words, your function will never return "south" (which actually would be "west" after you fix the first bug). Your logic for that case is actually reverse of what it should be.
|
160,497
|
This program uses the C language. What's used are two points, and the usage of the inverse tan function finds the angle of the line between the two points. Afterward, it finds the cardinal direction on the plane. -y is south, +y is north. It seems to work quite well. However, I want to find what is unconventional of my program. I want to learn to write good code and this is a good step towards it.
```
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265
int cardinal(double degrees)
{
// 0 is North
// 1 is North-east
// 2 is East
// 3 is South-east
// 4 is South
// 5 is South-west
// 6 is West
// 7 is North-west
int cardinal;
if (degrees >= -22.5 && degrees <= 22.5)
cardinal = 0;
if (degrees > 22.5 && degrees < 67.5)
cardinal = 1;
if (degrees >= 67.5 && degrees <= 112.5)
cardinal = 2;
if (degrees > 112.5 && degrees < 157.5)
cardinal = 3;
if (degrees >= -157.5 && degrees <= 157.5)
cardinal = 4;
if (degrees > -157.5 && degrees < -112.5)
cardinal = 5;
if (degrees >= -112.5 && degrees <= -67.5)
cardinal = 6;
if (degrees > -67.5 && degrees < -22.5)
cardinal = 7;
return cardinal;
}
char* direction(int cardinal)
{
if (cardinal == 0)
return "north";
if (cardinal == 1)
return "northeast";
if (cardinal == 2)
return "east";
if (cardinal == 3)
return "southeast";
if (cardinal == 4)
return "south";
if (cardinal == 5)
return "southwest";
if (cardinal == 6)
return "west";
if (cardinal == 7)
return "northwest";
}
int main()
{
int xpl = 494, ypl = 105;
int xcom = 152, ycom = -168;
double degrees;
double radians;
int num;
double CONS = 180.0 / PI;
int xo = xcom - xpl;
int yo = ycom - ypl;
radians = atan2(yo, xo);
degrees = radians * CONS;
num = cardinal(degrees);
printf("The angle to travel in is %f (degrees) %f (radians)\n", degrees, radians);
printf("Numerical direction: %d", num);
printf("\nDirection: %s", direction(num));
return 0;
}
```
|
2017/04/12
|
[
"https://codereview.stackexchange.com/questions/160497",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/111228/"
] |
Your implementation misses a few things when coming to good coding practices, but let us first restate your goal: *Calculate a degree based on line coordinates. Return a cardinal number evenly **dividing** the circle, and/or return a text related to the cardinal number.*
Code review
-----------
* *OK structure* – The structure of your program is OK, and it easy enough to read.
* *Enclose blocks in braces* – I'm not a fan of *not* enclosing the `if` block in braces. Your indentation is good, and they are single statements so it is legal, but still this will lead to an error somewhere along the road. Please enclose `if` blocks in braces.
* *Degree calculation not a function?* – Why haven't you made the actual calculation into a function? Wouldn't it be natural to have a `double line2degree(x1, y1, x2, y2)` function in your program?
* *Use correct return types* – Your `direction()` function returns `char *`, which I read as a char pointer to something I can change. What will happen if you start changing it? Use `const char *` to properly announce this is a constant string.
* *"Wrong" declaration of `main()`* - Please use a more standard version for declaring your `main` function, like `int main(int argc, char** argv)`. Even though you don't use it right now, it's better practice to do this.
* *Strip down `main()` to the bare minimum* – In my opinion it should only contain some argument checks (if needed), and then call of other functions. This will make it easier later on to extend your program either as a standalone program, or as part of a library, and so on.
* *No error checking* – You don't check that the `degrees` are within the expected range of -180 to 180. You don't check that `cardinal` is between 0 and 7. Both cases leading to unexpected results, or no results.
* *Use of magic numbers* – In general to sprinkle bare constants all over your code is not considered good practices. This both applies to the degrees in `cardinal()`, and the actual `cardinal` number (0-7). What if you want to change it to another range? Like 0-15? Or 0-9?. In general it would be better to declare these as constants, like you did for `PI`, and use the constants in your program. Or find a way to avoid using the specific numbers overall.
* *Extensive use of multiple `if` statements* – Whenever you find yourself writing more than a few `if` statements back to back, you need to reconsider whether there are better ways of tackling the issue.
Code refactor
-------------
Here are some ideas for refactoring your code.
* *Add `line2degree()`* – This seems like a natural extension to your code
* *Do error checking!* – Either normalize the input values to be within your expected range, or do some error handling when input values are outside of the range
* *Calculate the cardinal number* – What would happen if you did `(degrees + 180.0 + 22.5)/ 45`? You can rather easily calculate the cardinal number by recognising that you've divided the circle into even 45 degree parts. This would also restrain the need of constants. Now you could have `DEGREE_OFFSET = 202.5` and `DIVIDING_ANGLE = 45`. Probably you could do the calculation in `int`'s also.
* *Use an array for the `direction` texts* – As suggested in another post, you could easily return the cardinal text from an array (after checking array boundaries).
* **New feature:** *Extend the main to allow for entering new inputs* – If you look into it, you could rather easily allow for the new coordinates to be entered on the command line, making it easier to test multiple conditions.
I don't have time to code this, but I hope you get the gist of it, and come back with another version in a little while!
|
Code needs more robust testing. Some mods to create easier testing are below. With such testing, the **functional error** would be readily noticed. Not so surprisingly, test code can be harder and longer to write than the code-under-test.
```
void mainxy(int xo, int yo) {
double CONS = 180.0 / PI;
double radians = atan2(yo, xo);
double degrees = radians * CONS;
int num = cardinal(degrees);
printf("Angle is %11f (degrees) %9f (radians) ", degrees, radians);
printf("Numerical dir.: %2d ", num);
printf("Dir.: %s\n", direction(num));
}
int main() {
for (double degrees = -360.0; degrees < 361.0; degrees += 360.0 / 8) {
mainxy(100 * cos(degrees * PI / 360), 100 * sin(degrees * PI / 360));
}
}
```
Output
```
Angle is 180.000000 (degrees) 3.141593 (radians) Numerical dir.: 0 Dir.: north
Angle is -157.557247 (degrees) -2.749893 (radians) Numerical dir.: 0 Dir.: north
Angle is -135.000000 (degrees) -2.356194 (radians) Numerical dir.: 5 Dir.: southwest
Angle is -112.442753 (degrees) -1.962496 (radians) Numerical dir.: 6 Dir.: west
Angle is -90.000000 (degrees) -1.570796 (radians) Numerical dir.: 6 Dir.: west
Angle is -67.557247 (degrees) -1.179096 (radians) Numerical dir.: 6 Dir.: west
Angle is -45.000000 (degrees) -0.785398 (radians) Numerical dir.: 7 Dir.: northwest
Angle is -22.442753 (degrees) -0.391700 (radians) Numerical dir.: 4 Dir.: south
Angle is 0.000000 (degrees) 0.000000 (radians) Numerical dir.: 4 Dir.: south
Angle is 22.442753 (degrees) 0.391700 (radians) Numerical dir.: 4 Dir.: south
Angle is 45.000000 (degrees) 0.785398 (radians) Numerical dir.: 4 Dir.: south
Angle is 67.557247 (degrees) 1.179096 (radians) Numerical dir.: 4 Dir.: south
Angle is 90.000000 (degrees) 1.570796 (radians) Numerical dir.: 4 Dir.: south
Angle is 112.442753 (degrees) 1.962496 (radians) Numerical dir.: 4 Dir.: south
Angle is 135.000000 (degrees) 2.356194 (radians) Numerical dir.: 4 Dir.: south
Angle is 157.557247 (degrees) 2.749893 (radians) Numerical dir.: 0 Dir.: north
Angle is 180.000000 (degrees) 3.141593 (radians) Numerical dir.: 0 Dir.: north
```
---
No need to code `PI` to some approximation that might or might not be the best for an implementation when a one-time calculation can solve that.
```
// double CONS = 180.0 / PI;
double CONS = 180.0/acos(-1.0);
```
|
25,015,298
|
I have a table in Excel that looks something like this:
```
Stores 2010 2011 2012
---------------------------------------------
Store1 20000 30000 25000
Store2 60000 45000 50000
...
Store50 80000 41000 60000
```
I want to be able to create an icon set so that it will display an arrow pointing up, down or horizontal compared to its previous year. I've tried conditional formatting but it seems that it can't use relative cells.
So for example the above table would look something like:
```
Stores 2010 2011 2012
---------------------------------------------
Store1 20000 ^ 30000 v 25000
Store2 60000 v 45000 ^ 50000
...
Store50 80000 v 41000 ^ 60000
```
I found out that if i make a new conditional format for each cell I need it can be done, but with over 150 rows it would be nice to just create one format, and copy it to the other cells.
Can this be done?
|
2014/07/29
|
[
"https://Stackoverflow.com/questions/25015298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1732377/"
] |
I would suggest creating a new column and putting the % change from the previous to more recent year. Then do the conditional formatting on that row.
Is that an acceptable solution?
**EDIT** Screenshot below showing icon column can be narrowed to not show % change value.

|
If the problem is with adding columns into a PT this could be overcome by adding calculated items for the changes, provided the data is 'flattened' first, but may involve a lot of formatting also:

The calculated items are of formula type:
```
='2011'/'2010'-1
```
to return positive, negative or zero values that can then be formatted:
```
[Green]"ñ";[Red]"ò";[Yellow]"ó"
```
with Bold Windings font.
The results appear unstable and may need to be reapplied on PT refresh.
|
16,809,529
|
I have window with some divs that are draggable. I also have a second window that I created with `window.open()` that has divs that are draggable. Is it possible now to drag a div from one window to the other?
Thanks
|
2013/05/29
|
[
"https://Stackoverflow.com/questions/16809529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008834/"
] |
Take a look at this [tutorial](http://www.html5rocks.com/en/tutorials/dnd/basics/) for the DnD part.
To achieve this, it's possible to pass a temp value that both sending and receiving window can read. It could be a cookie, or a better idea could be to use localStorage if it's available, as some people voluntarily block cookies for more privacy.
Using the [Modernizr](http://modernizr.com/)'s fallback test, it could goes like this:
```
if (Modernizr.draganddrop) {
// add drag and drop support
} else {
// custom drag and drop support or suggest the user to get a real browser (if possible)
}
```
Whenever a drag is started :
```
if (Modernizr.localstorage) {
window.localStorage['item_1_drag_started'] = true;
} else {
document.cookie = "item_1_drag_started=1";
}
```
Then, when drag is over / mouse is up :
```
if (Modernizr.localstorage) {
delete window.localStorage['item_1_drag_started'];
} else {
document.cookie = "item_1_drag_started=0";
}
```
Now, when the mouse enters the other window, you may check if the item was still being dragged by accessing localStorage (or the dirty cookie if it's unavailable).
The only issue I can think of is when the user releases the mouse button while between those windows. That could be a problem, since the item will be considered dragging but you can't release a button that isn't pressed. Does anyone know about a trick to check if the mouse button is still pressed when entering a window even if it doesn't fired the event ?
In the meantime, the click event in the receiving window could simply check if it's still dragging then drop the item and remove the flag.
---
**UPDATE**: Concerning the mentionned issue, after digging a little and doing some test with events it seems that neither `mouseover` or `mousemove` is fired when a mouse button is still pressed (at least in Chrome where my tests have been made).
With that in mind, I think that the best approach to Drag and Drop between two windows is to *toggle* it:
```
Click --> Drag is started
Click again --> Drop the item
```
|
I guess you could set a variable "drag item = true" and store the item content somewhere. Then drop it on the mouse up in your popup.
|
16,809,529
|
I have window with some divs that are draggable. I also have a second window that I created with `window.open()` that has divs that are draggable. Is it possible now to drag a div from one window to the other?
Thanks
|
2013/05/29
|
[
"https://Stackoverflow.com/questions/16809529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008834/"
] |
From the answers provided I can see now that dragging between windows is really ugly. You have to basically transfer the mouse state from one window to the other and inject the element being dragged into the DOM of the destination window. I was hoping there was some jQuery around that you could run in both windows that would smooth all that over, but I guess not. I just won't do the drag in this project. I can just allow the user to click an element in the second window and have it appear immediately in the first window. Good enough. Thanks for looking at the question.
|
I guess you could set a variable "drag item = true" and store the item content somewhere. Then drop it on the mouse up in your popup.
|
16,809,529
|
I have window with some divs that are draggable. I also have a second window that I created with `window.open()` that has divs that are draggable. Is it possible now to drag a div from one window to the other?
Thanks
|
2013/05/29
|
[
"https://Stackoverflow.com/questions/16809529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008834/"
] |
Take a look at this [tutorial](http://www.html5rocks.com/en/tutorials/dnd/basics/) for the DnD part.
To achieve this, it's possible to pass a temp value that both sending and receiving window can read. It could be a cookie, or a better idea could be to use localStorage if it's available, as some people voluntarily block cookies for more privacy.
Using the [Modernizr](http://modernizr.com/)'s fallback test, it could goes like this:
```
if (Modernizr.draganddrop) {
// add drag and drop support
} else {
// custom drag and drop support or suggest the user to get a real browser (if possible)
}
```
Whenever a drag is started :
```
if (Modernizr.localstorage) {
window.localStorage['item_1_drag_started'] = true;
} else {
document.cookie = "item_1_drag_started=1";
}
```
Then, when drag is over / mouse is up :
```
if (Modernizr.localstorage) {
delete window.localStorage['item_1_drag_started'];
} else {
document.cookie = "item_1_drag_started=0";
}
```
Now, when the mouse enters the other window, you may check if the item was still being dragged by accessing localStorage (or the dirty cookie if it's unavailable).
The only issue I can think of is when the user releases the mouse button while between those windows. That could be a problem, since the item will be considered dragging but you can't release a button that isn't pressed. Does anyone know about a trick to check if the mouse button is still pressed when entering a window even if it doesn't fired the event ?
In the meantime, the click event in the receiving window could simply check if it's still dragging then drop the item and remove the flag.
---
**UPDATE**: Concerning the mentionned issue, after digging a little and doing some test with events it seems that neither `mouseover` or `mousemove` is fired when a mouse button is still pressed (at least in Chrome where my tests have been made).
With that in mind, I think that the best approach to Drag and Drop between two windows is to *toggle* it:
```
Click --> Drag is started
Click again --> Drop the item
```
|
What you could do is on drag being, set a cookie and on mouse over the target window, check for the cookie and *simulate* the drag.
|
16,809,529
|
I have window with some divs that are draggable. I also have a second window that I created with `window.open()` that has divs that are draggable. Is it possible now to drag a div from one window to the other?
Thanks
|
2013/05/29
|
[
"https://Stackoverflow.com/questions/16809529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008834/"
] |
From the answers provided I can see now that dragging between windows is really ugly. You have to basically transfer the mouse state from one window to the other and inject the element being dragged into the DOM of the destination window. I was hoping there was some jQuery around that you could run in both windows that would smooth all that over, but I guess not. I just won't do the drag in this project. I can just allow the user to click an element in the second window and have it appear immediately in the first window. Good enough. Thanks for looking at the question.
|
What you could do is on drag being, set a cookie and on mouse over the target window, check for the cookie and *simulate* the drag.
|
16,809,529
|
I have window with some divs that are draggable. I also have a second window that I created with `window.open()` that has divs that are draggable. Is it possible now to drag a div from one window to the other?
Thanks
|
2013/05/29
|
[
"https://Stackoverflow.com/questions/16809529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008834/"
] |
Take a look at this [tutorial](http://www.html5rocks.com/en/tutorials/dnd/basics/) for the DnD part.
To achieve this, it's possible to pass a temp value that both sending and receiving window can read. It could be a cookie, or a better idea could be to use localStorage if it's available, as some people voluntarily block cookies for more privacy.
Using the [Modernizr](http://modernizr.com/)'s fallback test, it could goes like this:
```
if (Modernizr.draganddrop) {
// add drag and drop support
} else {
// custom drag and drop support or suggest the user to get a real browser (if possible)
}
```
Whenever a drag is started :
```
if (Modernizr.localstorage) {
window.localStorage['item_1_drag_started'] = true;
} else {
document.cookie = "item_1_drag_started=1";
}
```
Then, when drag is over / mouse is up :
```
if (Modernizr.localstorage) {
delete window.localStorage['item_1_drag_started'];
} else {
document.cookie = "item_1_drag_started=0";
}
```
Now, when the mouse enters the other window, you may check if the item was still being dragged by accessing localStorage (or the dirty cookie if it's unavailable).
The only issue I can think of is when the user releases the mouse button while between those windows. That could be a problem, since the item will be considered dragging but you can't release a button that isn't pressed. Does anyone know about a trick to check if the mouse button is still pressed when entering a window even if it doesn't fired the event ?
In the meantime, the click event in the receiving window could simply check if it's still dragging then drop the item and remove the flag.
---
**UPDATE**: Concerning the mentionned issue, after digging a little and doing some test with events it seems that neither `mouseover` or `mousemove` is fired when a mouse button is still pressed (at least in Chrome where my tests have been made).
With that in mind, I think that the best approach to Drag and Drop between two windows is to *toggle* it:
```
Click --> Drag is started
Click again --> Drop the item
```
|
From the answers provided I can see now that dragging between windows is really ugly. You have to basically transfer the mouse state from one window to the other and inject the element being dragged into the DOM of the destination window. I was hoping there was some jQuery around that you could run in both windows that would smooth all that over, but I guess not. I just won't do the drag in this project. I can just allow the user to click an element in the second window and have it appear immediately in the first window. Good enough. Thanks for looking at the question.
|
324,237
|
Consider the structure of the positive real numbers $(0, \infty) $ with its unit $1$, its addition $+$, its multiplication $\times $, and its strict ordering $> $.
Is this structure
$$( (0, \infty), 1, +, \times, >) $$
o-minimal?
|
2019/02/27
|
[
"https://mathoverflow.net/questions/324237",
"https://mathoverflow.net",
"https://mathoverflow.net/users/136356/"
] |
Another way to see o-minimality is to note that $log$ induces an isomorphism
$$log : ((0,\infty), 1, +, \times, >) \cong (\mathbb R, 0, \oplus, +, >),$$
where $\oplus$ is the binary operation defined by $\oplus(x,y) = \log(e^x + e^y)$. But $\oplus$ is definable in $\mathbb R\_{exp}$. Hence the latter structure is a reduct of $\mathbb R\_{exp}$ and therefore is o-minimal.
|
Yes. To see this, first note that we can interpret the positive reals in $(\mathbb{R},0,1,+,-,\times)$ as squares of non-zero real numbers. We can by induction on complexity of formulas define a translation map from formulas in the language of the positive reals to formulas in the language of the reals as follows:
* For an atomic formula $\phi(x\_1,\dots x\_k)$ by its translation is $T(\phi)(y\_1, \dots, y\_k) = \phi(y\_1^2, \dots , y\_k^2)$
* $T(\phi \wedge \psi) = T(\phi) \wedge T(\psi)$
* $T(\neg \phi) = \neg T(\phi)$
* $T(\exists x \phi(x)) = \exists y (y \neq 0 \wedge T(\phi)(y^2))$
Then the postive reals model $\phi(c)$ for $c > 0$ if and only the reals models $T(\phi)(\sqrt{c})$, for formulas with a single free variable of arbitrary complexity.
But then using o-minimality of the reals, we know $\{y : T(\phi)(y)\}$ is a finite union of points and intervals, so the same is true of $\{c : \phi(c)\} = \{c : T(\phi)(\sqrt{c})\}$
|
657,505
|
hi so I bought windows 10 and I’m using Ubuntu, and i want to just use windows now and get rid of Ubuntu. I have no clue how to do this or how I can even start, I have the .iso file and I’m ready to start, but like how? I cant just open it, it says I cant, please help asap. keep in mind I’m really bad at the whole Linux thing so please try and clearly go through step by step as if I’m completely new, because I really am, thank-you :) I've tried googling it and i dont understand it at all, i was hoping someone can walk me through it really easy and simple :) also my cd drive doesnt work...
|
2015/08/07
|
[
"https://askubuntu.com/questions/657505",
"https://askubuntu.com",
"https://askubuntu.com/users/437206/"
] |
There seems to be 2 options; 1) Find a way to correct the Grub settings
or 2) Format both SSD drives and start again.
There may actually be some info for the 1st option in the ubuntu docmuentation (community, askubuntu).
If 2nd option is decided upon, I would recommend an old boot disk from Win98 or WinME on a floppy. This would make it possible to use fdisk /mbr which should clear the master boot record (and therefore clear Grub). The drives should then be accessible. When reinstalling, Do Windows install first. Grub seems to set up better when Windows partition already exists.
There is a part of your question that tells of DVD/USB not being accessible.
Double check to see if BIOS 'sees' the optical/usb drives before you start.
There is usually a 'Load BIOS defaults' in saving settings that could correct
normal BIOS 'errors' and return the drives.
Hope this helps and gets you started to fixing this dilemma.
Edit 8/11/15
Another option would be to format from Win 7 disk. Boot from the Win 7
disk and follow setup to a 'fresh' installation. At the time of choosing
the drive for Win 7, do a fresh install in the drive where
current Win 7 installation exists. Be sure to format drive. When install
is completed, boot into new installation and go to disk management where
you should be able to format the ubuntu drive, making empty space
for the ubuntu install. Just be certain that ubuntu installs into
that space and should have no problems. Also be sure that / and swap
partitions are created in the ubuntu install.
Hadn't thought of this at first. Hope this gets you going. Craig
|
yes, you should shoot your laptop and get ASUS G550JX instead. but remember to shoot it with a legal handgun. LOL :P
uhh... actually no. I think you can always start fresh, formatting all your drives and reinstall everything. but remember, there are different installer for Windows OEM, Retail, ....... (forgot the rest, sorry), but you can always modify one of those ISOs. Google is your friend. I reinstalled Windows 8.1 in my ASUS T100 with Windows 8.1 retail DVD and OEM key, after modifying the ei.cfg (if I remember correctly). You should start there. Also before installing, make sure you have all the drivers ready to install. You don't want more headache, do you? You may also want Windows 10, make sure the installer are ready to upgrade as soon as thw Windows 7 installed. Why, you ask? Remember the rules that Windows doesn't give a f\*\*k about another OS in your disk.
After installing Windows, then install Ubuntu. It should auto detect all OSes inside your laptop. You already have experience with that, I think you already know what to do.
Also if the disc still won't boot, try to change your laptop from Legacy BIOS to UEFI, and vice versa. It may help. You didn't specify you got Windows 7 32-bit or 64-bit. the 64-bit ones got EFI.
Hope this helps!
(but seriously, why Ubuntu on ROG? you didn't use it for gaming? why not Steam OS?)
|
61,757,262
|
How to print a plus pattern with 1's inside zeros using numpy array!! I need to satisfy all the cases.I tried below code!!
Code:
```
n = int(input())
import numpy as np
x = np.zeros((n,n), dtype=int)
x[3:4] = 0
x[2:-1,2:3] = x[1:-1,2:3] = x[2:3] = x[0:-1,2:3] = x[4:,2:3]= 1
for i in range(n):
for j in range(n):
print(x[i][j] , end = " ")
print()
```
output:
```
[[0 0 1 0 0]
[0 0 1 0 0]
[1 1 1 1 1]
[0 0 1 0 0]
[0 0 1 0 0]]
```
|
2020/05/12
|
[
"https://Stackoverflow.com/questions/61757262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11737958/"
] |
You could do it with broadcasting using an array where the middle element is 1 (or True):
```
n = int(input("size: "))
import numpy as np
r = np.arange(n)==n//2
r = r*1 | r[:,None]
print(r)
```
output:
```
size: 5
[[0 0 1 0 0]
[0 0 1 0 0]
[1 1 1 1 1]
[0 0 1 0 0]
[0 0 1 0 0]]
```
explanation:
```
r = np.arange(n)==n//2
```
produces an array of True/False where the middle point (indice n//2) is True and all other entries are false:
```
[False, False, True, False, False]
```
If you convert this 1x5 array to a shape of 5x1 using `r[,:None]` you get
```
[[False],
[False],
[ True],
[False],
[False]]
```
Multiplying these True/False values by 1 converts them to numbers and the binary or operator `|` will keep the ones in the middle line and middle column when each row is broadcasted over each column:
```
(OR) 0 0 1 0 0
-----------
0 | 0 0 1 0 0
0 | 0 0 1 0 0
1 | 1 1 1 1 1
0 | 0 0 1 0 0
0 | 0 0 1 0 0
```
Note that there are a multitude of ways to achieve this.
Here's another example:
```
np.max(np.indices((n,n))==n//2,axis=0)*1
```
|
This is another solution where you have a zero array and simply set the middle row and column to 1:
```
n = int(input())
a = np.zeros((n,n)).astype(int)
a[n//2,:]=a[:,n//2]=1
print(a)
[[0 0 1 0 0]
[0 0 1 0 0]
[1 1 1 1 1]
[0 0 1 0 0]
[0 0 1 0 0]]
```
|
61,757,262
|
How to print a plus pattern with 1's inside zeros using numpy array!! I need to satisfy all the cases.I tried below code!!
Code:
```
n = int(input())
import numpy as np
x = np.zeros((n,n), dtype=int)
x[3:4] = 0
x[2:-1,2:3] = x[1:-1,2:3] = x[2:3] = x[0:-1,2:3] = x[4:,2:3]= 1
for i in range(n):
for j in range(n):
print(x[i][j] , end = " ")
print()
```
output:
```
[[0 0 1 0 0]
[0 0 1 0 0]
[1 1 1 1 1]
[0 0 1 0 0]
[0 0 1 0 0]]
```
|
2020/05/12
|
[
"https://Stackoverflow.com/questions/61757262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11737958/"
] |
You could do it with broadcasting using an array where the middle element is 1 (or True):
```
n = int(input("size: "))
import numpy as np
r = np.arange(n)==n//2
r = r*1 | r[:,None]
print(r)
```
output:
```
size: 5
[[0 0 1 0 0]
[0 0 1 0 0]
[1 1 1 1 1]
[0 0 1 0 0]
[0 0 1 0 0]]
```
explanation:
```
r = np.arange(n)==n//2
```
produces an array of True/False where the middle point (indice n//2) is True and all other entries are false:
```
[False, False, True, False, False]
```
If you convert this 1x5 array to a shape of 5x1 using `r[,:None]` you get
```
[[False],
[False],
[ True],
[False],
[False]]
```
Multiplying these True/False values by 1 converts them to numbers and the binary or operator `|` will keep the ones in the middle line and middle column when each row is broadcasted over each column:
```
(OR) 0 0 1 0 0
-----------
0 | 0 0 1 0 0
0 | 0 0 1 0 0
1 | 1 1 1 1 1
0 | 0 0 1 0 0
0 | 0 0 1 0 0
```
Note that there are a multitude of ways to achieve this.
Here's another example:
```
np.max(np.indices((n,n))==n//2,axis=0)*1
```
|
**Assumption is:**
**Input:** Given a single positive odd integer 'n' greater than 2.
Below is the code:
#Read the input
```
n = int(input())
```
#Import the NumPy package
```
import numpy as np
```
#Create an (n x n) array with all zeros
```
arr = np.zeros((n, n), dtype = int)
```
#Make the middle row and middle column all 1s
```
arr[n//2, :] = 1
arr[: , n//2] = 1
```
#Print the final value of arr
```
print(arr)
```
#The Whole Code is Below:
```
n = int(input())
import numpy as np
arr = np.zeros((n, n), dtype = int)
arr[n//2, :] = 1
arr[: , n//2] = 1
print(arr)
```
Sample output for n=3:
```
[[0 1 0]
[1 1 1]
[0 1 0]]
```
Sample output for n=5:
```
[[0 0 1 0 0]
[0 0 1 0 0]
[1 1 1 1 1]
[0 0 1 0 0]
[0 0 1 0 0]]
```
Sample Output for n=7:
```
[[0 0 0 1 0 0 0]
[0 0 0 1 0 0 0]
[0 0 0 1 0 0 0]
[1 1 1 1 1 1 1]
[0 0 0 1 0 0 0]
[0 0 0 1 0 0 0]
[0 0 0 1 0 0 0]]
```
|
61,757,262
|
How to print a plus pattern with 1's inside zeros using numpy array!! I need to satisfy all the cases.I tried below code!!
Code:
```
n = int(input())
import numpy as np
x = np.zeros((n,n), dtype=int)
x[3:4] = 0
x[2:-1,2:3] = x[1:-1,2:3] = x[2:3] = x[0:-1,2:3] = x[4:,2:3]= 1
for i in range(n):
for j in range(n):
print(x[i][j] , end = " ")
print()
```
output:
```
[[0 0 1 0 0]
[0 0 1 0 0]
[1 1 1 1 1]
[0 0 1 0 0]
[0 0 1 0 0]]
```
|
2020/05/12
|
[
"https://Stackoverflow.com/questions/61757262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11737958/"
] |
**Assumption is:**
**Input:** Given a single positive odd integer 'n' greater than 2.
Below is the code:
#Read the input
```
n = int(input())
```
#Import the NumPy package
```
import numpy as np
```
#Create an (n x n) array with all zeros
```
arr = np.zeros((n, n), dtype = int)
```
#Make the middle row and middle column all 1s
```
arr[n//2, :] = 1
arr[: , n//2] = 1
```
#Print the final value of arr
```
print(arr)
```
#The Whole Code is Below:
```
n = int(input())
import numpy as np
arr = np.zeros((n, n), dtype = int)
arr[n//2, :] = 1
arr[: , n//2] = 1
print(arr)
```
Sample output for n=3:
```
[[0 1 0]
[1 1 1]
[0 1 0]]
```
Sample output for n=5:
```
[[0 0 1 0 0]
[0 0 1 0 0]
[1 1 1 1 1]
[0 0 1 0 0]
[0 0 1 0 0]]
```
Sample Output for n=7:
```
[[0 0 0 1 0 0 0]
[0 0 0 1 0 0 0]
[0 0 0 1 0 0 0]
[1 1 1 1 1 1 1]
[0 0 0 1 0 0 0]
[0 0 0 1 0 0 0]
[0 0 0 1 0 0 0]]
```
|
This is another solution where you have a zero array and simply set the middle row and column to 1:
```
n = int(input())
a = np.zeros((n,n)).astype(int)
a[n//2,:]=a[:,n//2]=1
print(a)
[[0 0 1 0 0]
[0 0 1 0 0]
[1 1 1 1 1]
[0 0 1 0 0]
[0 0 1 0 0]]
```
|
5,058
|
So Tridion UI/XPM/SiteEdit default TBBs output a `<span>` tag around each Component Presentation and Field changing the DOM and sometimes conflicting with your site's styles. So a project has been created (<https://github.com/TridionPractice/tridion-practice/wiki/TridionUI2012FunctionsForUseInHtmlTemplates>) that proves these are not necessary. It looks like you can simply print the SiteEdit markup in front of the editable field (btw, very cool).
So why aren't the default functions `@@RenderComponentPresentation(...)@@` and `@@RenderComponentField(...)@@` doing that straight out of the box?
I thought that maybe backwards compatibility could be one reason, but upon second thought this doesn't make sense because if you upgraded you'd still need to swap out your TBBs and republish your pages. So you'd be good to go.
I'm assumming there had to be some other architectural reason(s) why the `<span>` tags were needed and I'm curious what that scenario is.
|
2014/03/29
|
[
"https://tridion.stackexchange.com/questions/5058",
"https://tridion.stackexchange.com",
"https://tridion.stackexchange.com/users/159/"
] |
I was able to solve the problem with Nuno's help and information in another post here.
[Link Resolver with Razor](https://tridion.stackexchange.com/questions/653/link-resolving-with-razor-mediator?rq=1). The fact that in the other post the item was getting resolved with an ID of 0-0-0 made me think it was root in the same issue and it was. The Razor mediator does not publish the binaries. So as part of the TBBs I had to add `Publish Binaries In Package`. Once I did that all was good.
|
I don't have experience with the Razor mediator, but will take a leap of faith and assume it works just like the XSLT or Dreamweaver Mediators...
After your Razor TBB executes you should see in the package (if using Template Builder) that the image was added to the package as a binary item.
You should now add the `Default Finish Actions` to your template, after the Razor TBB, then execute the template again. If you click on the last item in the package (`Output`), you should now see the images displayed in your html.
The `Default Finish Actions` is a "TBB of TBBs", it includes multiple Template Building Blocks that execute different tasks on your template. One TBB will resolve links, another will "Publish Binaries in Package" - this is the one you need. It will basically get the actual binary from the package and translate it to a URL that your template can use.
|
598,741
|
If my map has too many points on it I want my users to zoom in to view fewer points. I'd also like to display other notifications, not sure if I should do this on the map or not, but it would relate directly to the stuff on the map.
Anyone know of an easy way to do this sort of thing?
|
2009/02/28
|
[
"https://Stackoverflow.com/questions/598741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50711/"
] |
A better approach would be to initialize or otherwise inject the DAO with the `SessionFactory`. Then you can do things like this:
```
public abstract class AbstractHibernateDao<T extends Object>
implements AbstractDao<T> {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
public void save(T t) { getSession().save(t); }
public void update(T t) { getSession().update(t); }
...
}
```
without having to pass `Session`s all over the place.
|
No, it should never be used, but a Service layer might. Imagine you have two different methods (in possibly different DAO's) that need to be encapsulated in the same transaction (commit/rollback), than you might want/have to use the same connection object.
|
28,770,298
|
I'm at a bit of a loss on this one. I'm using the AheadWorks blog extension to add event posts for the current calendar year to my page. The extension also creates a feed of these posts, which I am feeding to Google Calendar. It is because of this that I use the dates of the events as the created dates, so they feed correctly to the Google Calendar. However, I can't figure out how to get Magento to display all posts; it only dislpays those with created dates from either the current day or sooner. I understand this is the default; how can I work around it so that all posts regardless of the created\_time show?
I've seen several suggestions about changing the store time, and some that mention editing the created.php file, but I'm really not sure where to begin?
Could someone please give me an idea of what needs to be done?
Here's the app/code/community/AW/Blog/Block/Blog.php:
```
<?php
/**
* aheadWorks Co.
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://ecommerce.aheadworks.com/AW-LICENSE.txt
*
* =================================================================
* MAGENTO EDITION USAGE NOTICE
* =================================================================
* This software is designed to work with Magento community edition and
* its use on an edition other than specified is prohibited. aheadWorks does not
* provide extension support in case of incorrect edition use.
* =================================================================
*
* @category AW
* @package AW_Blog
* @version 1.3.4
* @copyright Copyright (c) 2010-2012 aheadWorks Co. (http://www.aheadworks.com)
* @license http://ecommerce.aheadworks.com/AW-LICENSE.txt
*/
class AW_Blog_Block_Blog extends AW_Blog_Block_Abstract
{
public function getPosts()
{
$collection = parent::_prepareCollection();
$tag = $this->getRequest()->getParam('tag');
if ($tag) {
$collection->addTagFilter(urldecode($tag));
}
parent::_processCollection($collection);
return $collection;
}
protected function _prepareLayout()
{
if ($this->isBlogPage() && ($breadcrumbs = $this->getCrumbs())) {
parent::_prepareMetaData(self::$_helper);
$tag = $this->getRequest()->getParam('tag', false);
if ($tag) {
$tag = urldecode($tag);
$breadcrumbs->addCrumb(
'blog',
array(
'label' => self::$_helper->getTitle(),
'title' => $this->__('Return to ' . self::$_helper- >getTitle()),
'link' => $this->getBlogUrl(),
)
);
$breadcrumbs->addCrumb(
'blog_tag',
array(
'label' => $this->__('Tagged with "%s"', self::$_helper->convertSlashes($tag)),
'title' => $this->__('Tagged with "%s"', $tag),
)
);
} else {
$breadcrumbs->addCrumb('blog', array('label' => self::$_helper->getTitle()));
}
}
}
}
```
Here's the app/design/frontend/[theme]/[theme]/template/aw\_blog/blog.phtml:
```
<?php
/**
* aheadWorks Co.
*
* NOTICE OF LICENSE
*
* This source file is subject to the EULA
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://ecommerce.aheadworks.com/AW-LICENSE.txt
*
* =================================================================
* MAGENTO EDITION USAGE NOTICE
* =================================================================
* This software is designed to work with Magento community edition and
* its use on an edition other than specified is prohibited. aheadWorks does not
* provide extension support in case of incorrect edition use.
* =================================================================
*
* @category AW
* @package AW_Blog
* @version 1.3.4
* @copyright Copyright (c) 2010-2012 aheadWorks Co. (http://www.aheadworks.com)
* @license http://ecommerce.aheadworks.com/AW-LICENSE.txt
*/
?><?php $posts = $this->getPosts(); ?>
<div id="messages_product_view">
<?php Mage::app()->getLayout()->getMessagesBlock()->setMessages(Mage::getSingleton('customer/session')->getMessages(true)); ?>
<?php echo Mage::app()->getLayout()->getMessagesBlock()->getGroupedHtml(); ?>
</div>
<?php echo $this->getChildHtml('aw_blog_comments_toolbar'); ?>
<?php foreach ($posts as $post): ?>
<div class="postWrapper">
<div class="postTitle">
<h2><a href="<?php echo $post->getAddress(); ?>" ><?php echo $post->getTitle(); ?></a></h2>
<h3><?php echo $post->getCreatedTime(); ?></h3>
</div>
<div class="postContent">
<?php echo $post->getPostContent(); ?>
</div>
<?php echo $this->getBookmarkHtml($post) ?>
<div class="tags"><?php echo $this->getTagsHtml($post) ?></div>
<div class="postDetails">
<?php if ($this->getCommentsEnabled()): ?>
<?php echo $post->getCommentCount(); ?> <a href="<?php echo $post->getAddress(); ?>#commentBox" > <?php echo Mage::helper('blog')->__('Comments'); ?></a> |
<?php endif; ?>
<?php $postCats = $post->getCats(); ?>
<?php if (!empty($postCats)): ?>
<?php echo Mage::helper('blog')->__('Posted in'); ?>
<?php foreach ($postCats as $data): ?>
<a href="<?php echo $data['url']; ?>"><?php echo $data['title']; ?></a>
<?php endforeach; ?>
<?php else: ?>
<?php echo Mage::helper('blog')->__('Posted'); ?>
<?php endif; ?><?php echo $this->__("By"); ?> <?php echo $post->getUser(); ?></div>
</div>
<?php endforeach; ?>
<?php echo $this->getChildHtml('aw_blog_comments_toolbar'); ?>
```
|
2015/02/27
|
[
"https://Stackoverflow.com/questions/28770298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2985100/"
] |
You can test if it does the rate limiting changing `5` to a large enough number and adding a display of the timing of `Sys.sleep` using:
```
print(system.time(Sys.sleep(...)))
```
That said, the function seems ok to me, unfortunately I cannot test it easily as rgithub is not available for my version of R (3.1.3).
|
Not a canonical answer, but some working example.
You should add some logging in your script, even kind of `write.csv(append=TRUE)`.
I've implemented automatic *antiddos* process which prevent your ip to be banned by the exchange market. You can find it [jangorecki/Rbitcoin/R/utils.R](https://github.com/jangorecki/Rbitcoin/blob/2f2eeedecc5d4b97c590c48d0ba7aab1b69f0970/R/utils.R#L103).
`Rbitcoin.last_api_call` is env object stored in package namespace, kind of session package cache.
This can help you with setting it in your package.
You should also consider a optional *parallel* supported version. Linking to database with concurrency read. My function can be easy modified to queue call and recheck timing every X seconds.
**Edit**
I forget to add that mentioned function support multiple *source systems*. That allows for example to extend your rgithub for bitbucket, etc. and still effectively manage API rate limiting.
|
48,668
|
I understand the FR of an ideal BPF is just 1 between the two cutoff frequencies and 0 everywhere else above and below them both. But with arbitrary cutoffs, how would one find the IR of this ideal basic filter type?
|
2018/04/20
|
[
"https://dsp.stackexchange.com/questions/48668",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/35247/"
] |
Hint:
\begin{align}
h(t) &= \int\_{-\infty}^\infty H(f)\exp(j2\pi ft)\,\mathrm df\\
&= \int\_{-f\_2}^{-f\_1} H(f)\exp(j2\pi ft)\,\mathrm df + \int\_{f\_1}^{f\_2} H(f)\exp(j2\pi ft)\,\mathrm df\\
&= \int\_{-f\_2}^{-f\_1} \exp(j2\pi ft)\,\mathrm df + \int\_{f\_1}^{f\_2} \exp(j2\pi ft)\,\mathrm df
\end{align}
which you *ought* to be able to compute for yourself. A little algebra and trignometry might be needed to massage the answer into a nice formula involving the sinc function times a cosine.
|
Here's another way to look at Dilip's answer... just wanna get the definitions down.
continuous Fourier transform:
$$ X(f) \triangleq \mathscr{F} \Big\{ x(t) \Big\} \triangleq \int\limits\_{-\infty}^{+\infty} x(t) \, e^{-j 2 \pi f t} \ \mathrm{d}t $$
and inverse:
$$ x(t) \triangleq \mathscr{F}^{-1} \Big\{ X(f) \Big\} = \int\limits\_{-\infty}^{+\infty} X(f) \, e^{+j 2 \pi f t} \ \mathrm{d}f $$
It's not hard to show:
$$ \mathscr{F} \Big\{ \operatorname{rect}(t) \Big\} = \operatorname{sinc}(f) $$
where
$$ \operatorname{rect}(u) \triangleq \begin{cases}
1 \qquad & \mathrm{for} \ |u| < \tfrac12 \\
\tfrac12 \qquad & \mathrm{for} \ |u| = \tfrac12 \\
0 \qquad & \mathrm{for} \ |u| > \tfrac12 \\
\end{cases} $$
and
$$ \operatorname{sinc}(u) \triangleq \begin{cases}
1 \qquad & \mathrm{for} \ u = 0 \\
\frac{\sin(\pi u)}{\pi u} \qquad & \mathrm{for} \ u \ne 0 \\
\end{cases} $$
.
And duality tells us if $X(f) = \mathscr{F} \Big\{ x(t) \Big\}$, then $x(-f) = \mathscr{F} \Big\{ X(t) \Big\}$.
We know, for the ideal LPF
$$ H\_\mathrm{LP}(f) = \operatorname{rect}\left( \tfrac{f}{f\_B} \right) $$
and impulse response
$$ h\_\mathrm{LP}(t) = f\_B\operatorname{sinc}(f\_B \, t) $$
Frequency translation tells us that
$$\begin{align}
\mathscr{F} \Big\{ 2 \cos(2 \pi f\_0 t ) \ h\_\mathrm{LP}(t) \Big\} &= \mathscr{F} \Big\{ \big( e^{j 2 \pi f\_0 t} + e^{-j 2 \pi f\_0 t} \big) \ h\_\mathrm{LP}(t) \Big\} \\
\\
&= H\_\mathrm{LP}(f-f\_0) + H\_\mathrm{LP}(f+f\_0) \\
\\
&= \operatorname{rect}\left( \tfrac{f-f\_0}{f\_B} \right) + \operatorname{rect}\left( \tfrac{f+f\_0}{f\_B} \right) \\
\end{align}$$
Now, with all of those explicit definitions above, can you tell us how $f\_0$ and $f\_B$ relate to Dilip's $f\_1$ and $f\_2$? And then how to specify your ideal BPF in terms of these frequencies?
|
45,745,550
|
I am having trouble added a column that has it's value based on another column in the same data set.
Here is an example of what I am working with:
```
+----+------+------------+
| id | type | date |
+----+------+------------+
| 1 | a | 2017-08-01 |
| 1 | b | 2017-08-05 |
| 2 | a | 2017-08-01 |
| 3 | c | 2017-08-01 |
| 4 | a | 2017-08-02 |
| 5 | a | 2017-08-03 |
| 5 | b | 2017-08-04 |
+----+------+------------+
```
My goal is create a `a_date` column where the date of all applicable rows is that of when the `type` is `a`. Like this:
```
+----+------+------------+------------+
| id | type | date | a_date |
+----+------+------------+------------+
| 1 | a | 2017-08-01 | 2017-08-01 |
| 1 | b | 2017-08-05 | 2017-08-01 |
| 2 | a | 2017-08-01 | 2017-08-01 |
| 3 | c | 2017-08-01 | |
| 4 | a | 2017-08-02 | 2017-08-02 |
| 5 | a | 2017-08-03 | 2017-08-03 |
| 5 | b | 2017-08-04 | 2017-08-03 |
+----+------+------------+------------+
```
Now to do this in R I have created a data table and tried to use a group by and have a temp column I use for the calculation:
```
test <-data.table(id = c(1,1,2,3,4,5,5), type = c("a","b","a","c","a","a","b"),
date = c("2017-08-01", "2017-08-05", "2017-08-01",
"2017-08-01", "2017-08-02", "2017-08-03", "2017-08-04"))
test[type == "a",temp_date := date]
test[, a_date := min(temp_date), by = c("id")]
```
What I end up with is completely different however. I have tried to separate these tables, where I have a table with just `id` and `date` and do a merge like follows:
`test <- merge(test, ids, by.x=id, by.y=id)`
This also yields results which are not desired and not the same length as the initial "test" table. (I have tried the `all.x` option)
The dataset I am actually dealing with is about 20 million rows long and gets our server quite close to its limit just by loading it in, so using a merge or having multiple copies of the table isn't really an option either.
Here is a working version using a for-loop and having a second table:
```
ids <- test[!is.na(temp_date),list(id, temp_date)]
for (i in ids[,id]){
test[id == i, create_date := ids[id == i, temp_date]]
}
```
I can't use this method as I am really constrained for RAM and this table is getting bigger every day. So the goal is to do it using the single data.table.
|
2017/08/17
|
[
"https://Stackoverflow.com/questions/45745550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8099994/"
] |
Create a one way binding from the contentEditable property to a field in your Component, then add an event binding for the click event on the header.
In your component, create a boolean:
```
private isEditable = false;
```
Then, in your html, toggle the value of this boolean with a click event, and bind the `contentEditable` property to this boolean as well:
```
<h1 (dblclick)="isEditable = !isEditable" [contentEditable]="isEditable">
```
You could also put the code of the `(dblclick)` binding inside a method on your component, if you'd rather have some method like `toggleIsEditable()`, with additional logic.
|
What you need is the following.
HTML
====
```
<h4 (dblclick)="contentEditable=true; toto.focus()"
*ngIf="!contentEditable">
{{myText}}
</h4>
<input #toto
autofocus
*ngIf="contentEditable"
[value]="myText"
(keyup.enter)="contentEditable=false; save(toto.value)"
(blur)="contentEditable=false; save(toto.value)"
type="text">
```
TypeScript
==========
```
myText = "Double-click Here to edit";
```
With some css you can get to have one in place of the other.
Here is the [plunker](https://plnkr.co/edit/TtXMORsMxOqsLCqKai2y?p=preview)
|
43,723,988
|
I have 2 forms and 1 file to upload to youtube. I am accessing them like so from both forms (both of the forms don't interact together)
```
await new UploadVideo().Run(video);
```
Now inside my uploadvideo class I am trying to get the percentage uploaded to use in my form
```
void videosInsertRequest_ResponseReceived(Video video)
{
//core.prog_up.Text = "Video id '{0}' was successfully uploaded." + video.Id;
}
```
In both of the forms, I have the exact same form controls, so the naming convention is exactly the same. So depending on which form I initiated the `uploadvideo` class I want the form component to be accessed from the uploadclass.
I have named my forms: `Form1` and `Form2`
I can iniate one by doing :
```
Form1 frm = new Form1();
```
But then I can't access Form2 if I initiate it from that form
|
2017/05/01
|
[
"https://Stackoverflow.com/questions/43723988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5968780/"
] |
>
> depedning on which form I initiate tge uploadvideo class I want the form component to be accessed from the uploadclass
>
>
>
No, not really. You only think you do.
Your `UploadVideo` class should not know *anything* about the `Form` classes. It has no need to, and it's exactly your effort to do otherwise that has led you into this trap. Instead, what you want to do is "decouple" your `UploadVideo` class from the other classes that use it. This avoids these kinds of difficulties and at the same time helps your `UploadVideo` class remain maximally reusable (you can even use it where there's *no* `Form` class involved).
One right way to do this is to implement an event, which each `Form` class can subscribe to as appropriate:
```
class UploadVideo
{
public event EventHandler<string> StatusTextChanged;
void videosInsertRequest_ResponseReceived(Video video)
{
StatusTextChanged?.Invoke(this, $"Video id '{video.Id}' was successfully uploaded.");
}
}
```
NOTE: your original text didn't really make sense. It used a format replacement specifier `{0}`, but didn't pass that to `string.Format()`, instead just appending the `Id` property value to the end of the string. I've changed the text expression to work as one would normally expect it to need to.
If you're not using the latest C# and don't have the "interpolated strings" feature, you can use `string.Format("Video id '{0}' was successfully uploaded.", video.Id)` instead.
Then a `Form` class can subscribe:
```
partial class Form1 : Form
{
async void button1_Click(object sender, EventArgs e)
{
UploadVideo uv = new UploadVideo();
uv.StatusTextChanged += (sender, text) =>
{
Invoke((MethodInvoker)(() => label1.Text = text));
}
await uv.Run(video);
}
}
```
(You didn't offer enough code to know exactly what the expression `core.prog_up` is really supposed to be, so in the above I've just assumed an arbitrary `label1` object that's used to display the text.)
Another alternative is to use the `Progress<T>` class:
```
class UploadVideo
{
private readonly IProgress<string> _progress;
public UploadVideo(IProgress<string> progress)
{
_progress = progress;
}
void videosInsertRequest_ResponseReceived(Video video)
{
_progress.Report($"Video id '{video.Id}' was successfully uploaded.");
}
}
```
and…
```
partial class Form1 : Form
{
async void button1_Click(object sender, EventArgs e)
{
Progress<string> progress = new Progress(s => label1.Text = text);
await new UploadVideo(progress).Run(video);
}
}
```
Note that when using the `Progress<T>` class, there's no need to add the call to `Control.Invoke()` to get back on the UI thread, because it handles that automatically for you.
The above shows passing the `IProgress<T>` instance to the `UploadVideo` constructor, but you could of course pass it to the `Run()` method instead. Either way will work. It just depends on where you need to value.
Yet another approach avoids callbacks altogether. Again, your original code example is pretty vague, so it's not clear whether this would apply in your case. But assuming the callback would be handled just before the `Run()` method returns, and assuming the `video` object passed to the `ResponseReceived` event handler is the same one your code passes to the `Run()` method, then you could just use the completion of the call to the `Run()` method as the indication to update the UI:
```
partial class Form1 : Form
{
async void button1_Click(object sender, EventArgs e)
{
await new UploadVideo().Run(video);
label1.Text = $"Video id '{video.Id}' was successfully uploaded.";
}
}
```
This is a particularly compelling approach, because it removes even the *string literal* from the `UploadVideo` class, putting it into the class that actually is directly involved in interacting with the user (i.e. the only place where a `string` value really matters).
If the above is not enough for you to get back headed in the right direction, you'll need to improve your question by editing it so that it includes a good [Minimal, Complete, and Verifiable code example](https://stackoverflow.com/help/mcve) showing exactly how your scenario works.
|
You can use parameters to pass the reference of form.
```
private Form _frm;
public Form1(Form form)
{
_frm = form;
InitializeComponent();
}
```
And then you can simply call the form like this:
`Form1 frm = new Form1(this)`
|
10,380,051
|
I am trying to send user a activation link through mail by using my gmail account. how do i set it up.How do Send email using Gmail? Where do I put the password?.
Is it to ancient or should I go for object oriented method.
```
// secure the password
$passWord = sha1($passWord);
$repeatPass = sha1($repeatPass);
// generate random number
$random =rand(1200345670,9999999999);
//send activation email
$to = $email;
$subject = "Activate your account";
$headers = "From: ti.asif@gmail.com";
$server = "smtp.gmail.com";
$body = "Hello $username,\n\n You registered and need to activate your account. Click the link below or paste it into the URL bar of your browser\n\nhttp://phpacademy.info/tutorials/emailactivation/activate.php?id=$lastid&code=$code\n\nThanks!";
ini_set("SMTP",$server);
if (!mail($to,$subject,$body,$headers))
echo "We couldn't sign you up at this time. Please try again later.";
else
{
// register the user
$queryreg = mysql_query("
INSERT INTO users VALUES ('','$userName','$passWord','$fullName','$date','$random','0','$email')
");
$lastid = mysql_insert_id();
die ("You have been registered. <a href='login.php'>Click here</a> to return to the login page.");
echo "Successfully Registered";
}
```
|
2012/04/30
|
[
"https://Stackoverflow.com/questions/10380051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1125857/"
] |
[Download phpmailer](https://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/) and try the following code
```
<?php
$mail = new PHPMailer();
$mail->IsSMTP();
//GMAIL config
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the server
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "gmailusername"; // GMAIL username
$mail->Password = "gmailpassword"; // GMAIL password
//End Gmail
$mail->From = "from@email.com";
$mail->FromName = "you name";
$mail->Subject = "some subject";
$mail->MsgHTML("the message");
//$mail->AddReplyTo("reply@email.com","reply name");//they answer here, optional
$mail->AddAddress("address@to.com","name to");
$mail->IsHTML(true); // send as HTML
if(!$mail->Send()) {//to see if we return a message or a value bolean
echo "Mailer Error: " . $mail->ErrorInfo;
} else echo "Message sent!";
```
|
the `mail` builtin is not very suitable for this, it supports only simple setups.
have a look at [pear mail](http://pear.php.net/package/Mail), the examples show you how to send using smtp auth.
|
15,891
|
I was surprised to find out ‘Luther’ is not Martin Luther’s original surname but ‘Luder’ is. The Greek word έλεύθερος that was the origin of his Latin name was Eleutherius. You can see ‘uder’ does not quite sound as good as ‘uther’. You can hear the sound of the Greek word here: [click on the speaker sign to listen](http://translate.google.com/#auto/el/%CE%AD%CE%BB%CE%B5%CF%8D%CE%B8%CE%B5%CF%81%CE%BF%CF%82)
I have read that in the fall of 1517 he changed his name. So what would make Luther get so fussy about his name so that he wanted it to match the original Greek more audibly?
|
2013/04/29
|
[
"https://christianity.stackexchange.com/questions/15891",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/1743/"
] |
According to a book by James Nestingen,
>
> On Luther's "Gospel discovery," his "tower experience," I agree with Nestingen (and Lohse) that it probably coincided with his name change from Luder the Luther, "a small change based on the Greek word for freedom, elutherius. I see the similarity as too exceptional simply to explain Luther's name change as merely a respelling from Low/Middle German to High German.
>
>
>
[http://www.amazon.com/Martin-Luther-James-A-Nestingen/dp/0800697146](http://rads.stackoverflow.com/amzn/click/0800697146)
The reason for choosing a word related to "freedom" has to do with the freedom offered by the Gospel.
|
Perhaps because the German word "Luder" is really not a nice word. It refers to a female that is very obstinate at best and is frequently associated with very questionable morals and behaviors.
You can try google translate but the result are probably not suitable for repeating on this site.
|
15,891
|
I was surprised to find out ‘Luther’ is not Martin Luther’s original surname but ‘Luder’ is. The Greek word έλεύθερος that was the origin of his Latin name was Eleutherius. You can see ‘uder’ does not quite sound as good as ‘uther’. You can hear the sound of the Greek word here: [click on the speaker sign to listen](http://translate.google.com/#auto/el/%CE%AD%CE%BB%CE%B5%CF%8D%CE%B8%CE%B5%CF%81%CE%BF%CF%82)
I have read that in the fall of 1517 he changed his name. So what would make Luther get so fussy about his name so that he wanted it to match the original Greek more audibly?
|
2013/04/29
|
[
"https://christianity.stackexchange.com/questions/15891",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/1743/"
] |
Perhaps because the German word "Luder" is really not a nice word. It refers to a female that is very obstinate at best and is frequently associated with very questionable morals and behaviors.
You can try google translate but the result are probably not suitable for repeating on this site.
|
"Luther shared many of the feelings and opinions of the humanists concerning the ignorance, pride, andfolly of this decadent scholastic system so intimately entwined with the superstitions, errors, and corruption hehad to face. For that reason he at one time was greatly impressed by humanism — so much that he changed his German name Luder to the Greek Eleutherios...free, liberal, freeing, delivering"
(Eckert, O.J., *Luther and the Reformation*, p16) <http://www.wlsessays.net/files/EckertReformation.pdf>
'If ye continue in my word, then are ye my disciples indeed; And ye shall know the truth, and the truth shall make you free.'
- John 8:31-32
|
15,891
|
I was surprised to find out ‘Luther’ is not Martin Luther’s original surname but ‘Luder’ is. The Greek word έλεύθερος that was the origin of his Latin name was Eleutherius. You can see ‘uder’ does not quite sound as good as ‘uther’. You can hear the sound of the Greek word here: [click on the speaker sign to listen](http://translate.google.com/#auto/el/%CE%AD%CE%BB%CE%B5%CF%8D%CE%B8%CE%B5%CF%81%CE%BF%CF%82)
I have read that in the fall of 1517 he changed his name. So what would make Luther get so fussy about his name so that he wanted it to match the original Greek more audibly?
|
2013/04/29
|
[
"https://christianity.stackexchange.com/questions/15891",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/1743/"
] |
Perhaps because the German word "Luder" is really not a nice word. It refers to a female that is very obstinate at best and is frequently associated with very questionable morals and behaviors.
You can try google translate but the result are probably not suitable for repeating on this site.
|
Martin Luther could hardly go through life as Martin Luder, as "Luder" is German (and Danish) for "slut, bitch, whore". What makes you think this had anything to do with audability?! It is just amazing that his father used a name with such a meaning. Check for yourself:
<https://www.dict.cc/german-english/Luder.html>
|
15,891
|
I was surprised to find out ‘Luther’ is not Martin Luther’s original surname but ‘Luder’ is. The Greek word έλεύθερος that was the origin of his Latin name was Eleutherius. You can see ‘uder’ does not quite sound as good as ‘uther’. You can hear the sound of the Greek word here: [click on the speaker sign to listen](http://translate.google.com/#auto/el/%CE%AD%CE%BB%CE%B5%CF%8D%CE%B8%CE%B5%CF%81%CE%BF%CF%82)
I have read that in the fall of 1517 he changed his name. So what would make Luther get so fussy about his name so that he wanted it to match the original Greek more audibly?
|
2013/04/29
|
[
"https://christianity.stackexchange.com/questions/15891",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/1743/"
] |
According to a book by James Nestingen,
>
> On Luther's "Gospel discovery," his "tower experience," I agree with Nestingen (and Lohse) that it probably coincided with his name change from Luder the Luther, "a small change based on the Greek word for freedom, elutherius. I see the similarity as too exceptional simply to explain Luther's name change as merely a respelling from Low/Middle German to High German.
>
>
>
[http://www.amazon.com/Martin-Luther-James-A-Nestingen/dp/0800697146](http://rads.stackoverflow.com/amzn/click/0800697146)
The reason for choosing a word related to "freedom" has to do with the freedom offered by the Gospel.
|
"Luther shared many of the feelings and opinions of the humanists concerning the ignorance, pride, andfolly of this decadent scholastic system so intimately entwined with the superstitions, errors, and corruption hehad to face. For that reason he at one time was greatly impressed by humanism — so much that he changed his German name Luder to the Greek Eleutherios...free, liberal, freeing, delivering"
(Eckert, O.J., *Luther and the Reformation*, p16) <http://www.wlsessays.net/files/EckertReformation.pdf>
'If ye continue in my word, then are ye my disciples indeed; And ye shall know the truth, and the truth shall make you free.'
- John 8:31-32
|
15,891
|
I was surprised to find out ‘Luther’ is not Martin Luther’s original surname but ‘Luder’ is. The Greek word έλεύθερος that was the origin of his Latin name was Eleutherius. You can see ‘uder’ does not quite sound as good as ‘uther’. You can hear the sound of the Greek word here: [click on the speaker sign to listen](http://translate.google.com/#auto/el/%CE%AD%CE%BB%CE%B5%CF%8D%CE%B8%CE%B5%CF%81%CE%BF%CF%82)
I have read that in the fall of 1517 he changed his name. So what would make Luther get so fussy about his name so that he wanted it to match the original Greek more audibly?
|
2013/04/29
|
[
"https://christianity.stackexchange.com/questions/15891",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/1743/"
] |
According to a book by James Nestingen,
>
> On Luther's "Gospel discovery," his "tower experience," I agree with Nestingen (and Lohse) that it probably coincided with his name change from Luder the Luther, "a small change based on the Greek word for freedom, elutherius. I see the similarity as too exceptional simply to explain Luther's name change as merely a respelling from Low/Middle German to High German.
>
>
>
[http://www.amazon.com/Martin-Luther-James-A-Nestingen/dp/0800697146](http://rads.stackoverflow.com/amzn/click/0800697146)
The reason for choosing a word related to "freedom" has to do with the freedom offered by the Gospel.
|
Martin Luther could hardly go through life as Martin Luder, as "Luder" is German (and Danish) for "slut, bitch, whore". What makes you think this had anything to do with audability?! It is just amazing that his father used a name with such a meaning. Check for yourself:
<https://www.dict.cc/german-english/Luder.html>
|
2,716
|
The method must search `Product`s found by criteria and store them in `@products`.
The criteria are as follows:
* If the user enters something in `text_field` (`:search_keywords`) then the product's name needs to be matched with that word
* If the user specifies `product_type` (`:product[:type]`) then all the found products must be of that type.
```
def search
if params[:search_keywords] && params[:search_keywords] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%'")
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%' AND product_type_id = " + params[:product][:type])
end
else
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.find_all_by_product_type_id(params[:product][:type])
else
@products = Product.all
end
end
end
```
|
2011/05/30
|
[
"https://codereview.stackexchange.com/questions/2716",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/4694/"
] |
Try to use scopes, its a lot nicer
```
def search
@products = Products.scoped
if !params[:search_keywords].blank?
@products = @products.where("name LIKE ?", "%#{params[:search_keywords]}%")
end
if !params[:product].try(:[], :type).blank?
@products = @products.where(:product_type_id => params[:product][:type])
end
@products # maybe @products.all if realy needed
end
```
|
1. You can use blank?
2. You need user parameters in SQL query.
3. Maybe you need escaping character `%` in `search_keywords`.
```
def search
keywords_blank = params[:search_keywords].blank?
type_blank = params[:product] && !params[:product][:type].blank?
@products = if keywords_blank && type_blank
Product.all
elsif keywords_blank
Product.find_all_by_product_type_id(params[:product][:type])
elsif type_blank
Product.find(:all, :conditions => ["name LIKE :name", :name => "%#{params[:search_keywords]}%"])
else
Product.find(:conditions => ["name LIKE :name AND product_type_id = :type", {:name => "%#{params[:search_keywords]}%", :type => params[:product][:type]}])
end
end
```
|
2,716
|
The method must search `Product`s found by criteria and store them in `@products`.
The criteria are as follows:
* If the user enters something in `text_field` (`:search_keywords`) then the product's name needs to be matched with that word
* If the user specifies `product_type` (`:product[:type]`) then all the found products must be of that type.
```
def search
if params[:search_keywords] && params[:search_keywords] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%'")
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%' AND product_type_id = " + params[:product][:type])
end
else
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.find_all_by_product_type_id(params[:product][:type])
else
@products = Product.all
end
end
end
```
|
2011/05/30
|
[
"https://codereview.stackexchange.com/questions/2716",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/4694/"
] |
I've seen many Railers' codes tempt to shove many logic in View and Controller. Allow me to add these important emphases:
1. **Skinny Controller Fat Model** which is one of *The Elegant Rails Way principles*.
2. And **Testing**.
Here I have **products\_controller.rb** file inside **app/controllers** directory that contains this:
```
class ProductsController < ApplicationController
def search
@products = Product.search(params)
end
end
```
I put the logic inside the Model. Here is my **product.rb** file inside **app/models** directory:
```
class Product < ActiveRecord::Base
scope :nm, lambda { |n| where "name LIKE ?", '%' + n + '%' }
scope :criteria, lambda { |n, type| nm(n).where type_id: type }
def self.search(opts={})
return all if opts.empty?
return nm(opts[:search_keywords]) unless opts[:search_keywords].nil?
return criteria(opts[:name], opts[:type]) if opts[:product].try(:[], :type).empty?
end
end
```
You could also try to experiment *Dynamic Scope Construction* to improve Product Model code above. I haven't tried it successfully **AND** efficiently here, let me know if anyone can make it better, anyway.
And **Testing**. You can also test your app using [RSpec](http://apidock.com/rspec), [Cucumber](http://cukes.info/), Ruby Selenium, Watir, or any other Test for Ruby Environment, but here I'll only show you how to do it using Ruby Unit Test. Here is my **product\_test.rb** inside **test/unit** directory:
```
require 'test_helper'
require 'product'
class ProductTest < ActiveSupport::TestCase
fixtures :products
def test_nm
assert_equal Product.nm("Pick").first.name, products(:pickaxe).name
end
def test_criteria
assert_equal Product.criteria("Bach", 2).first.name, products(:bach).name
end
def test_search
assert_equal Product.search(:search_keywords => "Pick").first.name,
products(:pickaxe).name
assert_equal Product.search(:search_keywords => "Pick", :type => 1).first.name,
products(:pickaxe).name
assert_equal Product.search.size, Product.count
end
end
```
And its related fixture. Here is my **products.yml** file inside **test/fixtures** directory:
```
pickaxe:
name: Pickaxe 3
type_id: 1
bach:
name: Bach
type_id: 2
lotr:
name: LOTR
type_id: 3
```
And for controller testing, here is my **products\_controller\_test.rb** file inside **test/functional** directory:
```
require 'test_helper'
require "products_controller"
class ProductsControllerTest < ActionController::TestCase
fixtures :products
test "should get search" do
get :search, :search_keywords => 'Pick', :product => { :type => '1' }
assert_response :success
assert_not_nil assigns(:products)
end
end
```
Let's go test them. I use:
```
. ruby -v
ruby 1.9.2p0 (2010-08-18) [i386-darwin9.8.0]
. rails -v
Rails 3.0.9
```
Here is my test's result:
```
. rake test
(in /Users/arie/se/tester)
NOTICE: CREATE TABLE will create implicit sequence "products_id_seq" for serial column "products.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "products_pkey" for table "products"
Loaded suite /opt/experiment/ruby/lib/ruby/1.9.1/rake/rake_test_loader
Started
...
Finished in 0.237899 seconds.
3 tests, 5 assertions, 0 failures, 0 errors, 0 skips
Test run options: --seed 54809
Loaded suite /opt/experiment/ruby/lib/ruby/1.9.1/rake/rake_test_loader
Started
.
Finished in 0.330431 seconds.
1 tests, 2 assertions, 0 failures, 0 errors, 0 skips
Test run options: --seed 25681
```
Alright! Worked like a charm! 0 errors for both unit (for model) and functional (for controller) tests. I also tested it from my browser and it worked.
[You can also download my copy files here](http://ifile.it/ep6hyzb).
Links:
1. [Testing Reference](http://guides.rubyonrails.org/testing.html)
2. [Beginning with Cucumber RailsCasts](http://railscasts.com/episodes/155-beginning-with-cucumber)
3. [Active Record Query Interface 3.0](http://m.onkey.org/active-record-query-interface)
4. [The Skinny on Scopes (Formerly named\_scope)](http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html)
|
1. You can use blank?
2. You need user parameters in SQL query.
3. Maybe you need escaping character `%` in `search_keywords`.
```
def search
keywords_blank = params[:search_keywords].blank?
type_blank = params[:product] && !params[:product][:type].blank?
@products = if keywords_blank && type_blank
Product.all
elsif keywords_blank
Product.find_all_by_product_type_id(params[:product][:type])
elsif type_blank
Product.find(:all, :conditions => ["name LIKE :name", :name => "%#{params[:search_keywords]}%"])
else
Product.find(:conditions => ["name LIKE :name AND product_type_id = :type", {:name => "%#{params[:search_keywords]}%", :type => params[:product][:type]}])
end
end
```
|
2,716
|
The method must search `Product`s found by criteria and store them in `@products`.
The criteria are as follows:
* If the user enters something in `text_field` (`:search_keywords`) then the product's name needs to be matched with that word
* If the user specifies `product_type` (`:product[:type]`) then all the found products must be of that type.
```
def search
if params[:search_keywords] && params[:search_keywords] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%'")
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%' AND product_type_id = " + params[:product][:type])
end
else
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.find_all_by_product_type_id(params[:product][:type])
else
@products = Product.all
end
end
end
```
|
2011/05/30
|
[
"https://codereview.stackexchange.com/questions/2716",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/4694/"
] |
1. You can use blank?
2. You need user parameters in SQL query.
3. Maybe you need escaping character `%` in `search_keywords`.
```
def search
keywords_blank = params[:search_keywords].blank?
type_blank = params[:product] && !params[:product][:type].blank?
@products = if keywords_blank && type_blank
Product.all
elsif keywords_blank
Product.find_all_by_product_type_id(params[:product][:type])
elsif type_blank
Product.find(:all, :conditions => ["name LIKE :name", :name => "%#{params[:search_keywords]}%"])
else
Product.find(:conditions => ["name LIKE :name AND product_type_id = :type", {:name => "%#{params[:search_keywords]}%", :type => params[:product][:type]}])
end
end
```
|
You can use a combination of scopes to simplify the code. Also, you can take advantage of some handy Ruby/ActiveSupport methods and conventions to avoid if conditions.
```
def search
@products = Product.scoped
@products = @products.search_by_name(params[:search_keywords])
@products = @products.search_by_type(params[:product][:type] rescue nil)
# in your view
# @products.all
end
class Product
def self.search_by_name(value)
if value.present?
where("name LIKE ?", "%#{value}%")
else
self
end
end
def self.search_by_type(value)
if value.present?
where(:product_type_id => value)
else
self
end
end
end
```
|
2,716
|
The method must search `Product`s found by criteria and store them in `@products`.
The criteria are as follows:
* If the user enters something in `text_field` (`:search_keywords`) then the product's name needs to be matched with that word
* If the user specifies `product_type` (`:product[:type]`) then all the found products must be of that type.
```
def search
if params[:search_keywords] && params[:search_keywords] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%'")
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%' AND product_type_id = " + params[:product][:type])
end
else
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.find_all_by_product_type_id(params[:product][:type])
else
@products = Product.all
end
end
end
```
|
2011/05/30
|
[
"https://codereview.stackexchange.com/questions/2716",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/4694/"
] |
1. You can use blank?
2. You need user parameters in SQL query.
3. Maybe you need escaping character `%` in `search_keywords`.
```
def search
keywords_blank = params[:search_keywords].blank?
type_blank = params[:product] && !params[:product][:type].blank?
@products = if keywords_blank && type_blank
Product.all
elsif keywords_blank
Product.find_all_by_product_type_id(params[:product][:type])
elsif type_blank
Product.find(:all, :conditions => ["name LIKE :name", :name => "%#{params[:search_keywords]}%"])
else
Product.find(:conditions => ["name LIKE :name AND product_type_id = :type", {:name => "%#{params[:search_keywords]}%", :type => params[:product][:type]}])
end
end
```
|
I like Bert Goethals, Arie and Simone Carletti's answers - my solution would have a touch of each:
in your controller:
```
class ProductsController < ApplicationController
def search
keywords = params[:search_keywords]
type_id = params[:product].try(:[],:type)
@products = Product.search({:type_id => type_id, :keywords => keywords})
end
end
```
in your model
```
def self.search(options={})
keywords = options[:keywords]
type_id = options[:type_id]
products = Product.scoped
products = products.where("name like ?","%#{keywords}%") if keywords.present?
products = products.where(:type_id => type_id) if type_id.present?
products
end
```
I could go with scopes but only if the scope will be used from more than one spot, otherwise the code is small enough to be understandable and organized without them.
|
2,716
|
The method must search `Product`s found by criteria and store them in `@products`.
The criteria are as follows:
* If the user enters something in `text_field` (`:search_keywords`) then the product's name needs to be matched with that word
* If the user specifies `product_type` (`:product[:type]`) then all the found products must be of that type.
```
def search
if params[:search_keywords] && params[:search_keywords] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%'")
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%' AND product_type_id = " + params[:product][:type])
end
else
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.find_all_by_product_type_id(params[:product][:type])
else
@products = Product.all
end
end
end
```
|
2011/05/30
|
[
"https://codereview.stackexchange.com/questions/2716",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/4694/"
] |
Try to use scopes, its a lot nicer
```
def search
@products = Products.scoped
if !params[:search_keywords].blank?
@products = @products.where("name LIKE ?", "%#{params[:search_keywords]}%")
end
if !params[:product].try(:[], :type).blank?
@products = @products.where(:product_type_id => params[:product][:type])
end
@products # maybe @products.all if realy needed
end
```
|
You can use a combination of scopes to simplify the code. Also, you can take advantage of some handy Ruby/ActiveSupport methods and conventions to avoid if conditions.
```
def search
@products = Product.scoped
@products = @products.search_by_name(params[:search_keywords])
@products = @products.search_by_type(params[:product][:type] rescue nil)
# in your view
# @products.all
end
class Product
def self.search_by_name(value)
if value.present?
where("name LIKE ?", "%#{value}%")
else
self
end
end
def self.search_by_type(value)
if value.present?
where(:product_type_id => value)
else
self
end
end
end
```
|
2,716
|
The method must search `Product`s found by criteria and store them in `@products`.
The criteria are as follows:
* If the user enters something in `text_field` (`:search_keywords`) then the product's name needs to be matched with that word
* If the user specifies `product_type` (`:product[:type]`) then all the found products must be of that type.
```
def search
if params[:search_keywords] && params[:search_keywords] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%'")
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%' AND product_type_id = " + params[:product][:type])
end
else
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.find_all_by_product_type_id(params[:product][:type])
else
@products = Product.all
end
end
end
```
|
2011/05/30
|
[
"https://codereview.stackexchange.com/questions/2716",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/4694/"
] |
Try to use scopes, its a lot nicer
```
def search
@products = Products.scoped
if !params[:search_keywords].blank?
@products = @products.where("name LIKE ?", "%#{params[:search_keywords]}%")
end
if !params[:product].try(:[], :type).blank?
@products = @products.where(:product_type_id => params[:product][:type])
end
@products # maybe @products.all if realy needed
end
```
|
I like Bert Goethals, Arie and Simone Carletti's answers - my solution would have a touch of each:
in your controller:
```
class ProductsController < ApplicationController
def search
keywords = params[:search_keywords]
type_id = params[:product].try(:[],:type)
@products = Product.search({:type_id => type_id, :keywords => keywords})
end
end
```
in your model
```
def self.search(options={})
keywords = options[:keywords]
type_id = options[:type_id]
products = Product.scoped
products = products.where("name like ?","%#{keywords}%") if keywords.present?
products = products.where(:type_id => type_id) if type_id.present?
products
end
```
I could go with scopes but only if the scope will be used from more than one spot, otherwise the code is small enough to be understandable and organized without them.
|
2,716
|
The method must search `Product`s found by criteria and store them in `@products`.
The criteria are as follows:
* If the user enters something in `text_field` (`:search_keywords`) then the product's name needs to be matched with that word
* If the user specifies `product_type` (`:product[:type]`) then all the found products must be of that type.
```
def search
if params[:search_keywords] && params[:search_keywords] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%'")
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%' AND product_type_id = " + params[:product][:type])
end
else
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.find_all_by_product_type_id(params[:product][:type])
else
@products = Product.all
end
end
end
```
|
2011/05/30
|
[
"https://codereview.stackexchange.com/questions/2716",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/4694/"
] |
I've seen many Railers' codes tempt to shove many logic in View and Controller. Allow me to add these important emphases:
1. **Skinny Controller Fat Model** which is one of *The Elegant Rails Way principles*.
2. And **Testing**.
Here I have **products\_controller.rb** file inside **app/controllers** directory that contains this:
```
class ProductsController < ApplicationController
def search
@products = Product.search(params)
end
end
```
I put the logic inside the Model. Here is my **product.rb** file inside **app/models** directory:
```
class Product < ActiveRecord::Base
scope :nm, lambda { |n| where "name LIKE ?", '%' + n + '%' }
scope :criteria, lambda { |n, type| nm(n).where type_id: type }
def self.search(opts={})
return all if opts.empty?
return nm(opts[:search_keywords]) unless opts[:search_keywords].nil?
return criteria(opts[:name], opts[:type]) if opts[:product].try(:[], :type).empty?
end
end
```
You could also try to experiment *Dynamic Scope Construction* to improve Product Model code above. I haven't tried it successfully **AND** efficiently here, let me know if anyone can make it better, anyway.
And **Testing**. You can also test your app using [RSpec](http://apidock.com/rspec), [Cucumber](http://cukes.info/), Ruby Selenium, Watir, or any other Test for Ruby Environment, but here I'll only show you how to do it using Ruby Unit Test. Here is my **product\_test.rb** inside **test/unit** directory:
```
require 'test_helper'
require 'product'
class ProductTest < ActiveSupport::TestCase
fixtures :products
def test_nm
assert_equal Product.nm("Pick").first.name, products(:pickaxe).name
end
def test_criteria
assert_equal Product.criteria("Bach", 2).first.name, products(:bach).name
end
def test_search
assert_equal Product.search(:search_keywords => "Pick").first.name,
products(:pickaxe).name
assert_equal Product.search(:search_keywords => "Pick", :type => 1).first.name,
products(:pickaxe).name
assert_equal Product.search.size, Product.count
end
end
```
And its related fixture. Here is my **products.yml** file inside **test/fixtures** directory:
```
pickaxe:
name: Pickaxe 3
type_id: 1
bach:
name: Bach
type_id: 2
lotr:
name: LOTR
type_id: 3
```
And for controller testing, here is my **products\_controller\_test.rb** file inside **test/functional** directory:
```
require 'test_helper'
require "products_controller"
class ProductsControllerTest < ActionController::TestCase
fixtures :products
test "should get search" do
get :search, :search_keywords => 'Pick', :product => { :type => '1' }
assert_response :success
assert_not_nil assigns(:products)
end
end
```
Let's go test them. I use:
```
. ruby -v
ruby 1.9.2p0 (2010-08-18) [i386-darwin9.8.0]
. rails -v
Rails 3.0.9
```
Here is my test's result:
```
. rake test
(in /Users/arie/se/tester)
NOTICE: CREATE TABLE will create implicit sequence "products_id_seq" for serial column "products.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "products_pkey" for table "products"
Loaded suite /opt/experiment/ruby/lib/ruby/1.9.1/rake/rake_test_loader
Started
...
Finished in 0.237899 seconds.
3 tests, 5 assertions, 0 failures, 0 errors, 0 skips
Test run options: --seed 54809
Loaded suite /opt/experiment/ruby/lib/ruby/1.9.1/rake/rake_test_loader
Started
.
Finished in 0.330431 seconds.
1 tests, 2 assertions, 0 failures, 0 errors, 0 skips
Test run options: --seed 25681
```
Alright! Worked like a charm! 0 errors for both unit (for model) and functional (for controller) tests. I also tested it from my browser and it worked.
[You can also download my copy files here](http://ifile.it/ep6hyzb).
Links:
1. [Testing Reference](http://guides.rubyonrails.org/testing.html)
2. [Beginning with Cucumber RailsCasts](http://railscasts.com/episodes/155-beginning-with-cucumber)
3. [Active Record Query Interface 3.0](http://m.onkey.org/active-record-query-interface)
4. [The Skinny on Scopes (Formerly named\_scope)](http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html)
|
You can use a combination of scopes to simplify the code. Also, you can take advantage of some handy Ruby/ActiveSupport methods and conventions to avoid if conditions.
```
def search
@products = Product.scoped
@products = @products.search_by_name(params[:search_keywords])
@products = @products.search_by_type(params[:product][:type] rescue nil)
# in your view
# @products.all
end
class Product
def self.search_by_name(value)
if value.present?
where("name LIKE ?", "%#{value}%")
else
self
end
end
def self.search_by_type(value)
if value.present?
where(:product_type_id => value)
else
self
end
end
end
```
|
2,716
|
The method must search `Product`s found by criteria and store them in `@products`.
The criteria are as follows:
* If the user enters something in `text_field` (`:search_keywords`) then the product's name needs to be matched with that word
* If the user specifies `product_type` (`:product[:type]`) then all the found products must be of that type.
```
def search
if params[:search_keywords] && params[:search_keywords] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%'")
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.where("name LIKE '%" + params[:search_keywords] + "%' AND product_type_id = " + params[:product][:type])
end
else
if params[:product] && params[:product][:type] && params[:product][:type] != ""
@products = Product.find_all_by_product_type_id(params[:product][:type])
else
@products = Product.all
end
end
end
```
|
2011/05/30
|
[
"https://codereview.stackexchange.com/questions/2716",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/4694/"
] |
I've seen many Railers' codes tempt to shove many logic in View and Controller. Allow me to add these important emphases:
1. **Skinny Controller Fat Model** which is one of *The Elegant Rails Way principles*.
2. And **Testing**.
Here I have **products\_controller.rb** file inside **app/controllers** directory that contains this:
```
class ProductsController < ApplicationController
def search
@products = Product.search(params)
end
end
```
I put the logic inside the Model. Here is my **product.rb** file inside **app/models** directory:
```
class Product < ActiveRecord::Base
scope :nm, lambda { |n| where "name LIKE ?", '%' + n + '%' }
scope :criteria, lambda { |n, type| nm(n).where type_id: type }
def self.search(opts={})
return all if opts.empty?
return nm(opts[:search_keywords]) unless opts[:search_keywords].nil?
return criteria(opts[:name], opts[:type]) if opts[:product].try(:[], :type).empty?
end
end
```
You could also try to experiment *Dynamic Scope Construction* to improve Product Model code above. I haven't tried it successfully **AND** efficiently here, let me know if anyone can make it better, anyway.
And **Testing**. You can also test your app using [RSpec](http://apidock.com/rspec), [Cucumber](http://cukes.info/), Ruby Selenium, Watir, or any other Test for Ruby Environment, but here I'll only show you how to do it using Ruby Unit Test. Here is my **product\_test.rb** inside **test/unit** directory:
```
require 'test_helper'
require 'product'
class ProductTest < ActiveSupport::TestCase
fixtures :products
def test_nm
assert_equal Product.nm("Pick").first.name, products(:pickaxe).name
end
def test_criteria
assert_equal Product.criteria("Bach", 2).first.name, products(:bach).name
end
def test_search
assert_equal Product.search(:search_keywords => "Pick").first.name,
products(:pickaxe).name
assert_equal Product.search(:search_keywords => "Pick", :type => 1).first.name,
products(:pickaxe).name
assert_equal Product.search.size, Product.count
end
end
```
And its related fixture. Here is my **products.yml** file inside **test/fixtures** directory:
```
pickaxe:
name: Pickaxe 3
type_id: 1
bach:
name: Bach
type_id: 2
lotr:
name: LOTR
type_id: 3
```
And for controller testing, here is my **products\_controller\_test.rb** file inside **test/functional** directory:
```
require 'test_helper'
require "products_controller"
class ProductsControllerTest < ActionController::TestCase
fixtures :products
test "should get search" do
get :search, :search_keywords => 'Pick', :product => { :type => '1' }
assert_response :success
assert_not_nil assigns(:products)
end
end
```
Let's go test them. I use:
```
. ruby -v
ruby 1.9.2p0 (2010-08-18) [i386-darwin9.8.0]
. rails -v
Rails 3.0.9
```
Here is my test's result:
```
. rake test
(in /Users/arie/se/tester)
NOTICE: CREATE TABLE will create implicit sequence "products_id_seq" for serial column "products.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "products_pkey" for table "products"
Loaded suite /opt/experiment/ruby/lib/ruby/1.9.1/rake/rake_test_loader
Started
...
Finished in 0.237899 seconds.
3 tests, 5 assertions, 0 failures, 0 errors, 0 skips
Test run options: --seed 54809
Loaded suite /opt/experiment/ruby/lib/ruby/1.9.1/rake/rake_test_loader
Started
.
Finished in 0.330431 seconds.
1 tests, 2 assertions, 0 failures, 0 errors, 0 skips
Test run options: --seed 25681
```
Alright! Worked like a charm! 0 errors for both unit (for model) and functional (for controller) tests. I also tested it from my browser and it worked.
[You can also download my copy files here](http://ifile.it/ep6hyzb).
Links:
1. [Testing Reference](http://guides.rubyonrails.org/testing.html)
2. [Beginning with Cucumber RailsCasts](http://railscasts.com/episodes/155-beginning-with-cucumber)
3. [Active Record Query Interface 3.0](http://m.onkey.org/active-record-query-interface)
4. [The Skinny on Scopes (Formerly named\_scope)](http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html)
|
I like Bert Goethals, Arie and Simone Carletti's answers - my solution would have a touch of each:
in your controller:
```
class ProductsController < ApplicationController
def search
keywords = params[:search_keywords]
type_id = params[:product].try(:[],:type)
@products = Product.search({:type_id => type_id, :keywords => keywords})
end
end
```
in your model
```
def self.search(options={})
keywords = options[:keywords]
type_id = options[:type_id]
products = Product.scoped
products = products.where("name like ?","%#{keywords}%") if keywords.present?
products = products.where(:type_id => type_id) if type_id.present?
products
end
```
I could go with scopes but only if the scope will be used from more than one spot, otherwise the code is small enough to be understandable and organized without them.
|
17,259,243
|
I have an embedded tableview within a view. The top rows of this embedded table view are always visible, even with the keyboard. If you enter something into the lower cells I want them to scroll up (as usual) in order to see what you're entering into the textfields. However this doesn't happen and they remain hidden behind the keyboard. How can I change this?
Thx
Michael
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17259243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833434/"
] |
As discussed in the comments below, your best bet is to use a proper grid system. Twitter Bootstrap has two great choices [Default Grid System](http://twitter.github.io/bootstrap/scaffolding.html#gridSystem) and [Fluid Grid System](http://twitter.github.io/bootstrap/scaffolding.html#fluidGridSystem). In addition, you can package Bootstrap from their website to only include the modules you need.
Otherwise, with the typo in `# middle` fixed, you can use `float: left` on `#middle` to make `#right` not wrap. You will also need to use JavaScript to set the width on `#middle` based on screen-size, or you risk the text being too long and pushing `#right` down again. A solution is easier to accomplish with a grid system!
I wrote the JS to work on `window.onload`, you could also do on a resize.
Modified code: <http://codepen.io/anon/pen/xfwJi>
|
One Solution:
```
#middle {
background-color: #999;
height: 100px;
float:left;
width:1364px;
}
```
|
17,259,243
|
I have an embedded tableview within a view. The top rows of this embedded table view are always visible, even with the keyboard. If you enter something into the lower cells I want them to scroll up (as usual) in order to see what you're entering into the textfields. However this doesn't happen and they remain hidden behind the keyboard. How can I change this?
Thx
Michael
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17259243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833434/"
] |
Use a
```
float: left
```
on the #middle one. Also, try setting a `width`, to avoid the middle div spanning to 100%
|
As discussed in the comments below, your best bet is to use a proper grid system. Twitter Bootstrap has two great choices [Default Grid System](http://twitter.github.io/bootstrap/scaffolding.html#gridSystem) and [Fluid Grid System](http://twitter.github.io/bootstrap/scaffolding.html#fluidGridSystem). In addition, you can package Bootstrap from their website to only include the modules you need.
Otherwise, with the typo in `# middle` fixed, you can use `float: left` on `#middle` to make `#right` not wrap. You will also need to use JavaScript to set the width on `#middle` based on screen-size, or you risk the text being too long and pushing `#right` down again. A solution is easier to accomplish with a grid system!
I wrote the JS to work on `window.onload`, you could also do on a resize.
Modified code: <http://codepen.io/anon/pen/xfwJi>
|
17,259,243
|
I have an embedded tableview within a view. The top rows of this embedded table view are always visible, even with the keyboard. If you enter something into the lower cells I want them to scroll up (as usual) in order to see what you're entering into the textfields. However this doesn't happen and they remain hidden behind the keyboard. How can I change this?
Thx
Michael
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17259243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833434/"
] |
As discussed in the comments below, your best bet is to use a proper grid system. Twitter Bootstrap has two great choices [Default Grid System](http://twitter.github.io/bootstrap/scaffolding.html#gridSystem) and [Fluid Grid System](http://twitter.github.io/bootstrap/scaffolding.html#fluidGridSystem). In addition, you can package Bootstrap from their website to only include the modules you need.
Otherwise, with the typo in `# middle` fixed, you can use `float: left` on `#middle` to make `#right` not wrap. You will also need to use JavaScript to set the width on `#middle` based on screen-size, or you risk the text being too long and pushing `#right` down again. A solution is easier to accomplish with a grid system!
I wrote the JS to work on `window.onload`, you could also do on a resize.
Modified code: <http://codepen.io/anon/pen/xfwJi>
|
try floating the middle div to left as well. That should work.
```
#middle {
background-color: #999;
height: 100px;
float:left;
}
```
|
17,259,243
|
I have an embedded tableview within a view. The top rows of this embedded table view are always visible, even with the keyboard. If you enter something into the lower cells I want them to scroll up (as usual) in order to see what you're entering into the textfields. However this doesn't happen and they remain hidden behind the keyboard. How can I change this?
Thx
Michael
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17259243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833434/"
] |
As discussed in the comments below, your best bet is to use a proper grid system. Twitter Bootstrap has two great choices [Default Grid System](http://twitter.github.io/bootstrap/scaffolding.html#gridSystem) and [Fluid Grid System](http://twitter.github.io/bootstrap/scaffolding.html#fluidGridSystem). In addition, you can package Bootstrap from their website to only include the modules you need.
Otherwise, with the typo in `# middle` fixed, you can use `float: left` on `#middle` to make `#right` not wrap. You will also need to use JavaScript to set the width on `#middle` based on screen-size, or you risk the text being too long and pushing `#right` down again. A solution is easier to accomplish with a grid system!
I wrote the JS to work on `window.onload`, you could also do on a resize.
Modified code: <http://codepen.io/anon/pen/xfwJi>
|
use `float: left;` in `#middle > p`
```css
#middle > p {
line-height: 100px;
color: #eee;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
font-family: monospace;
float: left; /* change here */
}
```
|
17,259,243
|
I have an embedded tableview within a view. The top rows of this embedded table view are always visible, even with the keyboard. If you enter something into the lower cells I want them to scroll up (as usual) in order to see what you're entering into the textfields. However this doesn't happen and they remain hidden behind the keyboard. How can I change this?
Thx
Michael
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17259243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833434/"
] |
As discussed in the comments below, your best bet is to use a proper grid system. Twitter Bootstrap has two great choices [Default Grid System](http://twitter.github.io/bootstrap/scaffolding.html#gridSystem) and [Fluid Grid System](http://twitter.github.io/bootstrap/scaffolding.html#fluidGridSystem). In addition, you can package Bootstrap from their website to only include the modules you need.
Otherwise, with the typo in `# middle` fixed, you can use `float: left` on `#middle` to make `#right` not wrap. You will also need to use JavaScript to set the width on `#middle` based on screen-size, or you risk the text being too long and pushing `#right` down again. A solution is easier to accomplish with a grid system!
I wrote the JS to work on `window.onload`, you could also do on a resize.
Modified code: <http://codepen.io/anon/pen/xfwJi>
|
Here is a [fiddle](http://jsfiddle.net/9N3Fs/1/). Check it out, it pretty much solves your problem.
Moreover, I would like to suggest you using a grid system as it will help you in making the website in a lot more easier way with very or no little problems!
**CSS:**
```
#outer {
background-color: #222;
height: 100px;
width: 100%;
}
#left {
background-color: #555;
width: 100px;
height: 100px;
float: left;
}
#right {
background-color: #777;
width: 200px;
height: 100px;
float: right;
margin-top: -100px;
}
#middle {
background-color: #999;
height: 100px;
width: 72%;
float:left;
}
#middle > p {
line-height: 100px;
color: #eee;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
font-family: monospace;
}
```
Take a look at [this site](http://www.xhtmljunction.com/blog/10-popular-css-grid-systems-for-a-website/), provides 10 CSS grid systems! :)
|
17,259,243
|
I have an embedded tableview within a view. The top rows of this embedded table view are always visible, even with the keyboard. If you enter something into the lower cells I want them to scroll up (as usual) in order to see what you're entering into the textfields. However this doesn't happen and they remain hidden behind the keyboard. How can I change this?
Thx
Michael
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17259243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833434/"
] |
Use a
```
float: left
```
on the #middle one. Also, try setting a `width`, to avoid the middle div spanning to 100%
|
One Solution:
```
#middle {
background-color: #999;
height: 100px;
float:left;
width:1364px;
}
```
|
17,259,243
|
I have an embedded tableview within a view. The top rows of this embedded table view are always visible, even with the keyboard. If you enter something into the lower cells I want them to scroll up (as usual) in order to see what you're entering into the textfields. However this doesn't happen and they remain hidden behind the keyboard. How can I change this?
Thx
Michael
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17259243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833434/"
] |
Use a
```
float: left
```
on the #middle one. Also, try setting a `width`, to avoid the middle div spanning to 100%
|
try floating the middle div to left as well. That should work.
```
#middle {
background-color: #999;
height: 100px;
float:left;
}
```
|
17,259,243
|
I have an embedded tableview within a view. The top rows of this embedded table view are always visible, even with the keyboard. If you enter something into the lower cells I want them to scroll up (as usual) in order to see what you're entering into the textfields. However this doesn't happen and they remain hidden behind the keyboard. How can I change this?
Thx
Michael
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17259243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833434/"
] |
Use a
```
float: left
```
on the #middle one. Also, try setting a `width`, to avoid the middle div spanning to 100%
|
use `float: left;` in `#middle > p`
```css
#middle > p {
line-height: 100px;
color: #eee;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
font-family: monospace;
float: left; /* change here */
}
```
|
17,259,243
|
I have an embedded tableview within a view. The top rows of this embedded table view are always visible, even with the keyboard. If you enter something into the lower cells I want them to scroll up (as usual) in order to see what you're entering into the textfields. However this doesn't happen and they remain hidden behind the keyboard. How can I change this?
Thx
Michael
|
2013/06/23
|
[
"https://Stackoverflow.com/questions/17259243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1833434/"
] |
Use a
```
float: left
```
on the #middle one. Also, try setting a `width`, to avoid the middle div spanning to 100%
|
Here is a [fiddle](http://jsfiddle.net/9N3Fs/1/). Check it out, it pretty much solves your problem.
Moreover, I would like to suggest you using a grid system as it will help you in making the website in a lot more easier way with very or no little problems!
**CSS:**
```
#outer {
background-color: #222;
height: 100px;
width: 100%;
}
#left {
background-color: #555;
width: 100px;
height: 100px;
float: left;
}
#right {
background-color: #777;
width: 200px;
height: 100px;
float: right;
margin-top: -100px;
}
#middle {
background-color: #999;
height: 100px;
width: 72%;
float:left;
}
#middle > p {
line-height: 100px;
color: #eee;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
font-family: monospace;
}
```
Take a look at [this site](http://www.xhtmljunction.com/blog/10-popular-css-grid-systems-for-a-website/), provides 10 CSS grid systems! :)
|
56,880,154
|
I have 10,000 full sized images so each image is about 4MB.
I want to display images in android app by using `firebase storage` and `database` and `recyclerview`.
My question is
**Case 1.** Do I have to save reduced sized images in firebase storage?
**Case 2.** Do I just save original big sized images in firebase storage and loading low quality small sized images?
I have already implemented the Case 1 with Glide. This is not a problem.
What about Case 2? Does it work?
|
2019/07/04
|
[
"https://Stackoverflow.com/questions/56880154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9131083/"
] |
>
> Case 1. Do I have to save reduced sized images in firebase storage?
>
>
>
Its totally depends upon you . you want to save original file or scale down image . But consider following facts .
* You need more storage for Original Size (paid plan after threshold)
* More Server bandwidth will be utilise for large Images
* user's Internet Data. (will consume more data for large images)
>
> Case 2. Do I just save original big sized images in firebase storage
> and loading low quality small sized images?
>
>
>
there are two cases
1. In firebase you need to store two types of images . (Thumbnail and Original image). so first load thumbnail and if user choose to download. then get original image.
2. You can scale down image at the time of loading in view with Glide or Picasso you can resize images easily.
|
Though it varies from case to case and I believe/assume with 10,000 images you are making an app whose primary feature is its photos.
Save the full sized images. Since user won't see all 10,000 at same time, you should also explore **Paging Library** from JetPack. Here is the link <https://developer.android.com/topic/libraries/architecture/paging.html>
Show/Load only the ones that are required. Optimization here will be the trick.
|
56,880,154
|
I have 10,000 full sized images so each image is about 4MB.
I want to display images in android app by using `firebase storage` and `database` and `recyclerview`.
My question is
**Case 1.** Do I have to save reduced sized images in firebase storage?
**Case 2.** Do I just save original big sized images in firebase storage and loading low quality small sized images?
I have already implemented the Case 1 with Glide. This is not a problem.
What about Case 2? Does it work?
|
2019/07/04
|
[
"https://Stackoverflow.com/questions/56880154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9131083/"
] |
>
> Case 1. Do I have to save reduced sized images in firebase storage?
>
>
>
Its totally depends upon you . you want to save original file or scale down image . But consider following facts .
* You need more storage for Original Size (paid plan after threshold)
* More Server bandwidth will be utilise for large Images
* user's Internet Data. (will consume more data for large images)
>
> Case 2. Do I just save original big sized images in firebase storage
> and loading low quality small sized images?
>
>
>
there are two cases
1. In firebase you need to store two types of images . (Thumbnail and Original image). so first load thumbnail and if user choose to download. then get original image.
2. You can scale down image at the time of loading in view with Glide or Picasso you can resize images easily.
|
Firebase will be paid on [bandwidth](https://firebase.google.com/docs/firestore/quotas), they are free up to some of the limit of bandwidth, so if you use more images(10K) with the low size or high size. You need to upgrade your firebase plan if the user loads that images.
The solution is that you should purchase any server with low cost and upload all images with various dimensions such as Thumbnail, medium, large, and original size, so it will be helpful for every condition to load fastly.
|
1,069,110
|
Not able to perform partition of C drive. I bought HP laptop windows 8.1 initially I shrink my C drive using disk management then it was done, but now when there is 170 GB free on my C drive and i want to shrink C drive to create one more drive of 50 GB, but it is giving only 13 MB to shrink.
[](https://i.stack.imgur.com/mFWjD.png)
|
2016/04/24
|
[
"https://superuser.com/questions/1069110",
"https://superuser.com",
"https://superuser.com/users/573410/"
] |
OK, I did a test and YES, the Boot.WIM file works and using GImageX works fine to install the required files for windows.
However... I then try to run BCDBoot.exe from that external drive and I come up with an error:
The program can't start because api-ms-win-core-heap-I2-1-0.dll is missing from your computer. Try reinstalling the program to fix this problem.
I am trying to make a Windows 10 external drive, from a machine that is currently running Windows 7. Does that make a difference? Any other reasons why that file isn't present? Could it be that Boot.WIM doesn't have that file and should?
|
You used the Media Creation tool and this includes ESD files. You can [convert the ESD into a WIM](https://github.com/gus33000/ESD-Decrypter) or [download proper ISOs from this Microsoft page](https://www.microsoft.com/en-US/software-download/techbench) which includes an `install.wim`.
|
22,662,778
|
I need to run a function for each item in a drop down menu. The code is:
```
$( document ).ready(function() {
$('[id*="lwayer_x002d_EisDikigoros_1eef9a23-7a35-4dcf-8de9-a088b4681b2b"]')
.each(function(index) {
/* here, I need to do some manipulation on the item */
console.log("index is:"+???+"value is"+???);
});
});
```
I understand that i need to put something before each() to select all items but I don't know what to put
Thank you
```
The drop down menu is :
<select id="lwayer_x002d_EisDikigoros_1eef9a23-7a35-4dcf-8de9-a088b4681b2b_$LookupField" title="Εισ. Δικηγόρος/οι">
<option value="0">(None)</option> <option value="1">(Name1)</option> etc
```
|
2014/03/26
|
[
"https://Stackoverflow.com/questions/22662778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750037/"
] |
```
.each(index, value) //2 parameter with index as well as value
```
>
> In your case value returns the htmlElement as object so use
> `$(this).val()`
>
>
>
so you can have
```
$('[id*="lwayer_x002d_EisDikigoros_1eef9a23-7a35-4dcf-8de9-a088b4681b2b"]
> option').
.each(function(index, value) {
console.log("index is:"+index+"value is"+$(this).val());
```
|
I think that It will help you.
```
$("#dropdownid option").each(function(){
/* write code what ever you want to do */
});
```
|
22,662,778
|
I need to run a function for each item in a drop down menu. The code is:
```
$( document ).ready(function() {
$('[id*="lwayer_x002d_EisDikigoros_1eef9a23-7a35-4dcf-8de9-a088b4681b2b"]')
.each(function(index) {
/* here, I need to do some manipulation on the item */
console.log("index is:"+???+"value is"+???);
});
});
```
I understand that i need to put something before each() to select all items but I don't know what to put
Thank you
```
The drop down menu is :
<select id="lwayer_x002d_EisDikigoros_1eef9a23-7a35-4dcf-8de9-a088b4681b2b_$LookupField" title="Εισ. Δικηγόρος/οι">
<option value="0">(None)</option> <option value="1">(Name1)</option> etc
```
|
2014/03/26
|
[
"https://Stackoverflow.com/questions/22662778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1750037/"
] |
Try this:
```
$(document).ready(function(){
$('select[id*="lwayer_x002d_EisDikigoros_1eef9a23-7a35-4dcf-8de9-a088b4681b2b"] option').each(function(index,value) {
console.log("index is:"+index); // index
console.log("value is"+$(this).val()); // dropdown option value
console.log("dropdown text value is"+$(this).text()); //dropdown option text
});
});
```
**[DEMO](http://jsfiddle.net/kunknown/qb8S7/)**
|
I think that It will help you.
```
$("#dropdownid option").each(function(){
/* write code what ever you want to do */
});
```
|
45,050,232
|
I want to read the Body of the email file (.msg) in a powershell script, however I can only open it once because the file is "locked" or already opened, so there is an error the 2nd time.
My Code:
```
Get-ChildItem $scriptPath -Filter *.msg |
ForEach-Object {
$outlook = New-Object -comobject outlook.application
$msg = $outlook.Session.OpenSharedItem($_.FullName)
$msg | Select-Object -ExpandProperty Body
$outlook.Quit()
}
```
Error is: The file XXX cant be opened. Maybe it is already opened....
Thanks in advance
|
2017/07/12
|
[
"https://Stackoverflow.com/questions/45050232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I know it's an old thread, but its the top when searching for this issue. This is what worked for me:
```
Get-ChildItem $scriptPath -Filter *.msg |
ForEach-Object {
$outlook = New-Object -comobject outlook.application
$msg = $outlook.Session.OpenSharedItem($_.FullName)
$msg | Select-Object -ExpandProperty Body
$msg.Close(1) # oldispose
$msg = $null
}
```
|
Which Outlook version do you use?
There's [a bug in Outlook](https://social.technet.microsoft.com/Forums/ie/en-US/3a15a6bf-dfb9-48a7-9ee8-faf592bd1287/we-cant-open-filelocationmsg-its-possible-the-file-is-already-open-or-you-dont-have?forum=outlook) and a workaround is to mark the `.msg` files with `readonly` attribute.
|
81,951
|
I'm using this command to process PNG files:
```
find . -iname "*png" -print0 | xargs -r0 --max-procs=4 -n1 sh -c 'pngnq -s1 $1 && advpng -z -4 -q ${$1%.*}-nq8.png' -
```
It seems to actually work fine, but also outputs this for each file that it processes:
```
-: 1: -: Bad substitution
```
I assume that I'm doing something wrong here `${$1%.*}` - but I'm really not sure. The trailing dash is there on purpose, as per the docs [here](http://www.gnu.org/software/findutils/manual/html_node/find_html/Invoking-the-shell-from-xargs.html#Invoking-the-shell-from-xargs) - and I can't just pipe the whole thing because `advpng` can't process things from stdin/out, sadly - so I have to use filenames.
Anyone know how to fix this so it doesn't have this error?
|
2013/07/06
|
[
"https://unix.stackexchange.com/questions/81951",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/41614/"
] |
An obvious problem is the missing quoting:
```
... sh -c 'pngnq -s1 "$1" && advpng -z -4 -q "${1%.*}"-nq8.png' -
```
You are right about your assumption that `${$1%.*}` is the real problem. You must not repeat the `$` in the brackets.
The docs say nothing about a trailing dash, do they? Just about a name.
|
Use GNU Parallel:
```
find . -iname "*png" -print0 | parallel -0 pngnq -s1 {} '&&' advpng -z -4 -q {.}-nq8.png
```
You can find more about GNU Parallel at: <http://www.gnu.org/s/parallel/>
You can install GNU Parallel in just 10 seconds with:
```
wget -O - pi.dk/3 | sh
```
Watch the intro video on <http://www.youtube.com/playlist?list=PL284C9FF2488BC6D1>
|
2,844,735
|
I'm making my first steps in Test Driven Development with Visual Studio. I have some questions regarding how to implement generic classes with VS 2010.
First, let's say I want to implement my own version of an ArrayList.
I start by creating the following test (I'm using in this case MSTest):
```
[TestMethod]
public void Add_10_Items_Remove_10_Items_Check_Size_Is_Zero() {
var myArrayList = new MyArrayList<int>();
for (int i = 0; i < 10; ++i) {
myArrayList.Add(i);
}
for (int i = 0; i < 10; ++i) {
myArrayList.RemoveAt(0); //should this mean RemoveAt(int) or RemoveAt(T)?
//VS doesn't know. Any work arounds?
}
int expected = 0;
int actual = myArrayList.Size;
Assert.AreEqual(expected, actual);
}
```
I'm using VS 2010 ability to hit
>
> ctrl + .
>
>
>
and have it implement classes/methods on the go.
1. I have been getting some trouble when implementing generic classes. For example, when I define an `.Add(10)` method, VS doesn't know if I intend a generic method(as the class is generic) or an `Add(int number)` method. Is there any way to differentiate this?
2. The same can happen with return types. Let's assume I'm implementing a `MyStack` stack and I want to test if after I push and element and pop it, the stack is still empty. We all know pop should return something, but usually, the code of this test shouldn't care for it. Visual Studio would then think that pop is a void method, which in fact is not what one would want. How to deal with this? For each method, should I start by making tests that are "very specific" such as is obvious the method should return something so I don't get this kind of ambiguity? Even if not using the result, should I have something like `int popValue = myStack.Pop()` ?
3. How should I do tests to generic classes? Only test with one generic kind of type? I have been using `int`s, as they are easy to use, but should I also test with different kinds of objects? How do you usually approach this?
4. I see there is a popular tool called TestDriven for .NET. With VS 2010 release, is it still useful, or a lot of its features are now part of VS 2010, rendering it kinda useless?
5. Whenever I define a new property in my test code, and ask VS to generate that method stub for me, it generates both a getter and a setter. If I have something like `int val = MyClass.MyProperty` i'd like to to understand that (at least yet) I only want to define a getter.
Thanks
|
2010/05/16
|
[
"https://Stackoverflow.com/questions/2844735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130758/"
] |
The usual approach is to send this information:
1. Where the player is
2. At what time he is there (using the game's internal concept of time, not necessarily real time)
3. The player's movement vector (direction and speed)
Then the clients can use dead reckoning to estimate where the other players are, so that the network latency will disturb the game less. Updates need to be send only when the player changes his direction or speed of movement (which the other clients cannot predict), so also network bandwidth will be saved.
Here are some links on dead reckoning. The same web sites contain probably also more articles on it.
<http://www.gamasutra.com/view/feature/3230/dead_reckoning_latency_hiding_for_.php>
<http://www.gamedev.net/reference/articles/article1370.asp>
|
i think the first approach is better. so you have equal data on all clients.
when the physics are simple and the results of the calculations are always the same the second approach is ok too. but if there are random numbers possible you will have different effects on all clients.
|
105,091
|
In the preface to his very influential books *Automata, Languages and Machines (Volumes A, B)*, Samuel Eilenberg tantalizingly promised a Volume C dealing with "a hierarchy (called the rational hierarchy) of the nonrational phenomena... using rational relations as a tool for comparison. Rational sets are at the bottom of this hierarchy. Moving upward one encounters 'algebraic phenomena,'" which lead to "to the context-free grammars and context-free languages of Chomsky, and to several related topics."
But Eilenberg never published volume C. He did leave preliminary handwritten notes for the first few chapters (<http://www-igm.univ-mlv.fr/~berstel/EilenbergVolumeC.html>) complete with scratchouts, question marks, side notes and gaps.
Finally, the question -- does anyone know of work along the same lines to possibly reconstruct what Eilenberg had in mind? If not, what material is likely closest to his ideas?
Also, anyone know *why* Eilenberg stopped before making much progress on Volume C? This was the late 70's, and he did not die until 1998. He seemed to have the math largely done, at least in his mind.
(Same but revised question on cstheory stackexchange - <https://cstheory.stackexchange.com/questions/10308/eilenbergs-rational-hierarchy-of-nonrational-automata-languages-where-is-i> )
|
2012/02/02
|
[
"https://math.stackexchange.com/questions/105091",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/271/"
] |
It would be hazardous to guess what Eilenberg had in mind, but a reasonable answer to your question
>
> What material is likely closest to his ideas?
>
>
>
might be the theory of [cones](http://en.wikipedia.org/wiki/Cone_(formal_languages)) (also called [full trios](http://en.wikipedia.org/wiki/Abstract_family_of_languages)).
An excellent reference on the part of this theory related to context-free languages is Berstel's book [Transductions and Context-Free Languages](http://www-igm.univ-mlv.fr/~berstel/LivreTransductions/Transductions_1979.djvu), Teuber 1979.
An alternative answer (still for context-free languages) can be found in the little known but very inspiring article by
J. Berstel and L. Boasson, [Towards an algebraic theory of context-free languages](http://www-igm.univ-mlv.fr/~berstel/Articles/1996AlgebraicTheory.pdf), 1996, Fundamenta Informaticae, 25(3):217-239, 1996.
To quote your introduction, the first reference is using "rational relations as a tool for comparison" and the second one really "encounters algebraic phenomena which lead to the context-free grammars and context-free languages".
|
I recommend Behle, Krebs, and Reifferscheid's recent work on extending
Eilenberg's fundamental theorem (that is, the correspondence between
pseudovarieties of monoids and varieties of languages) to non-regular
languages ([link](https://doi.org/10.1007/978-3-642-21493-6_6)). They point out previous works in this line (in particular,
Sakarovitch's on CFL).
|
9,944,954
|
Getting a segmentation fault for the following code. Please advise.
```
struct columns {
char* c_name;
char* c_type;
char* c_size;
};
int main(int argc, char* argv[])
{
int column_num = 3;
struct columns col[10];
//columns *col = (columns*) malloc (sizeof(columns) * column_num);
strcpy(col[0].c_name, "PSID");
strcpy(col[0].c_type, "INT");
strcpy(col[0].c_size, "4");
}
```
I am using 2 ways to allocate space for columns structure but continue to get a segmentation fault. Am I missing something?
|
2012/03/30
|
[
"https://Stackoverflow.com/questions/9944954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270042/"
] |
None of your pointers in the structure are actually initialized to anything. You have to give them a dimension, or dynamically allocate some memory for them.
|
You never allocate memory and initialize your `char*` pointers.
Like
```
strcpy(col[0].c_name=malloc(sizeof "PSID"),"PSID");
```
Of course, you need to check for errors and make it otherwise meaningful.
|
9,944,954
|
Getting a segmentation fault for the following code. Please advise.
```
struct columns {
char* c_name;
char* c_type;
char* c_size;
};
int main(int argc, char* argv[])
{
int column_num = 3;
struct columns col[10];
//columns *col = (columns*) malloc (sizeof(columns) * column_num);
strcpy(col[0].c_name, "PSID");
strcpy(col[0].c_type, "INT");
strcpy(col[0].c_size, "4");
}
```
I am using 2 ways to allocate space for columns structure but continue to get a segmentation fault. Am I missing something?
|
2012/03/30
|
[
"https://Stackoverflow.com/questions/9944954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270042/"
] |
None of your pointers in the structure are actually initialized to anything. You have to give them a dimension, or dynamically allocate some memory for them.
|
You allocate space for `columns` structure, but not for strings that you want to store. Your pointers (i.e. `c_name`) are left uninitialized, pointing to some random memory locations, thus you invoke undefined behavior right away.
|
9,944,954
|
Getting a segmentation fault for the following code. Please advise.
```
struct columns {
char* c_name;
char* c_type;
char* c_size;
};
int main(int argc, char* argv[])
{
int column_num = 3;
struct columns col[10];
//columns *col = (columns*) malloc (sizeof(columns) * column_num);
strcpy(col[0].c_name, "PSID");
strcpy(col[0].c_type, "INT");
strcpy(col[0].c_size, "4");
}
```
I am using 2 ways to allocate space for columns structure but continue to get a segmentation fault. Am I missing something?
|
2012/03/30
|
[
"https://Stackoverflow.com/questions/9944954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270042/"
] |
None of your pointers in the structure are actually initialized to anything. You have to give them a dimension, or dynamically allocate some memory for them.
|
`col[0].c_name` is a pointer, but doesn't point to any memory. That's why it will segfault.
Before copying anything in it allocate some memory using an array `char c_name[256];` or `malloc()`.
|
9,944,954
|
Getting a segmentation fault for the following code. Please advise.
```
struct columns {
char* c_name;
char* c_type;
char* c_size;
};
int main(int argc, char* argv[])
{
int column_num = 3;
struct columns col[10];
//columns *col = (columns*) malloc (sizeof(columns) * column_num);
strcpy(col[0].c_name, "PSID");
strcpy(col[0].c_type, "INT");
strcpy(col[0].c_size, "4");
}
```
I am using 2 ways to allocate space for columns structure but continue to get a segmentation fault. Am I missing something?
|
2012/03/30
|
[
"https://Stackoverflow.com/questions/9944954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270042/"
] |
`col[0].c_name` is a pointer, but doesn't point to any memory. That's why it will segfault.
Before copying anything in it allocate some memory using an array `char c_name[256];` or `malloc()`.
|
You never allocate memory and initialize your `char*` pointers.
Like
```
strcpy(col[0].c_name=malloc(sizeof "PSID"),"PSID");
```
Of course, you need to check for errors and make it otherwise meaningful.
|
9,944,954
|
Getting a segmentation fault for the following code. Please advise.
```
struct columns {
char* c_name;
char* c_type;
char* c_size;
};
int main(int argc, char* argv[])
{
int column_num = 3;
struct columns col[10];
//columns *col = (columns*) malloc (sizeof(columns) * column_num);
strcpy(col[0].c_name, "PSID");
strcpy(col[0].c_type, "INT");
strcpy(col[0].c_size, "4");
}
```
I am using 2 ways to allocate space for columns structure but continue to get a segmentation fault. Am I missing something?
|
2012/03/30
|
[
"https://Stackoverflow.com/questions/9944954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270042/"
] |
Try this (`strdup` takes care of storage but remember to free when you are done):
```
struct columns {
char* c_name;
char* c_type;
char* c_size;
};
int main(int argc, char* argv[])
{
int column_num = 3;
struct columns col[10];
col[0].c_name = strdup("PSID");
col[0].c_type = strdup("INT");
col[0].c_size = strdup("4");
return 0;
}
```
|
You never allocate memory and initialize your `char*` pointers.
Like
```
strcpy(col[0].c_name=malloc(sizeof "PSID"),"PSID");
```
Of course, you need to check for errors and make it otherwise meaningful.
|
9,944,954
|
Getting a segmentation fault for the following code. Please advise.
```
struct columns {
char* c_name;
char* c_type;
char* c_size;
};
int main(int argc, char* argv[])
{
int column_num = 3;
struct columns col[10];
//columns *col = (columns*) malloc (sizeof(columns) * column_num);
strcpy(col[0].c_name, "PSID");
strcpy(col[0].c_type, "INT");
strcpy(col[0].c_size, "4");
}
```
I am using 2 ways to allocate space for columns structure but continue to get a segmentation fault. Am I missing something?
|
2012/03/30
|
[
"https://Stackoverflow.com/questions/9944954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270042/"
] |
`col[0].c_name` is a pointer, but doesn't point to any memory. That's why it will segfault.
Before copying anything in it allocate some memory using an array `char c_name[256];` or `malloc()`.
|
You allocate space for `columns` structure, but not for strings that you want to store. Your pointers (i.e. `c_name`) are left uninitialized, pointing to some random memory locations, thus you invoke undefined behavior right away.
|
9,944,954
|
Getting a segmentation fault for the following code. Please advise.
```
struct columns {
char* c_name;
char* c_type;
char* c_size;
};
int main(int argc, char* argv[])
{
int column_num = 3;
struct columns col[10];
//columns *col = (columns*) malloc (sizeof(columns) * column_num);
strcpy(col[0].c_name, "PSID");
strcpy(col[0].c_type, "INT");
strcpy(col[0].c_size, "4");
}
```
I am using 2 ways to allocate space for columns structure but continue to get a segmentation fault. Am I missing something?
|
2012/03/30
|
[
"https://Stackoverflow.com/questions/9944954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270042/"
] |
Try this (`strdup` takes care of storage but remember to free when you are done):
```
struct columns {
char* c_name;
char* c_type;
char* c_size;
};
int main(int argc, char* argv[])
{
int column_num = 3;
struct columns col[10];
col[0].c_name = strdup("PSID");
col[0].c_type = strdup("INT");
col[0].c_size = strdup("4");
return 0;
}
```
|
You allocate space for `columns` structure, but not for strings that you want to store. Your pointers (i.e. `c_name`) are left uninitialized, pointing to some random memory locations, thus you invoke undefined behavior right away.
|
9,944,954
|
Getting a segmentation fault for the following code. Please advise.
```
struct columns {
char* c_name;
char* c_type;
char* c_size;
};
int main(int argc, char* argv[])
{
int column_num = 3;
struct columns col[10];
//columns *col = (columns*) malloc (sizeof(columns) * column_num);
strcpy(col[0].c_name, "PSID");
strcpy(col[0].c_type, "INT");
strcpy(col[0].c_size, "4");
}
```
I am using 2 ways to allocate space for columns structure but continue to get a segmentation fault. Am I missing something?
|
2012/03/30
|
[
"https://Stackoverflow.com/questions/9944954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270042/"
] |
Try this (`strdup` takes care of storage but remember to free when you are done):
```
struct columns {
char* c_name;
char* c_type;
char* c_size;
};
int main(int argc, char* argv[])
{
int column_num = 3;
struct columns col[10];
col[0].c_name = strdup("PSID");
col[0].c_type = strdup("INT");
col[0].c_size = strdup("4");
return 0;
}
```
|
`col[0].c_name` is a pointer, but doesn't point to any memory. That's why it will segfault.
Before copying anything in it allocate some memory using an array `char c_name[256];` or `malloc()`.
|
14,183,478
|
I would like to know if someone could explain me what happens exactly when we call a "render".
Let me introduce you my problem:
**This is my action:**
```
public function actionIndex()
{
$new_user = new CustomUser;
$new_person = new CustomPerson;
$tab_person = $this->getListPerson();
$this->render('index',array('tab'=>$tab_person,
'user'=>$new_user,
'person'=>$new_person));
}
```
**And this is my index view:**
```
.
.
.
</p> <br/>
<?php $this->renderPartial('person-form', array('person'=>$person,
'user' =>$user ));
?>
```
So my problem is that the loading page time is very long.
If I put a
>
> die("die");
>
>
>
just befor the render in my actionIndex or at the end of my view (after the renderPartial) the execution is very fast. I'll see "die"(and my index page if I put the statement at the end of it) after 0.3 second. But if I put it after my render or I don't put it, then my page is going to be loaded correctly but in 4-5 secondes.
So I think I didn't understand very well what happens after a render. I repeat if I stop the execution at the end of my view page it's very fast, but at the end of my action it's very slow. I thought about js and css, but after looking into I didn't see anything and Firebug shows me that these files are loaded very quickly.
And if I put the "die()" statment at the end of my layout main.php it's very fast as well.

So I know that render will show the page and wrap it in the layout but is there another thing which maybe could make the action very slow?
If anybody has an idea about my problem I would be very grateful.
Sorry if I did mistakes, English is not my mothertongue.
Thank you for reading me, have a good day :)
Michaël
|
2013/01/06
|
[
"https://Stackoverflow.com/questions/14183478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751045/"
] |
I cannot post formatted code in a comment, hence this new answer.
@sea\_gull is right - you need indeed to call the new DAO. The reason for it being this is a new type, so the Content Delivery storage mechanism won't know what to do with it. You have to call it somehow (potentially from a deployer module, but not necessarily). I used a unit test for calling it (just to provie that it works).
This is my sample unit test code I use to call the storage extension with:
```java
package com.tridion.extension.search.test;
import static org.junit.Assert.fail;
import java.util.Date;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.tridion.broker.StorageException;
import com.tridion.storage.StorageManagerFactory;
import com.tridion.storage.extension.search.PublishAction;
import com.tridion.storage.extension.search.PublishActionDAO;
/**
* @author Mihai Cadariu
*/
public class DAOTestCase {
private final Logger log = LoggerFactory.getLogger(DAOTestCase.class);
/**
* Test method for
* {@link com.tridion.storage.extension.search.PublishActionDAO#store(com.tridion.storage.search.PublishAction)}.
*/
@Test
public void testDAO() {
try {
log.debug("Get PublishActionDAO");
PublishActionDAO publishActionDAO = (PublishActionDAO) StorageManagerFactory.getDefaultDAO("PublishAction");
log.debug("Create new PublishAction bean");
PublishAction publishAction = new PublishAction();
publishAction.setAction("testStore action");
publishAction.setContent("testStore content");
publishAction.setTcmUri("testStore tcmUri");
publishAction.setUrl("testStore url");
publishAction.setCreationDate(new Date());
// Store
log.debug("Store bean");
publishAction = publishActionDAO.store(publishAction);
log.debug("Stored bean " + publishAction);
long id = publishAction.getId();
// FindByPrimaryKey
log.debug("Find PublishAction by PK=" + id);
publishAction = publishActionDAO.findByPrimaryKey(id);
log.debug("Found bean " + publishAction);
if (publishAction == null) {
log.error("Cannot find bean");
fail("TestFindByPrimaryKey failed: cannot retrieve object with pk " + id);
}
log.debug("Modifying bean content");
String content = publishAction.getContent();
content += "\r\nMODIFIED " + new Date();
publishAction.setContent(content);
// Update
log.debug("Update bean");
publishActionDAO.update(publishAction);
// Remove
log.debug("Remove bean");
publishActionDAO.remove(id);
} catch (StorageException se) {
log.debug("TestDAO failed: Exception occurred " + se);
fail("TestDAO failed: Exception occurred " + se);
se.printStackTrace();
}
}
}
```
If you call the code from a Deployer extension, this is the sample code I used:
```java
public class PageDeployModule extends PageDeploy {
private final Logger log = LoggerFactory.getLogger(PageDeployModule.class);
public PageDeployModule(Configuration config, Processor processor) throws ConfigurationException {
super(config, processor);
}
/**
* Process the page to be published
*/
@Override
protected void processPage(Page page, File pageFile) throws ProcessingException {
log.debug("Called processPage");
super.processPage(page, pageFile);
processItem(page);
}
private void processItem(Page page) {
log.debug("Called processItem");
try {
SearchConfiguration config = SearchConfiguration.getInstance();
String externalUrl = config.getExternalAccessUrl() + page.getURLPath();
String internalUrl = config.getInternalAccessUrl() + page.getURLPath();
PublishAction publishAction = new PublishAction();
publishAction.setAction("Publish");
publishAction.setTcmUri(page.getId().toString());
publishAction.setUrl(externalUrl);
publishAction.setContent(Utils.getPageContent(internalUrl));
PublishActionDAO publishActionDAO = (PublishActionDAO) StorageManagerFactory.getDefaultDAO("PublishAction");
publishAction = publishActionDAO.store(publishAction);
log.debug("Stored bean " + publishAction);
} catch (StorageException se) {
log.error("Exception occurred " + se);
}
}
}
```
You can use the same approach for the PageUndeploy, where you mark the action as "Unpublish".
|
The PublishAction type is not one of the default Tridion types which means it's not going to be used by default. In order for your DAO to be used you need to call it from somehow during the deployment process, usually from a Deployer Module. Can you check how and where are you using this PublishActionDAO?
|
14,183,478
|
I would like to know if someone could explain me what happens exactly when we call a "render".
Let me introduce you my problem:
**This is my action:**
```
public function actionIndex()
{
$new_user = new CustomUser;
$new_person = new CustomPerson;
$tab_person = $this->getListPerson();
$this->render('index',array('tab'=>$tab_person,
'user'=>$new_user,
'person'=>$new_person));
}
```
**And this is my index view:**
```
.
.
.
</p> <br/>
<?php $this->renderPartial('person-form', array('person'=>$person,
'user' =>$user ));
?>
```
So my problem is that the loading page time is very long.
If I put a
>
> die("die");
>
>
>
just befor the render in my actionIndex or at the end of my view (after the renderPartial) the execution is very fast. I'll see "die"(and my index page if I put the statement at the end of it) after 0.3 second. But if I put it after my render or I don't put it, then my page is going to be loaded correctly but in 4-5 secondes.
So I think I didn't understand very well what happens after a render. I repeat if I stop the execution at the end of my view page it's very fast, but at the end of my action it's very slow. I thought about js and css, but after looking into I didn't see anything and Firebug shows me that these files are loaded very quickly.
And if I put the "die()" statment at the end of my layout main.php it's very fast as well.

So I know that render will show the page and wrap it in the layout but is there another thing which maybe could make the action very slow?
If anybody has an idea about my problem I would be very grateful.
Sorry if I did mistakes, English is not my mothertongue.
Thank you for reading me, have a good day :)
Michaël
|
2013/01/06
|
[
"https://Stackoverflow.com/questions/14183478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751045/"
] |
The PublishAction type is not one of the default Tridion types which means it's not going to be used by default. In order for your DAO to be used you need to call it from somehow during the deployment process, usually from a Deployer Module. Can you check how and where are you using this PublishActionDAO?
|
More information needed:
1) What actually you are publishing while wanted to get invoked these methods - A Dynamic CP or a Page
2) From where you have received this code? I did not see any "create" method in your code...from where did you receive this code
In your previous post related to the "No named Bean loaded" error; Nuno has mentioned for one discussion on Tridion Forum (also given the forum link over there) started by Pankaj Gaur (i.e. me)...did you referred that?
Please note, If your Constructor is getting called, then there is no issue in your configuration at least; it is either the code or the mismatch in the type that you are publishing.
Also Note that, if you are trying to re-publish something without making any change, the Storage Extension might not get loaded (or the methods might not get invoked); so my suggestion during debuging, publsh always after making some changes in your presentation.
I hope it helps, else share the skeleton code along with the JAR file, and I will try t
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.