qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
30,003,986 | When I use the class `col-lg-6` on a `panel` in bootstrap, the `panel-heading` does not fill the width of the panel.
How can this be fixed?
```
<div class="container">
<div class="row">
<div class="panel panel-default col-lg-6">
<div class="panel-heading">Panel heading without title</div>
<div class="panel-body">
Panel content
</div>
</div>
</div>
</div>
``` | 2015/05/02 | [
"https://Stackoverflow.com/questions/30003986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4824107/"
] | Easy fix. Move the col-lg-6 to a div tag that surrounds the panel as such:
```
<div class="row">
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">Panel heading without title</div>
<div class="panel-body">
Panel content
</div>
</div>
</div>
</div>
``` | By giving `col-lg-6` you are giving the panel the width specified in `col-lg-6`.Instead put the panel markup inside the div containing `col-lg-6`.
Here is the [live working demo](http://jsfiddle.net/abhighosh18/6un4yftz/).
I am not sure if you want [this](http://jsfiddle.net/abhighosh18/6un4yftz/1/) too or not. |
150,779 | Problem 12 of section B of [this PDF file](http://univ.tifr.res.in/gs2015/Files/GS2013_QP_BIO.pdf) reads
>
> Two springs with spring constant k1 and k2 are attached to a body of mass (m) in two different
> configurations in 2 cases (A and B) as shown.
>
>
> 
>
>
> The mass rests on a surface with coefficient of
> friction between the mass and surface as $K$.
> The mass is moved to the right, parallel to the axis of the springs by a distance $d$ (from natural
> lengths of the springs) and is released. The time taken till the body comes to rest in case A is:
>
>
>
The given answer is equal to B but I get it to be less than B.
$$T= 2\pi \sqrt{\frac{m}{k}} $$
But I'm not sure how to incorporate effect of friction and mass.
In case of A, there is a $$ frictional force F = Kmg $$
But how do I relate this to T ?
I referred the pdf link above. I was trying to solve the question. The answer is
$$ T\_{a} = T\_{b} $$
An alernate way that I just figured is given below. Please clarify -
$For A $ ,$$ -k\_{1}d - k\_{2}d - Kmg = m\omega\_{a} ^2 x $$ $For B$,
$$ -k\_{1}d - k\_{2}d - Kmg = m\omega \_{b}^2 x $$
$$ \omega\_{a} = \omega\_{b} $$
$$ T=\frac{2Pi}{\omega} $$
$$ T\_a=T\_b $$
I am not a physics student. So I wanted to understand this conceptually and get the answer from the relevant equations. Also is my approach to the problem correct ? | 2014/12/06 | [
"https://physics.stackexchange.com/questions/150779",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/65482/"
] | You actually do not need to solve the equation at all in order to determine that, whatever the answer, it must be the same for A and B.
The only difference between A and B is the direction of k1. However if you look at $F=-kx$ is always a restoring force whose magnitude is proportional to the magnitude of the displacement from equilibrium. So the mass always experiences a restoring force of the same magnitude regardless of whether k1 is being compressed or stretched.
So in both cases the forces are the same and therefore the time must be the same also. | Since both springs are connected effectively in parallel, the both cases will have a same equation of motion. The equation of motion: $ma = F$
$$ \tag{1}
m \frac{d^2x}{dt^2} = -2kx - f\_d.
$$
The variable $x$ is the displacement for the oscillator displacement from its equilibrium position, $m$ the mass, $f\_d$ is the dragging or frictional force. It is not easy to model a constant static frictional force, because it is oscillation motion, the displacement $x$ changes sign regularly. It is more convinient to model a dragging force propotional to velocity, $f\_d = - b v$, the velocity will take care the sign of the force. Therefore, lets adopt this dragging force model:
$$ \tag{2}
m \frac{d^2x}{dt^2} = -2kx -b v;
$$
where $b$ is the damping coefficient. Write Eq. (2) in standard form of a second order differential equation:
$$ \tag{3}
m \frac{d^2x}{dt^2} + b \frac{dx}{dt} + 2kx= 0;
$$
Scale the equation by mass $m$, and define $\omega\_0 = \sqrt{\frac{2k}{m}}$
, $\gamma = \frac{b}{2m}$. We then write the equation as:
$$ \tag{4}
\frac{d^2x}{dt^2} + 2\gamma \frac{dx}{dt} + \omega\_0^2 x = 0;
$$
Assume that $\gamma \lt \omega\_0$ (the underdamping regime). The solution for Eq. (4):
$$
x(t) = e^{-\gamma t} \left\{ A \cos (\omega t) + B \sin(\omega t) \right\}.
$$
Where $\omega = \sqrt{\omega\_0^2 - \gamma^2}$, A and B are two constnats to be determined by the initial condition: $x(0)$ and $v(0)$, the initial displacement and initial velocity. |
84,810 | I'm thinking of installing Ubuntu (for the first time) on my internal hard drive to run as a primary OS on my Acer Aspire. Want to format my hard drive altogether and either run Ubuntu solely or alongside freshly reinstalled Windows 7 (it's that time again - windows is all bugged down).
Got a few questions though.
**1.** I've read that on installation of Ubuntu we get an option of
"use entire disk" - will this erase all the info on my hard drive (like formatting in DOS)?
**2.** My Windows installation files are pre-loaded on my hard drive. If i decide to go back to Windows (can't think of a reason why, but just in case :) will i still have Windows installation files if i use the option "use entire disk" installation for Ubuntu or is it safer to reinstall Windows (even though i won't be using it) and then run Ubuntu along side it?
**3.** I'm currently using 64 bit Windows 7. Should i install 64 bit Ubuntu?
I'm planning to use the latest 11.10 version of Ubuntu.
Thanks for all your answers in advance.
Vidrom | 2011/12/03 | [
"https://askubuntu.com/questions/84810",
"https://askubuntu.com",
"https://askubuntu.com/users/36441/"
] | >
> I've read that on installation of Ubuntu we get an option of "use entire disk" - will this erase all the info on my hard drive (like
> formatting in DOS)?
>
>
>
Yes.
>
> My Windows installation files are pre-loaded on my hard drive. If i decide to go back to Windows (can't think of a reason why, but just in
> case :) will i still have Windows installation files if i use the
> option "use entire disk" installation for Ubuntu or is it safer to
> reinstall Windows (even though i won't be using it) and then run
> Ubuntu along side it?
>
>
>
According to me, it is safer to keep Windows for now. You can remove later, once you gain confidence.
If you use "use entire disk", it will format whole drive, then you will not be able to reinstall Windows from preserved installation on the hard disk.
>
> I'm currently using 64 bit Windows 7. Should i install 64 bit Ubuntu?
>
>
>
Doesn't matter. You can use either of them. | 1. Yes, to the best of my knowledge (I almost never use these options), using the entire disk will, effectively, use the entire disk. This will entail re-partitioning the disk, so the data will probably be lost. Note however that the partitioner Ubuntu uses does not, in fact, wipe all the data off the drive (like Windows does, iirc) but just modifies the partition table.
2. I *think* Windows keeps those in a separate partition. In any case, using the entire disk will wipe that off and Windows will thus be forever lost (not that it'd be such a bad thing)! You will need to use a custom partition layout (there are many different possibilities, up to you) and keep that "hidden" Windows partition intact. Or you can re-install Windows first and install Ubuntu alongside if you feel safer that way.
3. As with Windows 64-bit, you have to be aware that some applications might not work, or be available, in 64-bit Linux. However, I find Linux generally has fewer problems of that kind (mostly because as software in open-source, it can easily be recompiled for 64-bit architectures), so I recommend 64-bit installs if your hardware supports it (here, it does). |
10,993,182 | Why does this work:
```
using namespace System;
using namespace System::Windows::Forms;
...
if( MessageBox::Show("Really do it?", "Are you sure?", System::Windows::Forms::MessageBoxButtons::YesNo) == System::Windows::Forms::DialogResult::Yes )
{
Console::WriteLine("Do it!");
}
```
..when this fails:
```
using namespace System;
using namespace System::Windows::Forms;
...
if( MessageBox::Show("Really do it?", "Are you sure?", System::Windows::Forms::MessageBoxButtons::YesNo) == DialogResult::Yes )
{
Console::WriteLine("Do it!");
}
```
...with the following error:
```
error C2039: 'Yes' : is not a member of 'System::Windows::Forms::Form::DialogResult'
```
I'm assuming Visual Studio is picking up DialogResult but I can't see where it's finding it? | 2012/06/12 | [
"https://Stackoverflow.com/questions/10993182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15369/"
] | It's valid, but you'll find that one bean is overridden by the other. You'll see this in the logs as
```none
Overriding bean definition for...
```
This behaviour allows you to override previously supplied bean definitions. It affects the static assembly of your app, and doesn't relate to threading/clustering as suggested in your question.
Note that the `DefaultListableBeanFactory` allows you to configure this behaviour via [setAllowBeanDefinitionOverriding()](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/beans/factory/support/DefaultListableBeanFactory.html#setAllowBeanDefinitionOverriding%28boolean%29) | This is valid and useful especially when you try to change the implementation of a third party bean (I mean, where you are not allowed to change the implementation of a bean) and Where you need to provide/configure some extra (merge) properties for the bean.
The overriding of the bean depends upon the order of the xmls you provide to build the `ApplicationContext` through web.xml or stand-alone. The latest bean definition will win the game. |
69,090,111 | I want to show data from a database that is about a specific user. I have a table when I fetch data from db.
I can add user on my admin panel, but I want for each user to show specific data. I`m building a CRM. And users send data to MYSQL db.
Now I fetch this data and based on username I want to create and user witch will be able to show just his data with his username. How can I do this in Laravel?
This is the migration.
```
public function up()
{
//
Schema::create('members', function (Blueprint $table) {
$table->increments('id');
$table->string('user')->nullable();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('phone_number')->nullable();
$table->timestamps();
});
}
```
This is the controller how I show db table on blade.
```
function index(Request $request) {
// fetch data from members table
$members = Member::paginate(6);
return view('list');
}
```
I use role to hide some data from user. | 2021/09/07 | [
"https://Stackoverflow.com/questions/69090111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16508951/"
] | Try this,
You can use the functional way instead.
```js
const inAscOrder = arr => arr.slice(1).every((elem,i) => elem > arr[i]);
console.log(inAscOrder([1,2,5]));
``` | For every element in the array, return true if it's the first element or it's greater than the previous element.
```js
const isAscending = (arr) => arr.every((el, i, arr) => i === 0 || el > arr[i - 1]);
console.log(isAscending([1, 2, 4, 7, 19]));
console.log(isAscending([1, 2, 3, 4, 5]));
console.log(isAscending([1, 6, 10, 18, 2, 4, 20]));
console.log(!isAscending([9, 8, 7, 6, 5, 4, 3, 2, 1]));
``` |
70,329,045 | So, when I request my webservice for getting download a zip file, it downloads the file content secretely and all of a sudden, the file appears in the download task bar but already downloaded full (100%)
Using the following angular method:
```js
const endpoint = "http://localhost:8080/download/zip"
this.http.get<Blop>(endpoint, {headers: httpHeaders, responseType: 'blob', reportProgress: true })
```
So here is how I am subscribing:
```js
this.http.get<Blop>(endpoint, {headers: httpHeaders, responseType: 'blob', reportProgress: true }).subscribe({
next: data => {
console.log('blocking or not');
const blob = new Blob([data as any], { type: 'application/zip' });
window.location.href = URL.createObjectURL(blob);
}
})
```
So I noticed my `console.log(...)` isn't called until the end of the download, so I suppose that the browser-ui can't detect the download until it reaches `window.location.href`.
How to force the download to be shown in the download task bar before the end of the transfert, and watch the download progress in the browser? I coudld not find anything related to async blop or something like that.
PS: my backend is serving a stream of data, so the backend is not the problem. When calling my api directly through the browser, we can see the download progress in the download task bar. Still, if you guys are interested, this is the snippet (spring-boot)
```kotlin
@GetMapping("/download/zip")
fun download(response: HttpServletResponse): StreamingResponseBody {
val file = downloads.download("launcher")
response.contentType = "application/zip"
response.setHeader(
"Content-Disposition",
"attachment;filename=sample.zip"
)
response.setContentLengthLong(file.length())
return StreamingResponseBody { outputStream: OutputStream ->
var bytesRead: Int
val buffer = ByteArray(2048)
val inputStream: InputStream = file.inputStream()
while (inputStream.read(buffer).also { bytesRead = it } != -1) {
outputStream.write(buffer, 0, bytesRead)
}
}
}
``` | 2021/12/13 | [
"https://Stackoverflow.com/questions/70329045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3552082/"
] | For download you have 2 ways:
1. http.get + msSaveOrOpenBlob (if its defined)/createObjectURL
* you have full control over request, process and errors. E.g. u can cancel request, add additional headers, etc.
* download remains in your app flow, e.g. F5 will cancel it.
2. create hidden download link and click it programatically
* you cannot add headers, you cannot show progress/errors in simple way (there are some tricks involving additional cookies to set by BE)
* Its strated as separate process, e.g. you can close your app tab or whatever.
There seems to be no chance of mixing these 2 approaches and in general I would say 1st one is more modern and preferable for small files, however if you are not happy with it try 2nd one (<https://stackoverflow.com/a/49917066/4019404>):
```
function download(url) {
const a = document.createElement('a')
a.href = url
a.download = url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
``` | You can simply use this package
```
npm i ngx-filesaver
```
and
```
constructor(private _http: Http, private _FileSaverService: FileSaverService) {
}
onSave() {
this._http.get('yourfile.png', {
responseType: ResponseContentType.Blob // This must be a Blob type
}).subscribe(res => {
this._FileSaverService.save((<any>res)._body, fileName);
});
}
```
complete doc here [ngx file saver](https://www.npmjs.com/package/ngx-filesaver)
and also [file saver.js](https://www.npmjs.com/package/file-saver) |
72,433,152 | While trying to read and write some `unsinged long long int` values to and from a file i encountered a problem when deserializing the values. The boiled down problem can be reproduced with the following code. Only sometimes bitshifting more than 32 bit result in value with leading ones. Why is that?
```
int main() {
unsigned char* myBuffer = new unsigned char[16] {
(unsigned char)0xb0,
(unsigned char)0xf7,
(unsigned char)0x80,
(unsigned char)0x01,
(unsigned char)0x00,
(unsigned char)0x00,
(unsigned char)0x00,
(unsigned char)0x00,
(unsigned char)0xf0,
(unsigned char)0xc0,
(unsigned char)0x49,
(unsigned char)0x89,
(unsigned char)0x29,
(unsigned char)0x00,
(unsigned char)0x00,
(unsigned char)0x00
};
unsigned long long int firstValue = 0;
unsigned long long int secondValue = 0;
for (int i = 0; i < 8; i++) {
firstValue |= myBuffer[i] << (8 * i);
secondValue |= myBuffer[i + 8] << (8 * i);
std::cout << "first buffer value " << std::hex << (int)myBuffer[i]
<< " second buffer value " << std::hex << (int)myBuffer[i + 8]
<< " first value " << std::hex << firstValue
<< " second value " << secondValue << endl;
}
return 0;
}
```
Output
------
```
first buffer value b0 second buffer value f0 first value b0 second value f0
first buffer value f7 second buffer value c0 first value f7b0 second value c0f0
first buffer value 80 second buffer value 49 first value 80f7b0 second value 49c0f0
first buffer value 1 second buffer value 89 first value 180f7b0 second value ffffffff8949c0f0
first buffer value 0 second buffer value 29 first value 180f7b0 second value ffffffff8949c0f9
first buffer value 0 second buffer value 0 first value 180f7b0 second value ffffffff8949c0f9
first buffer value 0 second buffer value 0 first value 180f7b0 second value ffffffff8949c0f9
first buffer value 0 second buffer value 0 first value 180f7b0 second value ffffffff8949c0f9
```
Solution
--------
I know how to fix this issue. By casting the `unsigned char`'s to an `unsigned long long int` before bitshifting everything works well:
```
secondValue |= ((unsigned long long int)myBuffer[i + 8]) << (8 * i);
```
I still just want to know why this is happening only sometimes. | 2022/05/30 | [
"https://Stackoverflow.com/questions/72433152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7815139/"
] | First, you need to get value of `p`
```
let countVal = document.getElementById('wordCount');
```
Then, make an array from it by using split(separator)
```
let countArr = countVal.split(" ")
```
Finally, display it in your js
```
document.getElementById('someId').textContent = countArr.length;
``` | you have same value for class and id in html , change it if possible
like this
```
<span class="Word" id="word">Words Number</span> <p class="Any" id="any">Here have some text which I want to count</p>
```
Then use this jQuery code
```
$(document).ready(function(){
var myString = $("#any").text();
var countWord = myString.split(' ').length;
});
``` |
34,313,391 | I have a blogger blog and I have already successfully had the domain set to a subdomain of my website e.g <http://blog.jthink.net>
But how do I actually embed the blog onto my website so that it has same header and footer as my main website ( <http://www.jthink.net> ) so it's more like the way they have done it [here](http://blog.beatunes.com/)
Is it even possible with blogger? | 2015/12/16 | [
"https://Stackoverflow.com/questions/34313391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1480018/"
] | I'm a bit late to the party but If you want an alternative to straight out embedding your blog you could use the the [Blogger api](https://developers.google.com/blogger/)?
To my mind that would be the best solution. | iframes are best for this. Most browsers support them.
Maybe you could use adobe business catalyst page templates? |
105,065 | I have two eyes and one mouth,
both my eyes are hallowed out.
My mouth won't let me talk, yet
my eyes will have you shocked.
For though air is what's inside,
I'm one reason why many died.
What am I, that causes doom?
Here's a hint, *I'm in your room.* | 2020/11/21 | [
"https://puzzling.stackexchange.com/questions/105065",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/70545/"
] | >
> Are you referring to a plug socket?
>
>
>
I have two eyes and one mouth,
>
> A plug socket has three holes at least in some places. Up side down it looks like two eyes and a mouth
>
>
>
both my eyes are hallowed out.
>
> They are the two holes at the bottom
>
>
>
My mouth won't let me talk, yet
my eyes will have you shocked.
>
> The electric current comes out of the two holes bottom holes only not the top.
>
>
>
For though air is what's inside,
>
> Again they are holes...
>
>
>
I'm one reason why many died.
>
> Many accidents are caused by electric shocks from these appliances.
>
>
>
What am I, that causes doom?
Here's a hint, I'm in your room.
>
> It is in my room.
>
>
> | Is the answer:
>
> An electric socket
>
>
>
my eyes will have you shocked.
>
> its speaking of literal current shock and not the feeling / emotion.
>
>
>
I'm one reason why many died.
What am I, that causes doom?
Here's a hint, I'm in your room.
>
> Electric shock is fairly common reason of death and sockets are present in our room
>
>
> |
1,852,299 | I wanna print the value of b[FFFC] like below,
```
short var = 0xFFFC;
printf("%d\n", b[var]);
```
But it actually print the value of b[FFFF FFFC].
Why does it happen ?
My computer is operated by Windows XP in 32-bit architecture. | 2009/12/05 | [
"https://Stackoverflow.com/questions/1852299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225413/"
] | `short` is a signed type. It's 16 bits on your implementation. 0xFFFC represents the integer constant 65,532, but when converted to a 16 bit signed value, this is resulting in -4.
So, your line `short var = 0xFFFC;` sets var to -4 (on your implementation).
0xFFFFFFFC is a 32 bit representation of -4. All that's happening is that your value is being converted from one type to a larger type, in order to use it as an array index. It retains its value, which is -4.
If you actually want to access the 65,533rd element of your array, then you should either:
* use a larger type for `var`. `int` will suffice on 32 bit Windows, but in general `size_t` is an unsigned type which is guaranteed big enough for non-negative array indexes.
* use an `unsigned short`, which *just* gives you enough room for this example, but will go wrong if you want to get another 4 steps forward. | use **%hx** or %hd instead to indicate that you have a short variable, e.g:
```
printf("short hex: %hx\n", var); /* tell printf that var is short and print out as hex */
```
**EDIT**: Uups, I got the question wrong. It was not about printf() as I thought. So this answer might be a little bit OT.
**New**: Because you are using **var** as an index to an array you should declare it as **unsigned short** (instead of short):
```
unsigned short var = 0xFFFC;
printf("%d\n", b[var]);
```
The 'short var' could be interpreted as a negative number.
To be more precise:
You are "underflowing" into the negative value range: Values in the range from 0x0000 upto 0x7FFF will be OK. But values from 0x8000 upto 0xFFFF will be negative.
Here are some examples of *var* used as an index to array b[]:
```
short var=0x0000;; // leads to b[0] => OK
short var=0x0001; // leads to b[1] => OK
short var=0x7FFF; // leads to b[32767] => OK
short var=0x8000; // leads to b[-32768] => Wrong
short var=0xFFFC; // leads to b[-4] => Wrong
short var=32767; // leads to the same as b[0x7FFF] => OK
short var=32768; // compile warning or error => overflow into 32bit range
``` |
42,874,927 | I use Thymeleaf 3.0.3 with Spring Boot 1.5.1 and STS Bundle 3.8.1. My Hungarian non-ASCII characters are not shown properly.
I have the following configuration in the application.properties file:
```
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=utf-8
```
These are anyway the defaults but I wanted to be sure that my Thymeleaf is configured properly.
My web page charset is also utf-8 and my text editor in Eclipse as well. So how can it happen that I see "�r�l�k, hogy �jra itt vagy Roland" instead of the expected: "Örülök, hogy újra itt vagy Roland"? | 2017/03/18 | [
"https://Stackoverflow.com/questions/42874927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6184153/"
] | I had same problem. I have found solution, that workerd for me:
You need to save the file as Encode in UTF-8 without BOM. It works for me.
Steps:
1. Edit the file in notepad++ and have a copy of these content in one more file.
2. Go to menu Encoding and choose Encode in UTF-8 without BOM.
3. If your file shows some char like xE9 etc., then copy original content to your file and save.
4. Close and re-open the file and check the encoding remains same as "Encode in UTF-8 without BOM".
If encoding default to Encode in AnsII that means you had few chars which are like "xE9" and your file didn't saved as Encode in UTF-8 without BOM.
5. If encode remains "Encode in UTF-8 without BOM".
6. Run your application and you could able to see the translated content.
<http://forum.thymeleaf.org/UTF-8-encoding-problem-using-messages-properties-in-Spring-Boot-with-Thymeleaf-td4030339.html> | You need to set encoding in the viewResolver
```
@Bean
public ThymeleafViewResolver thymeleafViewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setCharacterEncoding("UTF-8");
return viewResolver;
}
``` |
4,604,247 | We are using a website with some forms that have Javascript layover images over its radio buttons and checkboxes. These work well on IE7 upwards and Firefox, Safari etc. on Windows and Mac. The images layover the radio buttons/checkboxes using special javascript from Prototype and a plugin called "Protocheck" which we downloaded back in 2008 to implement on the site.
The problem is, our client has just reported:
"A customer has contacted us trying to order on an ipad, he is unable to select a source code (radio option) on his ipad and cant get past the page because of this."
"Also i attempted a transaction on my iphone - i selected a foot size but then it would not let me select a calf width and therefore could not complete the sale"
As an example see:
<http://www.duoboots.com/products/bo...-taupe_leather/>
(please see select your size and select your calf width radio buttons)
Questions, help needed:
1. We are downloading simulators to try (Phonegap to start for the Iphone) but can I just check if anyone knows about this issue or has experienced this before?
2. Does anybody know of any methods to simulate ipad and iphone on my pc or Mac? Or any good applications for that?(since i do not have an ipod or ipad) --- especially ipad since I've not heard any solid recommendations for simulators yet
Thanks in advance,
Isuru | 2011/01/05 | [
"https://Stackoverflow.com/questions/4604247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545697/"
] | You can download Xcode, which comes with an iPhone and iPad simulator. You could then run the simulator and load your website in Safari on either of the devices to test your customer issues.
Xcode Download:
<http://developer.apple.com/technologies/xcode.html> | I have found the solution for this. Posting so everyone will know. In Iphone and I pad you will need to have an "OnClick" event even if you do not need one. Because otherwise if you are using something like I have described above (protocheck) it will not take that elemet as a clickeble one. So solutin is having a fake "OnClick" so I pod & Pad detects it as a click able element. :) |
7,670,227 | I used to work on MonoDevelop 2.6 with MonoTouch 4.2. It's cool and everything is fine.
Later, when MD 2.8 came out, I installed it with MD 2.6 side by side (just renamed MD 2.6 as MonoDevelop 2.6). But I can not load iOS projects. And, there is no iOS project templates showing up in new solution window.
I tried to uninstall Mono Framework, MD 2.6, 2.8 and MonoTouch and reinstall Mono Framework 2.10, MD 2.8 and MonoTouch 4.2, but still, no iOS project templates.
So, anyone can help?
Thanks.
EDIT: According to <http://bugzilla.xamarin.com/show_bug.cgi?id=1413>, my problem would be related to case-sensitive issues. And it should be fixed in MD 2.8.1. | 2011/10/06 | [
"https://Stackoverflow.com/questions/7670227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/620138/"
] | Using the `shape` and `size` works well when you define a two dimension array, but when you define a simple array, these methods do not work
For example :
```
K = np.array([0,2,0])
```
`K.shape[1]` and `numpy.size(K,1)`
produce an error in python :
```
Traceback (most recent call last):
File "<ipython-input-46-e09d33390b10>", line 1, in <module>
K.shape[1]
IndexError: tuple index out of range
```
**Solution :**
It solved by adding a simple option to array,
```
K = np.array([0,2,0],ndmin = 2)
K.shape[0]
Out[56]: 1
K.shape[1]
Out[57]: 3
np.size(K,0)
Out[58]: 1
np.size(K,1)
Out[59]: 3
```
More information :
<https://codewithkazem.com/array-shape1-indexerror-tuple-index-out-of-range/> | 
this is a simple example, and you can follow it.By the way,the last statement should be corrected as "print b.shape[0]" |
35,664,473 | I'm trying to add adverts to my UWP app so I thought I'd follow up the walkthrough provided by Microsoft i.e. [Windows 10 Advertising SDK Walkthrough](https://msdn.microsoft.com/library/mt125365(v=msads.100).aspx), but I can't get it to work.
I've followed the steps i.e.
1. Added a reference to `Microsoft Advertising SDK for XAML` (V10.0.0.0)
2. Made sure the `Platform` is `x86`
3. Added the namespace to my page: `xmlns:UI="using:Microsoft.Advertising.WinRT.UI"`
4. Added the following XAML to my `<Grid>`:
```
<UI:AdControl ApplicationId="d25517cb-12d4-4699-8bdc-52040c712cab"
AdUnitId="10043107"
HorizontalAlignment="Left"
Height="250"
VerticalAlignment="Top"
Width="250"
ErrorOccurred="AdControl_ErrorOccurred" />
```
But it doesn't do anything. No ad displayed, no rectangle, nothing!!
As you can see from the above XAML, I've added the ErrorOccured event to see if I could spot anything else, and it does get triggered and I get the following error:
* ErrorCode: NoAdAvailable
* ErrorMessage: No Ad Available
Any ideas how to resolve this? It seems ridiculous that something that's suppose to be that simple is turning into something complicated in order to get it to work!
Thanks.
**UPDATE:**
I've just noticed in my Reference dialog box that I have the following entries:
1. Microsoft Advertising SDK for XAML
* Version: 10.0
* Targets: UAP 10.0.10240.0
* SDK Dependencies: Microsoft.VCLibs, Version=14.0
2. Microsoft Advertising Universal SDK
* Version: 1.0
* Targets: UAP 10.0.0.0
* SDK Dependencies: Microsoft.Advertising.Xaml, Version=10.0
Which one should I use? I will try both an update this post.
--- | 2016/02/27 | [
"https://Stackoverflow.com/questions/35664473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815847/"
] | For UWP app, please install Microsoft Universal Ad Client SDK(<https://visualstudiogallery.msdn.microsoft.com/401703a0-263e-4949-8f0f-738305d6ef4b>) and use AdMediatorControl.
References:
* [Install the Universal Ad Client SDK](https://msdn.microsoft.com/en-us/windows/uwp/monetize/install-the-microsoft-universal-ad-client-sdk)
* [Add and use the ad mediator control](https://msdn.microsoft.com/en-us/windows/uwp/monetize/add-and-use-the-ad-mediator-control)
>
> In a Universal Windows Platform (UWP) project, use the AdMediatorControl under the AdMediator Universal section.
>
>
> After you’ve added all the controls you’d like, you’re ready to configure the ad networks through Connected Services.
>
>
>
Check my sample: <https://github.com/Myfreedom614/UWP-Samples/tree/master/AdClientUWPApp> | It says on the walkthrough that it's a preview document, probably not official sdk release. Try this one [New advertising features and walkthrough of using Microsoft ads and mediation](https://blogs.windows.com/buildingapps/2015/10/08/new-advertising-features-and-walkthrough-of-using-microsoft-ads-and-mediation/) |
56,906,685 | I test the app on a physical device (Samsung Galaxy J4+). I open it and enter data (destined for *SharedPreferences*). Then ...
*SharedPreferences* **do not load** when tapping the app icon after having made the app UI disappear using the "<" button at the bottom of my Samsung screen, but they **do load** when tapping the app icon after having made the app UI disappear using the "|||" or "O" button at the bottom of my Samsung screen. The latter leads me to conclude that the saving and loading method both work properly.
The **loading method** (importSavedData()) is embedded alright in the method onCreate(), inside the MainActivity class. There is no other *activity life cycle method* [onStart(), on Resume (), onPause () etc.] included in the app.
The **saving method** (saveData()) is invoked each time data is entered into the app (happens by pressing buttons), so I didn't deem it necessary to include that method in an onStop() or onDestroy() method. I did try switching between editor.apply() en editor.commit(), but to no avail.
```
public class MainActivity extends AppCompatActivity {
int winnerA;
int winnerB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
importSavedData();
}
public void importSavedData() {
SharedPreferences savedData = getSharedPreferences("savedData",
Context.MODE_PRIVATE);
winnerA = savedData.getInt("winnerA_SP", 0);
winnerB = savedData.getInt("winnerB_SP", 0);
}
public void saveData(){
SharedPreferences savedData = getSharedPreferences("savedData",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = savedData.edit();
editor.putInt("winnerA_SP", winnerA);
editor.putInt("winnerB_SP", winnerB);
editor.apply();
}
/* saveData() is executed when the user has changed
the value of winnerA or winnerB by pressing one of the buttons in the
activity. */
}
``` | 2019/07/05 | [
"https://Stackoverflow.com/questions/56906685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841607/"
] | If I'm not wrong, what is going on is that at the moment you are importing work func from bar.py, the default argument is executed, and doesn't matter if you change the value later, because the default argument was already "declared" on the import, since the default arguments are evaluated just once | I think when the the compiler sees this:
```
def work(val=global_val[0])
```
the default value of val will be what global\_val[0] were at that time. Setting it to something different later on will not change the function definition, i.e. set the val variable to 0 (which is the first element of global\_val) if no argument for that parameter is supplied.
Try something like this instead:
```
def work(val=None):
if not val:
global global_val
val = global_val[0]
```
Here you set val to something known that you can catch, None in this case, and then set the proper value. Using the keyword global makes sure you use the variable from the global namespace. This will sett the correct value of global\_val if it's changed later on after the function definition is compiled. |
21,095,366 | I'm to post to a table in my localhosted MySQL database, but when i run the script the page stays white but there is nothing posted in the table. I'll add my code for clarification. Im using USBWebserver to host the apache and MySQL server on.
```
<?php
//connectie leggen met input data
//$con =
//variablen input invullen (bijv $gebruikeragenda = $_POST['gebruikeragenda'];
$gebruikeragenda = 'Testafspraak'; //hierin specifieren op welke account dit evenement geplaatst moet worden
$tegebruikenagenda = ''; //hierin specifieren we de agenda waarin het evenement geplaatst moet worden
$begintijd = '2014-01-13 15:30:00'; //begintijd specifieren
$eindtijd = '2014-01-13 16:30:00'; //eindtijd specifieren
$medeaanwezige = ''; //emailadressen van andere aanwezige tijdens dit evenement
//connectie leggen met MySQL(aanpasbaarnaar SQLite indien nodig)
$con=mysqli_connect("localhost:3307","root","usbw","baikal");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//input van hierboven ombouwen en in de database van Baikal bouwen
$calendardata = $gebruikeragenda;
$uri = 'default';
$lastmodified = $begintijd; //laatst gemodificeerd
$calenderid = '1'; //het id van de agenda waarbij de event hoort
$etag = 'niks';
$size = '200'; //grootte
$componenttype = ''; //wordt er gebruik gemaakt van een notificatie, voer hier dan VTODO in
$firstoccurence = $begintijd; //begintijd van evenement
$lastoccurence = $eindtijd; //eindtijd van evenement
//gegevens in de database plaatsen
mysqli_query($con,"INSERT INTO calendarobjects (calendardata, uri, calendarid, lastmodified, etag, size, componenttype, firstoccurence, lastoccurence) VALUES (".$calendardata.", ".$uri.",
".$lastmodified.",".$etag.",".$size.",".$componenttype.",".$firstoccurence.",".$lastoccurence.")");
mysqli_close($con);
``` | 2014/01/13 | [
"https://Stackoverflow.com/questions/21095366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2960417/"
] | Your columns and values do not match. You are attempting to insert 8 values into 9 columns.
Specifically, it appears you are missing a `calendarid`.
Second, your strings need to be wrapped in quotes.
Finally, you are vulnerable to SQL injections. Consider using [prepared](http://www.php.net/manual/en/mysqli.prepare.php) statements. | You need to use quotation for values.
You have 9 attributes and 8 values. You have missed one value in your query.Set another value in your query and
**Try this:**
```
<?php
//connectie leggen met input data
//$con =
//variablen input invullen (bijv $gebruikeragenda = $_POST['gebruikeragenda'];
$gebruikeragenda = 'Testafspraak'; //hierin specifieren op welke account dit evenement geplaatst moet worden
$tegebruikenagenda = ''; //hierin specifieren we de agenda waarin het evenement geplaatst moet worden
$begintijd = '2014-01-13 15:30:00'; //begintijd specifieren
$eindtijd = '2014-01-13 16:30:00'; //eindtijd specifieren
$medeaanwezige = ''; //emailadressen van andere aanwezige tijdens dit evenement
//connectie leggen met MySQL(aanpasbaarnaar SQLite indien nodig)
$con=mysqli_connect("localhost:3307","root","usbw","baikal");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//input van hierboven ombouwen en in de database van Baikal bouwen
$calendardata = $gebruikeragenda;
$uri = 'default';
$lastmodified = $begintijd; //laatst gemodificeerd
$calenderid = '1'; //het id van de agenda waarbij de event hoort
$etag = 'niks';
$size = '200'; //grootte
$componenttype = ''; //wordt er gebruik gemaakt van een notificatie, voer hier dan VTODO in
$firstoccurence = $begintijd; //begintijd van evenement
$lastoccurence = $eindtijd; //eindtijd van evenement
$sql = "INSERT INTO calendarobjects (calendardata, uri, calendarid, lastmodified, etag, size, componenttype, firstoccurence, lastoccurence) VALUES ('$calendardata', '$uri',
'$lastmodified','$etag','$size','$componenttype','$firstoccurence','$lastoccurence')";
//gegevens in de database plaatsen
if( mysqli_query($con,$sql)){
echo "successully inserted";
}else{
echo "something wrong";
}
mysqli_close($con);
``` |
34,428,891 | A very quick question - does it matter at all for the optimal performance whether the type of the script is specified before or after the source path?
```
<script type="text/javascript" src="/myjavascript.js"></script>
```
vs
```
<script src="/myjavascript.js" type="text/javascript"></script>
```
Similarly, would it matter if ***rel="stylesheet"*** and ***type="text/css"*** are specified before or after ***href*** for css files? | 2015/12/23 | [
"https://Stackoverflow.com/questions/34428891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4330769/"
] | it doesn't matter which comes first and which comes last. what matters is that the src attribute links to the correct location of the script source.
for formality (and because i grew with it) i always add a type = "text/javascript":
```
<script type = "text/javascript" src = "{link-to-js-file}"></script>
```
but as far as HTML5 is concerned, you are no longer required to put "type='text/javascript'" beforehand. | It doesn't matter.
But for HTML5, we don't require to specify type="text/javascript" |
196,105 | Reading the comments to this [answer](https://softwareengineering.stackexchange.com/a/196028/16898), specifically:
>
> Just because you can't write a test doesn't mean it's not broken. Undefined behaviour which usually happens to work as expected (C and C++ are full of that), race conditions, potential reordering due to a weak memory model... – ***CodesInChaos*** 7 hours ago
>
>
>
>
> @CodesInChaos if it cant be reproduced then the code written to 'fix' cant be tested either. And putting untested code into live is a worse crime in my opinion – ***RhysW*** 5 hours ago
>
>
>
...has me wondering if there are any good general ways to consistently trigger very infrequently occurring in production problems caused by race conditions in test case. | 2013/04/25 | [
"https://softwareengineering.stackexchange.com/questions/196105",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/16898/"
] | After having been in this crazy business since about 1978, having spent almost all of that time in embedded real-time computing, working multitasking, multithreaded, multi-whatever systems, sometimes with multiple physical processors, having chased more than my fair share of race conditions, my considered opinion is that the answer to your question is quite simple.
No.
There's no good general way to trigger a race condition in testing.
Your ONLY hope is to design them completely out of your system.
When and if you find that someone else has stuffed one in, you should stake him out an anthill, and then redesign to eliminate it. After you have designed his faux pas (pronounced f\*\*\*up) out of your system, you can go release him from the ants. (If the ants have already consumed him, leaving only bones, put up a sign saying "This is what happens to people who put race conditions into XYZ project!" and LEAVE HIM THERE.) | The best tool I know for these sort of problems is an extension of Valgrind called [Helgrind](http://valgrind.org/docs/manual/hg-manual.html).
Basically Valgrind simulates a virtual processor and runs your binary (unmodified) on top of it, so it can check every single access to memory. Using that framework, Helgrind watch system calls to infer when an access to a shared variable is not properly protected by a mutual exclusion mechanism. That way it can detect a theorical race condition even if it has not actually happened.
Intel sells a very similar tool called [Intel Inspector](http://software.intel.com/en-us/intel-inspector-xe/).
These tools give great results but your program will be considerably slower during analysis. |
10,963,710 | **Problem:**
I am stuck in figuring out how to add a string in a variable to a number of different strings using PHP.
**Variable:**
```
$insert = 'icon-white';
```
**Strings are in a variable called $hyperlink:**
```
$hyperlink = '<i class="icon-home"></i>';
```
**Desired output:**
```
<i class="icon-home icon-white"></i>
```
Any recommendations are welcome, and thanks in advance. | 2012/06/09 | [
"https://Stackoverflow.com/questions/10963710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1045160/"
] | This is how to use `preg_replace()` php function to fit your needs :
```
$ php -a
Interactive shell
php > $oldvar = '<i class="icon-home"></i>';
php > $newvar = preg_replace('/(.*?".*?)"(.*)/', '\1 icon-white"\2 ', $oldvar);
php > echo $newvar;
<i class="icon-home icon-white"></i>
``` | When rendering the output, you could do;
```
<i class="icon-home <?= $insert ?>"></i>
```
if you don't want it to be conditional.
If you have a variable;
```
$i = '<i class="icon-home"></i>';
```
you can do;
```
$i = '<i class="icon-home ${insert}"></i>';
``` |
14 | Is there any written proof/documentation that Robin Hood ever existed? Did he ever get arrested and got his name written in the prison books or something like that? | 2011/10/11 | [
"https://history.stackexchange.com/questions/14",
"https://history.stackexchange.com",
"https://history.stackexchange.com/users/16/"
] | * The surname 'Hood' implied where the individual was from. For all purposes, there were many people with the last name. The name Robin Hood is accounted as not an uncommon name in the middle ages.
* There is a corpus of [evidence](http://www.bbc.co.uk/history/british/middle_ages/robin_01.shtml) that there were outlaw stories circulating about a Robin Hood during the reign of King John.
* However, there are cases of multiple outlaws taking on the pseudonym Robin Hood during the 13th and 14th century.
So yes, there were Robin Hoods. But not precisely the one you're thinking of. | A good source on the historical Robin Hood is James Clarke Holt's book [Robin Hood](https://www.amazon.co.uk/Robin-Hood-J-C-Holt/dp/0500275416). Within, you will learn that there was no single one Robin Hood, but a corpus of ballads and stories that may have some basis in reality. |
6,102,190 | I have the below code which prints out lines of text as long as the lines aren't empty:
```
$textChunk = wordwrap($value, 35, "\n");
foreach(explode("\n", $textChunk) as $textLine)
{
if ($textLine!=='')
{
$page->drawText(strip_tags(ltrim($textLine)), 75, $line, 'UTF-8');
$line -=14;
}
}
```
I would like to edit it so that it also doesn't print the line if it begins with 'T:'
Any ideas? | 2011/05/23 | [
"https://Stackoverflow.com/questions/6102190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239768/"
] | Use [substr](http://php.net/substr) to check the first two characters:
```
if ($textLine !== '' && substr($textline, 0, 2) !== 'T:')
``` | ```
$textChunk = wordwrap($value, 35, "\n");
foreach(array_filter(explode("\n", $textChunk)) as $textLine)
{
if (strncmp('T:', $textLine,2) !== 0)
{
$page->drawText(strip_tags(ltrim($textLine)), 75, $line, 'UTF-8');
$line -=14;
}
}
```
At all `strncmp()` is slightly faster than `substr()`. |
400,918 | I have an Apache Proxy setup in front of an HTTP daemon process that serves a Sinatra web application with the following Directives (which work great)
```
ProxyPass / http://ip-ad-dr-ess:8080/
ProxyPassReverse / http://ip-ad-dr-ess:8080/
```
This allows me to browse <http://example.com> and served the content from the daemon web server.
I would like to include a wordpress blog as a subdirectory to the main site.
```
http://example.com <- Sinatra
http://example.com/blog <- Wordpress
```
Here is the entire config section
```
<IfModule mod_proxy_http.c>
LogLevel debug
ProxyRequests Off
ProxyPass /blog http://blog.example.com:80/
ProxyPassReverse /blog http://blog.example.com:80/
ProxyPass / http://ip-ad-dr-ess:8080/
ProxyPassReverse / http://ip-ad-dr-ess:8080/
<Location />
RequestHeader set X-Forwarded-Protocol http
</Location>
<Location /blog>
RequestHeader set X-Forwarded-Protocol http
</Location>
ProxyPreserveHost on
ProxyErrorOverride Off
</IfModule>
```
The problem I am having is when I navigate to <http://example.com/blog> I am served content from <http://example.com> not from the Wordpress.
As a test, in the config above I replaced <http://blog.example.com:80/> with <http://www.google.com:80/> and when I navigate to <http://example.com/blog> I am simply redirected to Google's site (with the URL in the address bar) which is not the behavior I expected.
Any idea of how I can resolve or maybe further debug this issue as to why the wordpress content is not be served?
Thanks
**Update blog.exmaple.com excerpt**
```
<VirtualHost ip-ad-dr-ess:80>
ServerAdmin webmaster@blog.example.com
DocumentRoot /home/path/blog.example.com
ServerName www.blog.example.com
ServerAlias blog.example.com
DirectoryIndex index.html index.shtml index.htm Index.html Index.htm Index.shtml$
ErrorLog /home/path/logs/blog.example.com/http.20187367/error.log
Alias /stats /home/path/logs/blog.example.com/http.20187367/html
<Directory /home/path/logs/blog.example.com/http.20187367/html>
AllowOverride AuthConfig FileInfo Indexes Limit Options=ExecCGI,Includes,Indexes$
</Directory>
Alias /doc/analog /usr/share/analog
RewriteEngine on
RewriteCond %{HTTP_HOST} =www.blog.example.com [NC]
RewriteRule ^(.*) http://blog.example.com$1 [R=301,NE]
</VirtualHost>
``` | 2012/06/21 | [
"https://serverfault.com/questions/400918",
"https://serverfault.com",
"https://serverfault.com/users/107757/"
] | You should try adding a trailing slash the path "/blog" like this
```
ProxyPass /blog/ http://blog.example.com/
ProxyPassReverse /blog/ http://blog.example.com/
``` | I was able to solve this issue. The root cause was that the I setup a proxy from one virtualhost to another on the same ip and the same port.
I changed the `blog.example.com` to listen on a different port, updated the proxy values in `http://example.com` which resolved the problem |
42,137,529 | If I have a series that has either NULL or some non-null value. How can I find the 1st row where the value is not NULL so I can report back the datatype to the user. If the value is non-null all values are the same datatype in that series. | 2017/02/09 | [
"https://Stackoverflow.com/questions/42137529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1087908/"
] | You can use [`first_valid_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.first_valid_index.html) with select by `loc`:
```
s = pd.Series([np.nan,2,np.nan])
print (s)
0 NaN
1 2.0
2 NaN
dtype: float64
print (s.first_valid_index())
1
print (s.loc[s.first_valid_index()])
2.0
# If your Series contains ALL NaNs, you'll need to check as follows:
s = pd.Series([np.nan, np.nan, np.nan])
idx = s.first_valid_index() # Will return None
first_valid_value = s.loc[idx] if idx is not None else None
print(first_valid_value)
None
``` | You can also use `get` method instead
```
(Pdb) type(audio_col)
<class 'pandas.core.series.Series'>
(Pdb) audio_col.first_valid_index()
19
(Pdb) audio_col.get(first_audio_idx)
'first-not-nan-value.ogg'
``` |
651 | I've always wondered why refrigerators don't have some of their parts located outdoors like an air conditioner.
In warm weather, it seems like it would make sense to have the condenser outside like an AC unit to avoid heating the room. In cold weather, it seems like it would be much more efficient to have the condenser outside to cool down faster. Why is the condenser still indoors?
First, does this exist in some places? Have I personally just never seen it? Maybe for large commercial, refrigerator/freezers?
If not, would the cost simply outweigh the benefit? Is it cheaper to have the AC cool the room down after the fridge has heated it slightly rather than install another condenser outside? In cold weather, is the fridge acting as an efficient space heater, so putting the condenser outside not really get you anywhere? I'd be interested to see if a cost/benefit analysis has been done.
Finally, is it just convenience? Is it simply much easier to just move the fridge in, plug it in, and be done? | 2015/02/14 | [
"https://engineering.stackexchange.com/questions/651",
"https://engineering.stackexchange.com",
"https://engineering.stackexchange.com/users/161/"
] | The cost of installing and maintaining a split refrigeration system for cabinet style refrigerators would swamp the cost of the refrigerator itself.
For large refrigerated rooms, or whole house cooling systems, the cost of the entire system is greater than the cost of the labor and maintenance.
Given mass manufacturing, though, it doesn't make sense to sell a $400 refrigerator that requires a lot more money to install, including holes, routing pipes, placement of an internal and external unit, etc. Further, it would decrease reliability and require more maintenance.
Lastly, there is actually little efficiency to be gained. It's such a small space to cool that the little heat increase in the summer isn't large, and is offset by reduced heating in the winter (when a refrigerator with an external unit would actually have to work harder).
It does make sense (and is more efficient) for much larger cooling requirements, but not for small refrigerator sized consumer appliances. | Modern materials would make separation an easy thing to do. Homes could be built with ducting to accommodate such a system. Right now a length of tubing is already used for the water supply for an ice maker. The connections can be designed to fit together without venting problems requiring re/filling the system. Many refrigerators sit and accumulate dust for years gradually loosing efficiency and causing degradation of components. Separating the parts may allow for easier cleaning. Refrigerators generate heat and moisture which can attract insects. They are noisy and do add heat to a room. My guess is that the suggestion will become something people will want and pay extra for as electricity savings becomes more apparent when dependent upon alternative power sources for the home. I would also like to see designs that retain the refrigerated air instead of dumping it when a door is opened. There surely is a better way. |
437,046 | I'm coding an enum strategy pattern where one of the strategies makes use of an `ScheduledExecutor`:
```
class ControllerImpl {
//...
boolean applyStrat(StratParam param) {
getStrat().apply(param);
}
//...
private enum Strats {
NOOP (NoopStrategyImpl.class),
REAL (RealtimeStrategyImpl.class),
SCHED (ScheduledStrategyImpl.class),
;
private final Strategy strategy;
Mode(Class<? extends Strategy> strategyClass) {
this.strategy = getInjector().getInstance(strategyClass);
}
public boolean applyStrategy(StratParam param) {
return this.strategy.apply(param);
}
}
class ScheduledStrategyImpl implements Strategy {
private ScheduledExecutor executor = Executors.new..().schedule..();
@Override
public boolean apply(StratParam param) {
// actual apply() logic
}
}
```
The goal of doing it like this, is to be able to hot-swap strategies. The default strategy is REAL, but during runtime it may be switched to NOOP or SCHED.
Now, the above code initializes the executor during static initialization of the enum. This means that `SCHED` will contain a running executor -- even if it is never used.
But I don't want to start the executor unless the strategy is *actually* used (no point in having it running in the background for no reason).
The common solution for this is to lazily initialize the executor in the `apply()` method instead:
```
class ExecutorStrategyImpl implements Strategy {
private ScheduledExecutor executor = null;
@Override
public boolean apply(..) {
if (executor == null) {
executor = Executors.new..().schedule..();
}
// actual apply() logic
}
}
```
This way, the executor will get initialized the first time the strategy is applied, not sooner. And if SCHED is never used, the executor is never created.
However, I don't want to waste cycles checking for `(executor == null)` every single time SCHED is `apply()`ed, when I know the condition will *always* be false except for the first time.
To avoind doing so, this is what I came up with:
```
class ExecutorStrategyImpl implements Strategy {
private ScheduledExecutor executor = null;
private Function<StratParam, Boolean> normal = param -> {
// normal apply() logic
};
private Function<StratParam, Boolean> firstTime = param -> {
innerStrategy = normal;
if (executor == null) {
executor = Executors.new..().schedule..();
}
return normal.apply(param);
}
private volatile Function<StratParam, Boolean> innerStrategy = firstTime;
@Override
public boolean apply(StratParam param) {
return innerStrategy.apply(param);
}
}
```
The reasoning behind the above code is as follows:
1. `innerStrategy` initially points to `firstTime` lambda, which includes the executor initialization code.
2. The first thread to get to `apply()` invokes `innerStrategy.apply()` and thus `firstTime` functionality.
3. `innerStrategy` is changed to `normal`; `volatile` keyword ensures that this change will be visible for every other thread that comes after.
4. Executor is initialized.
5. Every other thread calling `innerStrategy.apply()` gets `normal` functionality instead.
**My question is**: is there a window between 2. and 3. where two threads may read `innerStrategy` with the same `firstTime` value, thus creating two executors? Or is `volatile` enough to prevent that?
And, of course: is there a better way to do this? | 2022/02/28 | [
"https://softwareengineering.stackexchange.com/questions/437046",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/248892/"
] | I think you are on the right track. You want the `Player` object to allow autonomous movement, but without putting too much knowledge about the "outer game mechanics" into it. A "grabbed" state inside the player does not fit to this design, and you are perfectly right: introducing such attributes which are only useful for exactly one use case will make the class less reusable and flexible.
One can solve this by developing a clear idea what fits well into a certain abstraction, and what not. That's what we call the **responsibility** of a class. In this case, you want the `Player` to be an abstraction for a physical game item - hence it makes sense let the player know only it's own physical properties (like velocity and position), and maybe some meta information (like a name or id), **but not many more**.
Since the game will allow changing velocity and position of a player "from outside", you need to give it getters and setters for both. Making a boss "grab" a player just sets the player's velocity to zero - no need to introduce an extra `state` attribute for this (of course, this comes for the price of having the player "forgetting" its former velocity). When the boss lets the player go, the game mechanics has to set a new velocity for the player - but which velocity that will be is part of the game rules, nothing a player object should care for.
Still you can (and should) implement all methods inside the `Player` class which can be implemented reasonably by making use of player's internal attributes, like your `update` method. I would consider to use a more expressive name for it, like `moveAutomatically`. Such a method fits perfectly into your player abstraction of a "physical item", and placing it there helps to keep your program well organized.
When your program grows, and you add more and more use cases to it, you will several times have to make a decision whether the `Player`class should be extended, or whether a certain functionality should be kept out of the class. When you stick to the responsibility you envisioned, this usually leads to some *convergence* - for the first use cases you implement, the class has to be extended and refactored, but at some time in the future, the class becomes "feature complete" and stable. Then new use cases can be implemented by simply reusing the `Player`'s methods and attributes which are already there. | If you update positions of your characters iteratively based on their properties you could add some extra conditions that are outside the scope of the object itself. This would nicely reflect the powerless nature of a grabbed character.
Say some boss grabs your player, rather than flagging the player as grabbed you could have it removed from the list of characters to be updated on each iteration.
The boss chases a character and when his position is close enough to the player's, he could raise an event to the player manager object to request that player to be removed from the pool of free moving players and handed to him. In the same way he could release the player, having it re-added to the pool of free players.
Grabbed is an external condition which I would say should not be a property of player.
It may still be useful for a player to know its grabbed state if he could do something about it like struggle himself free or deploy some defense mechanism. But as long as that is not the case there is now reason for him to know, he would just be taken out of the game. |
5,988,246 | When testing in python shell, I always have to type some import like:
```
Python 2.5.4 (r254:67916, Jun 24 2010, 15:23:27)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>import sys
>>>import datetime
```
Can someone help me to automatically finish these? It means I run some command to enter python shell it has already done import for me, and a python shell waiting for me to continue type command.
Thanks. | 2011/05/13 | [
"https://Stackoverflow.com/questions/5988246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/371973/"
] | Try:
```
python -i -c "import sys; import datetime;"
```
More info:
```
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
```
&
```
-c cmd : program passed in as string (terminates option list)
``` | Create a file with the commands you want to execute during startup, and set the environment variable `PYTHONSTARTUP` to the location of that file. The interactive interpreter will then load and execute that file. See <http://docs.python.org/tutorial/interpreter.html#the-interactive-startup-file>
On a sidenote, you might want to consider [ipython](http://ipython.scipy.org/moin/) as an improved Python shell when working in interactive mode. |
45,761,270 | I am trying to manually add an additional attribute to parameters in the controller after completing a form. The params seem to be wrapped in , which seems to be preventing me to from changing the params.
**Controller:**
```
class ActualsController < SignedInController
...
def update
respond_to do |format|
facesheet = actual_params[:facesheet]
#trying to manually add attribute
actual_params.merge(:file_name => 'ted.png')
new_params = actual_params.except(:facesheet)
if @actual.update(new_params)
format.html { redirect_to action: 'show', id:@actual.id, notice: 'Actual was successfully updated.' }
format.json { render :show, status: :ok, location: @actual }
else
format.html { render :edit }
format.json { render json: @actual.errors, status: :unprocessable_entity }
end
end
end
...
end
```
**"new\_params" from console**
```
<ActionController::Parameters {"encounter_type_id"=>"1", "physician_id"=>"669", "insurance_id"=>"1182", "time_start"=>"05:00", "time_end"=>"07:00", "date_start"=>"2017-08-02", "date_end"=>"2017-08-02", "facility_id"=>"1", "med_rec_num"=>"1244", "patient_name_first"=>"Bob", "patient_name_last"=>"Smith", "patient_name_middle_initial"=>"H", "patient_dob"=>"2000-02-05", "note"=>"", "is_complete"=>"0", "procedure_ids"=>["", "300"]} permitted: true> -Thanks for your help on this.
```
**"@actual" from console**
```
#<Actual id: 18, encounter_id: 4, provider_id: 7, encounter_type_id: 1, physician_id: 669, facility_id: 1, insurance_id: 1182, group_id: nil, datetime_start_utc: "2017-08-02 10:00:00", datetime_end_utc: "2017-08-02 12:00:00", payer: nil, med_rec_num: "1244", patient_name_first: "Bob", patient_name_last: "Smith", patient_name_middle_initial: "H", patient_dob: "2000-02-05", finclass: nil, is_valid: nil, is_complete: false, image_location: nil, note: "", created_at: "2017-08-18 13:30:58", updated_at: "2017-08-18 16:01:28">
``` | 2017/08/18 | [
"https://Stackoverflow.com/questions/45761270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2452324/"
] | Try something like
```
private
def post_params
params.require(:post).permit(:some_attribute).merge(user_id: current_user.id)
end
``` | Try to whitelist the params instead of using .except
Also try to use .permit() to whitelist the required params |
1,565,724 | If I have a `list<object*>>* queue` and want to pop the first object in the list and hand it over to another part of the program, is it correct to use (sketchy code):
```
object* objPtr = queue->first();
queue->pop_first();
return objPtr; // is this a pointer to a valid memory address now?
```
?
According to the documentation on <http://www.cplusplus.com/reference/stl/list/pop_front/> it calls the destructor of the deleted element, but I'm confused as to whether it means the linked list's node object, or the actually stored "user" object.
Edit: I might be `front` instead of `first`, my bad. | 2009/10/14 | [
"https://Stackoverflow.com/questions/1565724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/189793/"
] | Yes, it is a valid pointer. List will not release the memory allocated by you. List will destroy its internal not the user object. | **Yes `objPtr` contains pointer to a valid memory.**
When you insert an element into a `std::list`, `list` makes a copy of it. In your case the element is an address (a pointer) so list makes a copy of the address and stores it.
```
object * optr = queue->pop_front();
```
optr now points to the object
```
queue->pop_front();
```
removes the element (an address/pointer) from the `list`, `optr` already points to your object.
After you're done with the object don't forget do delete it otherwise you end up with memory leak.
Example:
```
#include <iostream>
#include <list>
using namespace std;
struct A
{
static int count;
A() : val(count++) { cout << "A(" << val << ")" << endl; }
~A() { cout << "~A(" << val << ")" << endl; }
int val;
};
int A::count = 0;
ostream& operator<<(ostream& os, A& a) { return os << a.val; }
int main()
{
list<A*> alist;
for (unsigned int i = 3; i; --i) alist.push_back(new A());
for (unsigned int i = 3; i; --i)
{
A * aptr = alist.front();
alist.pop_front();
cout << *aptr << endl;
delete aptr;
aptr = 0;
}
}
``` |
2,385,022 | Is it possible to write any rational number (say 1 or 2 or .15) using a number system that was base pi instead of a number system that used a rational number as its base? | 2017/08/06 | [
"https://math.stackexchange.com/questions/2385022",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/462242/"
] | EDIT : The issue : The general setup for a given base $b$ is to write a given Real number $a$ as $a\_0 b^0 + a\_1b^1+....+a\_k b^k$ with $a\_k$ an integer less than the floor of $b$.
EDIT 2: STILL needs some work, which I am doing right now. Will be back soon to rewrite, or, if necessary, delete. Comments are welcome.
In our case, for $\pi$ we want to represent ( I assume) a Real number $a$ as $ \pi^0 a\_0+ \pi^1 a\_1+....+ \pi^n a\_n ; a\_j < \pi$
at each stage, you choose the largest number $a\_k$ , so that $$a\_0 \pi^0+a\_1\pi^1+...+a\_k \pi^k \leq a $$.
This is a monotone, non-decreasing sequence of Real numbers bounded above by $a$, so it will converge to its $lub=a $.
I think we need as a basis a Real number $x; |x|>1$. | We can write rational numbers in irrational bases; easily shown by $100$ base $\sqrt 2$ is 2. There are in fact problems and papers that I have seen that use base phi, $\frac{\sqrt 5 + 1}{2}$.
However, because pi is transcendental, it is not the solution of any polynomial with rational coefficients. This means that no rational number can be written as a sum of powers of pi, which is equivalent to the fact that you can not write any rational number base pi.
Edit: Of course, you can always write the numbers non negative integers less than or equal to the base in that base, like 2 base pi is still $2\cdot \pi^0 = 2$. I was talking about everything else. |
1,619 | For this site to succeed, we need enough "experts" (meaning, for example, graduate students, academic economists, or professional economists) around to provide high quality answers.
I am interested to hear from experts about their views of various types of question we get on the site. What kind of questions do you most like answering? How positively do you feel that various types of question contribute to the vitality of the site.
Some "types" of question might be:
1. Technical, specific graduate-level questions (e.g. [How to solve a variation of Merton's optimal portfolio problem?](https://economics.stackexchange.com/questions/13399/how-to-solve-a-variation-of-mertons-optimal-portfolio-problem))
2. Conceptual questions about basic (i.e. undergraduate) academic economics (e.g. [Why does Slutsky compensation "overcompensate" the consumer?](https://economics.stackexchange.com/questions/5357/why-does-slutsky-compensation-overcompensate-the-consumer/5453#5453))
3. Homework-style undergrad-level questions with effort shown.
4. Laymen asking economists to explain stuff (e.g. [Why do celebrities get high wages?](https://economics.stackexchange.com/questions/10742/why-do-celebrities-get-high-wages/10745#10745) or [How does Black Friday work?](https://economics.stackexchange.com/questions/9531/how-does-black-friday-work))
5. Reference requests (e.g. [Is there a folk theorem for repeated games on networks?](https://economics.stackexchange.com/questions/200/is-there-a-folk-theorem-for-repeated-games-on-networks))
6. Requests to use economics to answer practical/"how-to" questions (e.g. [Is a universal basic income possible in the United States?](https://economics.stackexchange.com/questions/1893/is-a-universal-basic-income-possible-in-the-united-states) or [Best way to analyze return rate data](https://economics.stackexchange.com/questions/13420/best-way-to-analyze-return-rate-data)) | 2016/09/15 | [
"https://economics.meta.stackexchange.com/questions/1619",
"https://economics.meta.stackexchange.com",
"https://economics.meta.stackexchange.com/users/108/"
] | **Vote up if you agree with the following:** I like to see/answer questions in which laymen ask economists to explain phenomena they observe (such as why celebrities are paid so much).
* Putting economics to work to explain such phenomena is an interesting challenge or good practice for doing research.
* This helps me to get to ideas for work or to spot limitations economics' ability to explain phenomena.
* Reading the answers to these questions helps me to learn about bits of economics I wouldn't otherwise have encountered.
* etc.
**Vote down if you agree with the following:** I do not like to see/answer questions in which laymen ask economists to explain phenomena they observe (such as why celebrities are paid so much).
* Such questions are often poorly framed and do not lend themselves to the kind of rigorous answers that should be on this site.
* The answer is often obvious to economists and therefore does not belong on a site aimed at experts.
* etc. | **Vote up if you agree with the following:** I like to see/answer homework style questions on this site (provided effort is showin in accordance with site policy).
* If a student has put in some effort and needs a few pointers then I don't mind helping.
* A key role for this site should be to support the education of economists in training, and answering homework questions supports this objective.
* Answering such questions gives me ideas for teaching or keeps my basic economics skills from getting rusty.
* etc.
**Vote down if you agree with the following:** I do not like to see/answer homework style questions on this site (even if effort is shown in accordance with current site policy). By extension, I think that all homework questions should be banned from the site.
* These questions are too basic. This should be a site for experts who already understand the basic building blocks of economics.
* The danger of this being used to help students cheat is too high.
* Answering such questions is likely to undermine a students' education.
* Since I already understand these basic concepts very well, I find writing answers too tedious.
* etc. |
57,193,502 | Suppose I use python zeep to execute a query against a server like this:
```
from zeep import Client
wsdl_url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL"
client = Client(wsdl_url)
result = client.service.ListOfContinentsByCode()
```
I would like to see the raw XML that comes back from this method, ie extract it somehow from result. Is this possible? How? | 2019/07/25 | [
"https://Stackoverflow.com/questions/57193502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699285/"
] | I think what you are looking for is the history plugin.
```py
from zeep.plugins import HistoryPlugin
from zeep import Client
from lxml import etree
wsdl_url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL"
history = HistoryPlugin()
client = Client(wsdl_url, plugins=[history])
client.service.CurrencyName('GBP')
your_pretty_xml = etree.tostring(history.last_received["envelope"], encoding="unicode", pretty_print=True)
``` | Here (requests [takes care](https://2.python-requests.org//en/master/user/quickstart/#binary-response-content) of the gzip)
```
import requests
r = equests.get('http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL')
if r.status_code == 200:
print(r.content)
``` |
93,979 | Personally, I never saw the smartphone coming, but maybe science-fiction did. Basically, I'm looking for the first science fiction story (if one exists) where people commonly have a device which can perform the general tasks of a smartphone today, namely:
* Being able to communicate, both personally and to the community (define community as what you will - today the community is anyone with internet access)
* A personal organiser
* Access to a large database of knowledge
* (Maybe) able to play games
(If there are any other essential functions to a smartphone you think I've neglected to mention, feel free to comment)
Note, it doesn't necessary *have* to have a touch screen, just so long as it is a portable, personal device which can accomplish the above listed tasks.
I'm specifically asking about *when* the first instance of such a technology in science fiction was and whether this predates smartphones in our world. | 2015/06/28 | [
"https://scifi.stackexchange.com/questions/93979",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/22917/"
] | Seems like Jerry Pournelle and Larry Niven beat Clarke by a couple of years with "The Mote in God's Eye" from 1974. In that book, people are constantly using pocket computers.
They contain large amounts of personal data, have calendars, can connect with other computers to call up even more information and are used to send messages to other people.
Usage is decribed much like a tablet, but rather than fingers they use some kind of pen/stylus.
The hardware is described as being "one big integrated circuit, if they break we don't even try to repair them."
I'm pretty sure there were earlier examples, but I just finished re-reading that book and happened to notice the publication date (1974.) I originally read it around 1990, and was surprised at how much earlier it was.
---
From the [list](http://forum.brighthand.com/threads/the-evolution-of-the-pda-1976-1995.214442/) linked to in the comments, "A Spaceship for the King" from 1971 (also Pournelle and Niven) would be earlier. I've read "A Spaceship for the King" in its novel form ("King David's Spaceship") and the pocket computers are the same as in "The Mote in God's Eye."
So, 1971. | While numerous stories have anticipated such device, I want to make a note that, in some broad sense, you're asking about the commercially successful product and its function, and not of a technology. And it also seems that 60's videophones are pretty far from the commercial products of these days, so here's a lot of bias to the question.
Smartphone is a:
* computer
* with a telephony/radio interface allowing it to communicate with network of base stations
* powered by a LiPo-based energy source.
Was there a story that involved both general-purpose computers (add Linux, Windows, whatever), a prebuilt set of communication towers and a lot of enthusiatic people making, say, applications or nowaday's mesh networks with VoiP - aka, software? `Spellbinder` (TV) comes to mind, but it was filmed already at the early age of handheld devices.
The videophones are identified as:
* analog components
* no computing function, no applications
* plugged into telephone line or using some central point of radio signal (like a TV)
* no internal power source. |
2,524,292 | How can we prove for $a$, $b$ and $c$ positive integers that if
$$\gcd(a,b)=\gcd(b,c)=\gcd(a,c)=d$$ then $$\gcd(a,b,c)=d$$
For $a$ and $b$ co-prime numbers, $\gcd(a,b)=1$, means that the pairs $(b,c)$ and $(a,c)$ are also co-prime numbers, then from the $\gcd$ commutativity and associativity:
$$\gcd(a,b,c)=\gcd(\gcd(a,b),c)=\gcd(\gcd(a,c),b)=\gcd(a,gcd(b,c))$$
$$\gcd(a,b,c)=\gcd(1,c)=\gcd(1,b)=\gcd(a,1)=1$$
This is correct because if $a$, $b$ and $c$ are mutually prime numbers their $\gcd$ is $1$, is this a special case only and we can found counterexamples for the above claim? | 2017/11/17 | [
"https://math.stackexchange.com/questions/2524292",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/503678/"
] | Let us merely assume that $\gcd(a,b)=d$ and that $d$ divides $c.$ Clearly, $d$ is a common divisor of $a,b,$ and $c.$ Let $e$ be any other common divisor of $a,b,$ and $c.$ Since $e$ is a common divisor of $a$ and $b,$ it follows that $e$ divides $\gcd(a,b)=d.$ Hence $d$ is the greatest common divisor of $a,b,$ and $c.$ | If $gcd(a,b)=d\Rightarrow a=md,b=nd$ with $ m,n\in\mathbb{N}$ and so $gcd(m,n)=1$. If $gcd(m,n)=1$, then $gcd(n,m,k)=1$ for any $k\in\mathbb{N}$. Can you work out from here? |
49,992,423 | I am creating a React app using `Next.js` and am trying to use components provided by `reactstrap`.
The issue I seem to be running into seems to involve importing the CSS file named `bootstrap/dist/css/bootstrap.min.css` as the `reactstrap` guide says to do.
The error I am seeing is `Error in bootstrap/dist/css/bootstrap.min.css
Module parse failed: Unexpected token (6:3) You may need an appropriate loader to handle this file type.`
Does anyone know what I have to do to make this work correctly? I am a new web developer so sorry if I am missing anything obvious.
Thanks! | 2018/04/24 | [
"https://Stackoverflow.com/questions/49992423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3723821/"
] | **EDIT: As of Next.js 7**, all you have to do to support importing .css files is to register the [withCSS](https://github.com/zeit/next-plugins/tree/master/packages/next-css) plugin in your next.config.js. Start by installing the plugin:
```
npm install --save @zeit/next-css
```
Then create the `next.config.js` file in your project root and add the following to it:
```
// next.config.js
const withCSS = require('@zeit/next-css')
module.exports = withCSS({/* my next config */})
```
You can test that this is working by creating a simple page and importing some CSS. Start by creating a CSS file:
```
// ./index.css
div {
color: tomato;
}
```
Then create the `pages` folder with an `index.js` file. Then you can do stuff like this in your components:
```
// ./pages/index.js
import "../index.css"
export default () => <div>Welcome to next.js 7!</div>
```
You can also use CSS modules with a few lines of config. For more on this check out the documentation on [nextjs.org/docs/#css](https://nextjs.org/docs/#css).
---
**Next.js < version 7**
Next.js doesn't come with CSS imports by default. You'll have to use a webpack loader. You can read about how this works here: <https://zeit.co/blog/next5#css,-less,-sass,-scss-and-css-modules>.
Next.js also has plugins for CSS, SASS and SCSS. Here is the plugin for CSS: <https://github.com/zeit/next-plugins/tree/master/packages/next-css>. The documentation for that plugin makes it fairly simple:
1. You create the `_document` file in `pages/`.
2. You create the `next.config.js` file in the root.
Using the code snippets from the documentation should set you up to import CSS files.
You'll need at least version 5.0. You can make sure you have the latest Next.js installed: `npm i next@latest`. | If you are still getting the error:
```
Unexpected token (6:3) You may need an appropriate loader to handle this file type.
```
try this in your next.config.js:
```
// next.config.js
const withCSS = require('@zeit/next-css')
module.exports = withCSS({
cssLoaderOptions: {
url: false
}
})
```
3. Now you should be able to import styleshets from node\_modules like this:
```
import 'bootstrap-css-only/css/bootstrap.min.css';
```
*Note: Using Next v 8+*
**Background:**
I spent a few hours trying to simply import a CSS installed as a node\_module and the various solutions are mostly hacky workarounds, but as shown above, there is a [simple solution](https://spectrum.chat/next-js/general/ignoring-folders-files-specifically-fonts~4f68cfd5-d576-46b8-adc8-86e9d7ea0b1f).
It was provided by one of the core team members |
605,110 | I have a flat file containing columns of data representing fields from a table. I get the file from an outside source and want to insert the data into a table in my database. Unfortunately, the file I receive is missing a field in a specific column (new field that was added). Since I have no control of what is being sent to me, I would like to edit the file and just add the field. Can `sed` be used to add text in a specific column on every row?
For example, let's say I have this file:
```
Alan Bradford 555-2012
Cathy Davies 555-7823
Edward Farris 555-9162
Gary Hobbs 555-5151
Irene Jacobs 555-1285
```
The file is missing the area codes, so I want to add `213` in front. I know the phone numbers always start in column (pure character count) 31. So I want it to show
```
Alan Bradford 213 555-2012
Cathy Davies 213 555-7823
Edward Farris 213 555-9162
Gary Hobbs 213 555-5151
Irene Jacobs 213 555-1285
```
I know I can do this in three passes. I can use `cut -c1-30` and get Part1, and `cut -c31-` to get Part2. Then I can paste it all together with `echo "$Part1 $NEWDATA $Part2" >> filename`
I just wonder if there is a much easier way using sed. I should be able to use something like
```
sed -e "30l,i213 " InFile > OutFile
```
I just can't seem to get the syntax right to say move over 30 characters on the line, then insert `213` .
Anyone know what might work, or work better than my cut and paste options?
UPDATE
======
I'm told that my example was not accurate enough and I should edit the question to stop wasting people's time. The example I gave was pretty accurate for the question: How do I insert a string "XXX" ALWAYS in position Y no matter what is before or after it?
But no problem...Here's my real world example. I have a text file with rows of 928 characters each. I want to insert a string starting at position 878. The values before and after the string cannot be counted on to be the same each time, since the next field after where I want to insert is a remarks field, which is usually but not always blank.
The answer from @DonHolgo had the most promise and is a great answer. But on my flavor of UNIX (AIX 7.1) it seems that it only allows you to keep track of up to 255 characters before you get an error.
Here I am inserting "XXX " at column 255:
```
# sed 's/.\{255\}/&XXX /' OrigTextFile
1 030680001001YNPO 14 H502 000595000000000000 1 0000680M00000100000004799000000000000479900000004799000000004799000000000000479900000 SDI42028820 20P561292 00000000000XXX 000000000000000000000000000000000000000000000000000000000000000 T 0000655000000000Y 0000516000000000E 0000280000000000 0000000000000000 0000000000000000 0000000000000000 0000000000000000 0000000000000000 0000000000000000 0000000000000000 20200814
```
But I try the same thing for inserting at column 256 or higher:
```
# sed 's/.\{256\}/&XXX /' OrigTextFile
sed: 0602-404 Function s/.\{256\}/&XXX / cannot be parsed.
```
Looks like a limitation on my version of sed. So I may have to just do my original plan of cutting the textfile up.
File1 = First 878 characters of each line from the textfile
File2 = New string I want to add, one line for each line in original file
File3 = Remaining characters from original textfile.
Then just join them all:
```
# paste File1 File2 File3 > NewTextFile
``` | 2020/08/18 | [
"https://unix.stackexchange.com/questions/605110",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/428811/"
] | You can use a counted RE. For example, `x{12}` will match 12 `x` characters, and `y{1,3}` would match 1, 2, or 3 `y` characters. Here we're going to use `.{30}` to match 30 character wildcards (i.e. 30 of any character). The `\1` in the result string matches the bracketed reference in the pattern match
```
sed -r 's#^(.{30})#\1213 #' file
```
In your updated question you now say there are 878 characters before the insert. So just amend the example's 30 to reality's 878 and insert `XXX`
```
sed -r 's#^(.{878})#\1XXX#' file
```
The same process can apply for any fixed-width modification.
You can use `perl` too, which doesn't have the line length limitations that plague some implementations of `sed`,
```
perl -pe 's#^(.{878})#$1XXX#' file
``` | You can also try it with `awk`
```
awk '{sub(/^.{30}/,"&213 ")}1' file
```
This will append `213` to the pattern consisting of the first 30 characters of the line, no matter what they are.
The syntax is as follows:
* The `sub()` function is used to substitute *the first* occurence of the specified regular expression on the current line (default target if no string-to-be-manipulated is explicitly stated).
* The regular expression is `^.{30}`, meaning "30 times any character", but starting at the beginning of line (meaning of the "anchor" `^`).
* The replacement is "the found pattern (meaning of the `&`), followed by `213` and a space.
* The remainder of the line will be untouched, leading effectively to an insertion of the `213` after these first 30 characters.
This action is performed on any line (action block `{ ... }` without condition). `awk` will then print the modified line (the `1` at the end of the `awk` program). |
330,997 | What I am trying to do is to digitally send a signal through a cat5 cable. I wan't to send it digitally so people can't just come along and put a voltage on the wires to activate the circuit. I would like the signal to come from the main control board. Thanks. | 2017/09/24 | [
"https://electronics.stackexchange.com/questions/330997",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/-1/"
] | Depending on your skills, budget and time schedule, then anything we suggest might be too complicated, expensive or time consuming etc. for you to use in your design. However I'll mention one technology which fits your stated desire to "send some bytes" through the cable, to operate the lamp attached to the "Main Box".
You could use the [Holtek](http://www.holtek.com/producthome/-/pid/413/453/604) [HT12E (encoder)](http://www.holtek.com/productdetail/-/vg/2_12e) and [HT12D (decoder)](http://www.holtek.com/productdetail/-/vg/2_12d) to send a coded data stream along the CAT 5 cable. Obviously you would use a matching address selection (effectively that is your code) on both the encoder and the decoder.
Often the HT12E and HT12D are used for wireless links e.g. IR or wireless via OOK modulation modules. However, the "data out" pin of the HT12E encoder can be directly connected to the "data in" pin of the HT12D decoder.
The encoder would be in your "Portable Box", and the switch which you showed would need to also be either fitted to, or at least connected to, that box in order to trigger the encoder to send its coded data stream. A power source would either be in the "Portable Box" or power could be sent to the "Portable Box", along dedicated wires in the CAT 5 cable, from the "Main Box".
In the "Main Box" would be the decoder and, depending on the type of lamp, the exact behaviour desired (e.g. if the light should stay on *only* when the switch is operated, or whether it should "latch on" for some period etc.) and the power source you provide, then some ancillary components may be needed between the decoder and the lamp.
As a minimum, even if your "Portable Box" contained its own power source for the HT12E encoder, there would need to be two wires used in the CAT 5 cable - the "data wire" linking the encoder and the decoder, and a shared Gnd reference between the two boxes. If the power for the "Portable Box" was coming from the "Main Box", then another wire in the CAT 5 cable would need to be dedicated to that.
Depending on the length of the wire and therefore its capacitance, you would likely want to choose a slow oscillator frequency for both the encoder & decoder, as the data waveform will be distorted by the effects of the cable capacitance.
It might become necessary to add a differential driver (at the encoder) and receiver (at the decoder) - e.g. RS-422 or RS-485 - to increase the reliability of the data reception.
If someone can open either box, or can attach an oscilloscope or logic analyser to the cable, then the code can be discovered & defeated. However within the limit of "not expensive" then this approach is something to consider.
(There might be other encoder/decoder device pairs which are also suitable - I suggested that pair as they are well-known & have public datasheets.) | You don't want to actually use Ethernet signalling, just use the cable (unless you have some other requirement for Ethernet signalling)
Some simple serial scheme between minimal microcontrollers would work. Annoyingly propriety laptop supplies sometimes do this.
Note that short of a cryptographic scheme it can be reverse engineered easily.
On the simple end, require a known resistor much smaller than the cable resistance to be on an extra wire, or require pulses at a specific rate. |
34,702 | Because my C: drive is just a 40gig SSD and space is an issue with it, I tend to keep games from saving files, DLC and screenshots there.
I've changed my 'Documents' target on Windows 7 to target a folder on my D: drive. However, Sims 3 doesn't seem to care about this and keeps creating files at Username\My Documents on my C: drive.
Could anyone tell me if its possible, and how I can get it to download store content, save screenshots, save games, etc., in a folder on my D: drive and not there? | 2011/11/09 | [
"https://gaming.stackexchange.com/questions/34702",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/13898/"
] | I'm guessing the game has been hard coded to use C:\ instead of checking where the documents directory is, you could use a [NTFS Symbolic Link](http://en.wikipedia.org/wiki/NTFS_symbolic_link) to workaround it. This will essentially create a shortcut, that programs will actually follow it properly.
To create one you will need to open a command prompt as admin. To do that just open the Start menu, type "cmd" and press Control + Shift + Enter. From there the basic command your going to want is
```
mklink /D "C:\Users\[you]\Documents" "D:\Users\[you]\Documents"
```
Of course supplement the directories for the ones you're using. You can either do it for the entire Documents directory or just for The Sims 3 data. In other words, move the Sims 3 folder, for example, to drive D before entering the above command. | Try uninstalling it then when you re-install it, use the custom download option and set it where you want it to save, unless that's what you mean when you said, "I've changed my 'Documents' target on Windows 7 to target a folder on my D: drive." |
27,137,486 | I have a list of line number for a given file. Now I want to insert a specific line before each of these lines in the file. How is it possible to do using C++ file operations.
I know that `tellg()` would give location of character in file, but how do I get the line and print just before that line. | 2014/11/25 | [
"https://Stackoverflow.com/questions/27137486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2277510/"
] | 1. Create the class with `main()` method:
```java
public class Test1 {
public static void main(String[] args) {
System.out.println("hello1");
}
}
```
2. Hit `ctrl``shift``F10` (or `ctrl``shift``R` for Mac)
It will compile, assemble and print `hello1` | Solution:
1. Execute run \* \* main() with coverage;
2. Modify gradle.xml under. Idea
< GradleProjectSettings> Add a row under the label node
< option name=”delegatedBuild” value=”false” />
<https://programmerah.com/tag/android/page/2/> |
467,255 | I currently rely on anchor tags to perform AJAX requests on my web application (using jQuery). For example:
```
<script type="text/javascript">
$(document).ready(function() {
$("#test").click(function() {
// Perform AJAX call and manipulate the DOM
});
});
<a id="test" href="">Click me!</a>
</script>
```
However, these anchor tags pretty much become useless if the user disables javascript in their browser. What's the best way to handle graceful degradation of these anchor tags? Is my only option to switch them all to buttons inside form tags?
Edit: I should be more clear and specify that my AJAX call is an HTTP POST to a URL that I cannot, for security reasons, expose to normal HTTP GETs (e.g. think of a delete url "/items/delete/1"). With that in mind, I can't change the href of the anchor to be "/items/delete/1" in order to satisfy users with javascript turned off since it poses a security risk. | 2009/01/21 | [
"https://Stackoverflow.com/questions/467255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] | One option (for which I'm sure I'll get downvoted), is to not bother with people who have javascript off. Display a message in a `<noscript>` tag informing the user that your site requires Javascript.
It'll affect two groups of people: those who have knowingly disabled javascript and presumably know how to turn it back on, and those who are viewing your site on an older mobile device.
Consider how important these groups of people are before you go on spending hours and hours developing for them. | Your best bet for no-JS would probably be to have a form with a submit button, and point the form's action to your URL.
You can style the button to look like a link (or like anything else):
```
<button class="linkstyle" type="submit">Foo</button>
<style type="text/css">
button.linkstyle { border:none; background:none; padding:0; }
<style>
```
There's a good example of styling buttons in Particletree's article: [Rediscovering the Button Element](http://particletree.com/features/rediscovering-the-button-element/) |
47,081,354 | Hello I have two tables
Let's called them table schedule and table appointments
**Schedule table:**
```
+----+
| id |
+----+
| 3 |
| 42 |
+----+
```
**Appointment table:**
```
+----+-------------+
| id | schedule_id |
+----+-------------+
| 1 | 0 |
| 2 | 42 |
+----+-------------+
```
I have a query that gets appointments and schedules out of the database it looks something similar to this:
```
SELECT id FROM appointment
UNION ALL
SELECT id FROM schedule
```
I want to get all schedules and appointments, if there's an appointment that has a matching schedule\_id I want the schedule row to be removed from the results
The end result would be
```
+----+-------------+
| id | schedule_id |
+----+-------------+
| 1 | 0 |
| 2 | 42 |
| 3 | 0 |
+----+-------------+
```
What do I need to do to create that query? | 2017/11/02 | [
"https://Stackoverflow.com/questions/47081354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/978970/"
] | Character constant `'2'` in the ASCII table has code 50. So using the format specifier `%d` the character is displayed as an integer that is its value 50 is displayed.
As for this expression
```
a[1] - '0'
```
then as it has been said `a[1]` that represents the character `'2'` stores the ASCII value `50`. The character `'0'` has the ASCII code `48`. So the difference yieds `2`. | C specifies that the codes for characters `'0'`, `'1'`, `'2'`, ... `'9'` are sequential.
`'0' + 3` must equal `'3'`.
This applies for any character set: the common [ASCII](https://en.wikipedia.org/wiki/ASCII) or others.
Subtraction from `'0'` yields the numeric difference.
```
printf("%d",'2' - '0'); // must print 2
```
>
> ... the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous. ... C11dr §5.2.1 3
>
>
> |
502,835 | Is there a relay that will work with 12V / 300ma input to close a Normally Open output? I've been trying to make it work with Ardouino board and a HiLetgo 12V 1 Channel Relay Module With Optocoupler Isolation Support High or Low Level Trigger, but have not been able to get it to work. Seems like there should be a simpler solution that doesn't involve a controller board. | 2020/05/30 | [
"https://electronics.stackexchange.com/questions/502835",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/253982/"
] | Here's the end product - worked as expected [](https://i.stack.imgur.com/oI463.png) | Just use a 12V relay - most small 12V relays will have 200 ohm or more coil resistance and thus use much less than 300mA to operate. - for 300mA coil resistance as low as 40 ohms would work.
Add a diode parralel to the relay coil to prevent back-emf problems. |
18,088,795 | Why does the following code throw an exception? Note that the file is a `/proc/pid/stat` file so it could be interfered by the kernel.
```
// Checked that file does exist
try {
std::ifstream file(path.c_str());
// Shouldn't even be necessary because it's the default but it doesn't
// make any difference.
file.exceptions(std::ifstream::goodbit);
// Read the stream into many fields
// !!!! The exception was thrown here.
file >> _ >> comm >> state >> ppid >> pgrp >> session >> tty_nr
/* >> ... omitted */;
file.close();
} catch (const std::ifstream::failure& e) {
std::cout << "Exception!!!! " << e.what();
}
```
The exception was "basic\_filebuf::underflow error reading the file".
Shouldn't the stream not throw an exception when we haven't asked it to (by setting `file.exceptions()`)?
More info:
* It runs on gcc version 4.1.2 20080704 (Red Hat 4.1.2-54)
* The full code that causes the problem (without the try/catch part): [proc.hpp](https://github.com/apache/mesos/blob/e5c2edc3434b918bc9e25629b1571d7c283ce867/3rdparty/libprocess/3rdparty/stout/include/stout/proc.hpp#L214) | 2013/08/06 | [
"https://Stackoverflow.com/questions/18088795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118863/"
] | Update 2
--------
I've even tried to force an error by manually setting tiny or huge buffer sizes:
```
std::filebuf fb;
// set tiny input buffer
char buf[8]; // or huge: 64*1024
fb.pubsetbuf(buf, sizeof(buf));
fb.open(path.c_str(), std::ios::in);
std::istream file(&fb);
```
I've verified that the read size were indeed tiny (7) using `strace`
```
sudo strace ./test $(sudo ps h -ae -o pid) |&
egrep -w 'read|open' | grep -v '= 7' | less -SR
```
Interestingly, none of this failed.
Updated
-------
in response to the comments, I have devised a standalone program that does *exactly* what the OP describes, but I can't reproduce the problem:
* [**See it live on Coliru again** http://coliru.stacked-crooked.com/view?id=81960c...](http://coliru.stacked-crooked.com/view?id=81960c6cde468ebdefcc96b05372f5e4-0894edcb4536c67d1317b0e5694fa971)
```
#include <sys/types.h> // For pid_t.
#include <fstream>
#include <string>
// mock up
#include <boost/variant.hpp>
namespace {
struct None {};
struct Error { std::string s; Error(std::string s): s(s){} };
std::ostream& operator<<(std::ostream& os, None const&) {
return os << "None";
}
std::ostream& operator<<(std::ostream& os, Error const& e) {
return os << "Error {" << e.s << "}";
}
template <typename T>
using Result = boost::variant<None, Error, T>;
}
// end mockup
namespace proc {
// Snapshot of a process (modeled after /proc/[pid]/stat).
// For more information, see:
// http://www.kernel.org/doc/Documentation/filesystems/proc.txt
struct ProcessStatus
{
pid_t pid;
std::string comm;
char state;
pid_t ppid, pgrp, session;
int tty_nr;
pid_t tpgid;
unsigned int flags;
unsigned long minflt, cminflt, majflt, cmajflt;
unsigned long utime, stime;
long cutime, cstime, priority, nice, num_threads, itrealvalue;
unsigned long long starttime;
unsigned long vsize;
long rss;
unsigned long rsslim, startcode, endcode, startstack, kstkeip, signal, blocked, sigcatch, wchan, nswap, cnswap;
friend std::ostream& operator<<(std::ostream& os, proc::ProcessStatus const& ps) {
return os <<
"pid: " << ps.pid << "\n" <<
"comm: " << ps.comm << "\n" <<
"state: " << ps.state << "\n" <<
"ppid: " << ps.ppid << "\n" <<
"pgrp: " << ps.pgrp << "\n" <<
"session: " << ps.session << "\n" <<
"tty_nr: " << ps.tty_nr << "\n" <<
"tpgid: " << ps.tpgid << "\n" <<
"flags: " << ps.flags << "\n" <<
"minflt: " << ps.minflt << "\n" <<
"cminflt: " << ps.cminflt << "\n" <<
"majflt: " << ps.majflt << "\n" <<
"cmajflt: " << ps.cmajflt << "\n" <<
"utime: " << ps.utime << "\n" <<
"stime: " << ps.stime << "\n" <<
"cutime: " << ps.cutime << "\n" <<
"cstime: " << ps.cstime << "\n" <<
"priority: " << ps.priority << "\n" <<
"nice: " << ps.nice << "\n" <<
"num_threads: " << ps.num_threads << "\n" <<
"itrealvalue: " << ps.itrealvalue << "\n" <<
"starttime: " << ps.starttime << "\n" <<
"vsize: " << ps.vsize << "\n" <<
"rss: " << ps.rss << "\n" <<
"rsslim: " << ps.rsslim << "\n" <<
"startcode: " << ps.startcode << "\n" <<
"endcode: " << ps.endcode << "\n" <<
"startstack: " << ps.startstack << "\n" <<
"kstkeip: " << ps.kstkeip << "\n" <<
"signal: " << ps.signal << "\n" <<
"blocked: " << ps.blocked << "\n" <<
"sigcatch: " << ps.sigcatch << "\n" <<
"wchan: " << ps.wchan << "\n" <<
"nswap: " << ps.nswap << "\n" <<
"cnswap: " << ps.cnswap << "\n";
}
};
// Returns the process statistics from /proc/[pid]/stat.
// The return value is None if the process does not exist.
inline Result<ProcessStatus> status(pid_t pid)
{
std::string path = "/proc/" + std::to_string(pid) + "/stat";
std::ifstream file(path.c_str());
if (!file.is_open()) {
#if 1
return Error("Failed to open '" + path + "'");
#else // FIXME reenable
// Need to check if file exists AFTER we open it to guarantee
// process hasn't terminated (or if it has, we at least have a
// file which the kernel _should_ respect until a close).
if (!os::exists(path)) {
return None();
}
return Error("Failed to open '" + path + "'");
#endif
}
std::string _; // For ignoring fields.
// Parse all fields from stat.
ProcessStatus ps;
if (file >> _ >> ps.comm >> ps.state >> ps.ppid >> ps.pgrp >> ps.session >> ps.tty_nr
>> ps.tpgid >> ps.flags >> ps.minflt >> ps.cminflt >> ps.majflt >> ps.cmajflt
>> ps.utime >> ps.stime >> ps.cutime >> ps.cstime >> ps.priority >> ps.nice
>> ps.num_threads >> ps.itrealvalue >> ps.starttime >> ps.vsize >> ps.rss
>> ps.rsslim >> ps.startcode >> ps.endcode >> ps.startstack >> ps.kstkeip
>> ps.signal >> ps.blocked >> ps.sigcatch >> ps.wchan >> ps.nswap >> ps.cnswap)
{
return ps;
} else
{
return Error("Failed to read/parse '" + path + "'");
}
}
} // namespace proc {
int main(int argc, const char *argv[])
{
for (auto i=1; i<argc; ++i)
std::cout << proc::status(std::stoul(argv[i])) << "\n";
}
```
It runs happily on my machine, printing stuff like
```
pid: 594590200
comm: (test)
state: R
ppid: 8123
pgrp: 8123
session: 8123
...
```
Even if/when I torture it with
```
sudo ./test $(sudo ps h -ae -o pid) | grep -v : | sort -u
./test $(sudo ps h -ae -o pid) | grep -v : | sort -u
```
It just shows (presumably the `sudo`/`ps` from the subshell)
```
Error {Failed to open '/proc/8652/stat'}
Error {Failed to open '/proc/8653/stat'}
```
I have tried to read the information *twice* from the input stream (to force read-past-the-end type situation), but no luck.
---
Old answer text:
----------------
You need to establish under what kind of conditions the exception occurs. The following demo code works as expected on my system:
```
#include <fstream>
#include <iostream>
int main()
{
system("ps -o pid,comm,state,ppid,pgrp,session,tty > input.txt");
try {
std::ifstream file("input.txt");
file.exceptions(std::ifstream::goodbit);
std::string _, comm, state, ppid, pgrp, session, tty_nr;
while (file >> _ >> comm >> state >> ppid >> pgrp >> session >> tty_nr)
{
for (auto&& s : { _, comm, state, ppid, pgrp, session, tty_nr })
std::cout << s << "\t";
std::cout << "\n";
}
file.close();
} catch (const std::ifstream::failure& e) {
std::cout << "Exception!!!! " << e.what();
}
}
```
Prints, e.g.:
```
PID COMMAND S PPID PGRP SESS TT
20950 bash S 20945 20950 20950 pts/1
21275 vim S 20950 21275 20950 pts/1
21279 bash S 21275 21275 20950 pts/1
21280 test S 21279 21275 20950 pts/1
21281 sh S 21280 21275 20950 pts/1
21282 ps R 21281 21275 20950 pts/1
```
Update
------
I thought, on many systems the default buffer size is probably max 8192 bytes; let's create some silly long lines instead! Replacing the `system` call by
```
system("od /dev/urandom -t x8 -Anone | xargs -n256 | tr -d ' ' | xargs -n7 | head -n100 > input.txt");
```
results in lines with 7 columns, taking ~29kB per line. The output is without hesitation and amounts to 2.8MiB of output, measured with
```
make -B && ./test | wc
```
See it live on coliru:
* <http://coliru.stacked-crooked.com/view?id=00160c8a2b5d4447cbda3866da3913aa-b8c04540b49ee47c13fd3df477ec213b>
*Note that on Coliru, we can't access `/dev/urandom`, which is why I read from the binary itself. "Random" enough for this purpose :)* | I consistently get this error on g++ 4.5 when I attempt to read from a file corresponding to an exited process (so the file no longer exists). Here's a test case:
```
#include <iostream>
#include <fstream>
int main(int argc, char** argv)
{
if(argc!=2)
{
std::cerr << "Usage: " << argv[0] << " /proc/PID/filename\n";
return 1;
}
std::ifstream file(argv[1]);
if(!file)
{
std::cerr << "Failed to open the file\n";
return 2;
}
std::cout << "Type anything and press <Return> to continue...\n";
char c;
std::cin >> c;
int field;
try
{
file >> field;
if(file)
{
std::cout << "Successful read, field = " << field << "\n";
return 0;
}
else
{
std::cout << "Non-exception read failure\n";
return 3;
}
}
catch(std::exception& ex)
{
std::cerr << "Exception: " << ex.what() << "\n";
return 4;
}
}
```
After compilation, test like this:
```none
$ sleep 0.5 & ./test /proc/$!/stat
[1] 8261
Type anything and press <Return> to continue...
d
Exception: basic_filebuf::underflow error reading the file: iostream error
[1]+ Done sleep 0.5
```
If you instead pass e.g. `5` to `sleep` and type something to resume the program before 5 seconds pass, you'll get successful read.
This happens due to a [bug in libstdc++](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53984), which is now fixed. |
37,620,072 | I need to get a list of unique email addresses across 2 table. For example I have the selects:
```
select distinct
email
from
contacts
order by
email
select distinct
email
from
customers
order by
email
```
If I only needed one of those, piece of cake. If I wanted them as 2 columns side by side, also piece of cake.
But how do I get them as a single column, no duplicates, sorted? This will be running on Azure Sql Database if that is useful. | 2016/06/03 | [
"https://Stackoverflow.com/questions/37620072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/509627/"
] | **Clear Data** will clear everything, Shared Preference, Cache, DB.
If you really want to clear only shared preference (some/all) you can do it programmatically by iterating over Shared Preferences like this:
```
Map<String, ?> allEntries = prefA.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.i("debug", entry.getKey() + ": " + entry.getValue().toString());
//put delete/edit logic here for some shared preference
}
```
This logic can be placed based on your app version, or some other logic like when user logs out, but this action would be performed in your app only.
I dont think Android Applications settings allows any option where you can clear only shared preferences and not local db. | There is an option to put a database in apk [directly](https://github.com/jgilfelt/android-sqlite-asset-helper). Of course if you use already completed database in your case |
312,180 | tl;dr
-----
We rolled out some improvements for how you track the topics you are interested in for your favorite Q&A sites. This feature used to be called Favorite Tags. We are renaming it Tag Watching. Naming is hard, but we think this better captures the value of the feature. There were a number of confusing elements to the old feature. We've attempted to clear these up and refocus the user experience on the core functionality.
>
> This feature is live as of today (07/26/2018) on all sites. We turned this on for all sites earlier than expected so that we could do some code cleanup.
>
>
>
Key improvements:
-----------------
* Released
+ On boarding: new users are introduced to tag watching and how it can help them
+ Cleaner pop up: new pop up is more focused on the key actions.
* Coming later
+ Notifications: When watching a tag you're prompted to set up notifications, if desired. Also, changing notification settings will be supported when you edit your watched tags in the right side bar.
On boarding
-----------
Many users don't actually favorite any/many tags. Part of this is likely due to fact that we never explained why you should bother. In the old system all you saw was:
Tag Favorites on boarding
[](https://i.stack.imgur.com/pNlW8.png)
Now you see a description of the value tag watching provides.
[](https://i.stack.imgur.com/b9Hgb.png)
Tag pop up
----------
Our old tag pop up was very comprehensive and confusing. So many options. Watching/ignoring a tag was a tristate button (those are never a good option). An every action is essentially presented on equal footing. This makes it really hard for new users to understand what they can/should do.
[](https://i.stack.imgur.com/bmEDP.png)
The new pop up is focused on two primary actions (watch or ignore tag) and two minor actions (view tag, access RSS).
[](https://i.stack.imgur.com/UXxD9.png)
Notifications (coming later)
----------------------------
>
> We have some work to make the notifications scale to SO. So, while these improvements are live for Teams users, they will be enabled later (timing TBD) for SO and the rest of the network.
>
>
>
With the old system watching a tag and getting notifications were two separate steps. With the new experience, you will be prompted to set your notifications when you watch a tag.
[](https://i.stack.imgur.com/BEN8D.png)
Also, changing your notifications will be integrated into the experience of editing your watched tags.
[](https://i.stack.imgur.com/zXE8d.png)
Feedback wanted
---------------
As usual, we are happy to hear your constructive feedback. Feel free to post an answer below if you think of an improvement. | 2018/07/05 | [
"https://meta.stackexchange.com/questions/312180",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/354333/"
] | **Please de-emphasize the Unwatch button**
The unwatch button in really inviting and asks to be pressed as 'main' action in the tag-section. This is OK if you accidentally added the tag, but for a normal workflow this is not what a user wants to do.
See this image:
[](https://i.stack.imgur.com/0iQHz.png)
Maybe just a grey button with blueish text is ok? | ### Font size of "edit" is too big
[](https://i.stack.imgur.com/DAhXt.png)
The font size of "edit" should not be bigger than the tags below. This would be consistent with the "edit" links for questions and answers which are also set in a smaller font size. |
52,283,528 | ```
var array = [];
document.querySelectorAll("a").forEach(array.push); //Uncaught TypeError: Cannot convert undefined or null to object
```
Why does this fail? what does this error mean? It seems perfectly reasonable to pass an array method as a function, what am I not understanding/seeing? | 2018/09/11 | [
"https://Stackoverflow.com/questions/52283528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9464185/"
] | `array.push` loses context (its `this`), so you need to pass a function with context captured.
But, even if what you wanted worked - you still would not get the result you want, since `NodeList:forEach` passes 3 arguments to the callback function, so you would fill your `array` with elements, indexes and the list of nodes.
So a solution would be to do
```
var array = [];
document.querySelectorAll("a").forEach(e => array.push(e));
``` | I'm not 100% sure what you're trying to do, but I'm going to guess that you'd like to push the elements returned by querySelectorAll into 'array'. In which case, you can't just pass the function push to forEach, you must call push on array with each element as the argument, like so:
```
document.querySelectorAll("a").forEach(item => array.push(item));
``` |
21,482,103 | In Eclipse the auto complete is very very strict. Is there a way to have it slightly looser? For instance:
```
getData()
setData()
```
I want to type "data", and have the two functions above be found but because both functions have "get" or "set" at the start, it doesn't suggest these functions, I have to type `get` or `getD` to finally be able to get it in the auto complete.
I was wondering if there was a setting to have it include 'any' functions that have the search term within it, not just starts with?
I have tried doing searches on Google, but without knowing the the terms I am only getting people asking for help saying 'its not working'.
I just want to change from "startswith" to "contains".. | 2014/01/31 | [
"https://Stackoverflow.com/questions/21482103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387015/"
] | Unfortunately there is no preferences setting to enable or change that. There are several ways to tweak the behavior of Content Assist under **Preferences** > **Java** > **Editor** > **Content Assist**, such as enabling "camel caps" matching (eg, typing `gD` will find`getData()`), but I see nothing about sub-string matching. It would be a good feature request, though. Please consider entering it in [Eclipse's Bugzilla](https://bugs.eclipse.org/bugs/). | Even better with [Eclipse 4.17 July 2020](https://www.eclipse.org/eclipse/news/4.17/jdt.php#content-assist-substring-types):
>
> Substring/Subword matches for types
> -----------------------------------
>
>
>
>
> Content Assist now fully supports both substring and subword matches for types:
>
>
>
[](https://i.stack.imgur.com/XRe2Z.png)
>
> Substring matches are always shown and subword matches can be enabled/disabled with the existing `Show subword matches` option on the `Java > Editor > Content Assist` preference page.
>
>
> |
7,945,756 | If I defined a char buffer like below
```
char buffer[20] = "foo";
```
then
```
buffer[0] == 'f';
buffer[1] == 'o';
buffer[2] == 'o';
buffer[3] == 0;
```
What does the standard say about **buffer[4]** to **buffer[19]**. Are they guaranteed to be intialized to zero as well ? | 2011/10/30 | [
"https://Stackoverflow.com/questions/7945756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764882/"
] | All remaining elements guaranteed to be intialized to zero.
Reference:
**C++03 Standard section 6.7.8 para 21:**
>
> If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be
> initialized implicitly the same as objects that have static storage duration.
>
>
> | A lot of compilers will initialize the content of buffer[20] to 0. It is especially true if you initialize it with {}
You can check your compiler's behaviour using something like this:
```
#include <stdio.h>
int main() {
char buf1[20] = "foo";
char buf2[20] = {};
int i;
for(i = 0; i < 21; i++ ) {
printf("%02x ", buf1[i]);
}
printf("\n");
for(i = 0; i < 21; i++ ) {
printf("%02x ", buf2[i]);
}
printf("\n");
}
```
*Note that i put 21 in the conditional rather than 20 just to push the output beyond the actual buffer allocation. It should dump some garbage byte afterwards.* |
21,126,287 | I'm trying to add a click bind to the `icon-next` class if the `td` element doesn't have the `ui-disabled` class without using if statements if possible (no pun).
```
$(".icon-next:not(.ui-disabled)").bind('click',function(){});
``` | 2014/01/14 | [
"https://Stackoverflow.com/questions/21126287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/962449/"
] | You want to do it like this:
```
$("td:not(.ui-disabled) .icon-next").bind("click",function(){});
```
As [Johannes](https://stackoverflow.com/a/21126391/1879895) said, it would be a better idea to use [`.on()`](http://api.jquery.com/on/) in order to delegate the event in case the `.ui-disabled` class is removed.
```
$("body").on("click", "td:not(.ui-disabled) .icon-next", function(){});
``` | [Billy](https://stackoverflow.com/a/21126313/573634) was spot on with his code, though I would suggest you use [`.on()`](http://api.jquery.com/on/) instead and use a delegated event so that events are properly bound/unbound.
```
$('body').on("click", "td:not(.ui-disabled) .icon-next", function(){});
``` |
24,718,567 | "Free theorems" in the sense of Wadler's paper "Theorems for Free!" are equations about certain values are derived based only on their type. So that, for example,
```
f : {A : Set} → List A → List A
```
automatically satisfies
```
f . map g = map g . f
```
Can I get my hands on an Agda term, then, of the following type:
```
(f : {A : Set} → List A → List A) {B C : Set} (g : B → C) (xs : List B)
→ f (map g xs) ≡ map g (f xs)
```
or if so/if not, can I do something more/less general?
I'm aware of the existence of the [Lightweight Free Theorems library](http://wiki.portal.chalmers.se/agda/pmwiki.php?n=Libraries.LightweightFreeTheorems) but I don't think it does what I want (or if it does, I don't understand it well enough to do it).
(An example use case is that I have a functor `F : Set → Set` and would like to prove that a polymorphic function `F A × F B → F (A × B)` is automatically a natural transformation.) | 2014/07/13 | [
"https://Stackoverflow.com/questions/24718567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/812053/"
] | No, the type theory on which Agda is build is not strong enough to prove this. This would require a feature called "internalized parametricity", see the work by Guilhem:
* Jean-Philippe Bernardy and Guilhem Moulin: [*A Computational Interpretation of Parametricity*](http://publications.lib.chalmers.se/records/fulltext/local_147257.pdf) (2012)
* Guilhem Moulin: [*Pure Type Systems with an Internalized Parametricity Theorem*](http://publications.lib.chalmers.se/records/fulltext/191873/191873.pdf) (2013)
This would allow you for example to prove that all inhabitants of "(A : Set) → A → A" are equal to the (polymorphic) identity function. As far as I know, this has not been implemented in any language yet. | Chantal Keller and Marc Lasson developped a tactic for Coq generating the parametricity relation corresponding to a (closed) type and proving that this type's inhabitants satisfy the generated relation. You can find more details about this work on [Keller's website](http://cs.au.dk/~chkeller/Recherche/coqparam.html).
Now in Agda's case, it is in theory possible to do the same sort of work by implementing the tactic in pure Agda using a technique called reflection. |
13,756,474 | I have a problem that's been giving me grief for weeks now. I forgot about it for a while when I was updating to the new Facebook SDK, but now it's back to haunt my dreams.
I'm making basically a Facebook feed reader. It gets the JSON data from an API call and uses that to populate a ListView. Each time the custom adapter calls the getView() method, it checks to see what type of "status" it is. If it's a "photo" status, the view will have two images (a profile picture and the picture of the status update). I'm using nostra13's Universal Image Loader to load both images after inflating the ImageViews using a holder class to help recycle views. That's where I think my problem exists.
When I scroll through the list, all the profile pictures load fine and work great. But as I scroll, the status photos do a couple things:
1.) The all load the same image (I didn't have this problem before but I gave it to myself trying to fix the others).
2.) The images jump around and either disappear or appear in different views than they're supposed to.
3.) If the images load correctly and don't all show the same image, the images change as I scroll up and down, eventually all becoming the same image.
I'll post my getView() code (sorry it's kind of long).
```
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
try {
jsonObject = getItem(position);
jsonFrom = jsonObject.getJSONObject("from");
postType = jsonObject.getString("type");
posterName = jsonFrom.getString("name");
posterID = jsonFrom.getString("id");
posterPhoto = "http://graph.facebook.com/" + posterID
+ "/picture?type=square";
if (jsonObject.has("message")) {
posterMessage = jsonObject.getString("message");
} else {
posterMessage = jsonObject.getString("story");
}
} catch (JSONException e) {
e.printStackTrace();
}
if (postType.equals("status")) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.status_post_holder,null);
holder = new ViewHolder();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.posterName = (TextView) convertView.findViewById(R.id.posterName);
holder.posterMessage = (TextView) convertView.findViewById(R.id.posterMessage);
holder.posterProfilePhoto = (ImageView) convertView.findViewById(R.id.posterProfilePic);
if (jsonObject != null) {
holder.posterName.setText(posterName);
if (posterMessage != null) {
holder.posterMessage.setText(posterMessage);
} else {
holder.posterMessage.setText("No message for this post.");
}
profileImageLoader.displayImage(posterPhoto,
holder.posterProfilePhoto);
}
}
else if (postType.equals("photo")) {
if (convertView == null) {
try {
posterImageURL = jsonObject.getString("picture");
} catch (JSONException e) {
e.printStackTrace();
}
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.photo_post_holder, null);
holder = new ViewHolder();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.posterName = (TextView) convertView.findViewById(R.id.posterName);
holder.posterMessage = (TextView) convertView.findViewById(R.id.posterMessage);
holder.posterProfilePhoto = (ImageView) convertView.findViewById(R.id.posterProfilePic);
holder.posterImage = (ImageView) convertView.findViewById(R.id.posterImage);
if (jsonObject != null) {
holder.posterName.setText(posterName);
if (posterPhoto != null) {
profileImageLoader.displayImage(posterPhoto,holder.posterProfilePhoto);
}
if (posterImageURL != null) {
pictureImageLoader.displayImage(posterImageURL,holder.posterImage);
}
if (posterMessage != null) {
holder.posterMessage.setText(posterMessage);
} else {
holder.posterMessage.setText("No message for this post.");
}
}
}
else if (postType.equals("link")) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.status_post_holder,null);
holder = new ViewHolder();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.posterName = (TextView) convertView.findViewById(R.id.posterName);
holder.posterMessage = (TextView) convertView.findViewById(R.id.posterMessage);
holder.posterProfilePhoto = (ImageView) convertView.findViewById(R.id.posterProfilePic);
if (jsonObject != null) {
holder.posterName.setText(posterName);
if (posterMessage != null) {
holder.posterMessage.setText(posterMessage);
} else {
holder.posterMessage.setText("No message for this post.");
}
profileImageLoader.displayImage(posterPhoto,holder.posterProfilePhoto);
}
}
else {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.status_post_holder,null);
holder = new ViewHolder();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.posterName = (TextView) convertView.findViewById(R.id.posterName);
holder.posterMessage = (TextView) convertView.findViewById(R.id.posterMessage);
holder.posterProfilePhoto = (ImageView) convertView.findViewById(R.id.posterProfilePic);
if (jsonObject != null) {
holder.posterName.setText(posterName);
if (posterMessage != null) {
holder.posterMessage.setText(postType);
} else {
holder.posterMessage.setText("No message for this post.");
}
profileImageLoader.displayImage(posterPhoto,holder.posterProfilePhoto);
}
}
return convertView;
}
```
I'm sure it has something to do with Android recycling views and being efficient, but I can't figure out where I'm making the error. It's also weird that the problem only exists for the one image view. Any help would be hot. Thanks.
**UPDATE:** We discovered it was an error with my JSON parsing. You have to use setTag() to retain the image specific to that line item. The adapter was trying to set a tag of null to the view, which caused the NPE.
**UPDATE AGAIN:** After digging some more, it looks like it's the ImageView itself that's giving a null value as if it isn't finding the correct layout. I was using two different xml layouts for the different types of posts. So now it looks like the best solution would be to use the same layout and just conditionally inflate different elements in each view depending on the status type. | 2012/12/07 | [
"https://Stackoverflow.com/questions/13756474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1754999/"
] | please be specific during using and dealing with the image loader class.
If possible, don't create more instance of the same class. Instead of use the same instance in different way.
See below adapter class and try to integrate same in your case. which will help you.
```
private class OrderAdapter extends ArrayAdapter<User> {
private ArrayList<User> items;
Activity a;
public ImageLoader imageLoader;
public OrderAdapter(Context context, int textViewResourceId,ArrayList<User> items) {
super(context, textViewResourceId, items);
this.items = items;
// extra
/*if (Utility.model == null) {
Utility.model = new FriendsGetProfilePics();
}
Utility.model.setListener(this);*/
}
/*@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
super.isEmpty();
return false;
}*/
@Override
public View getView(final int position, View convertView,ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.add_buddies_row_new, null);
holder = new ViewHolder();
imageLoader = new ImageLoader(NotificationsActivity.this);
//--------------
//---------------------------------------------------------------------
// for head to head
holder.userName = (TextView) v.findViewById(R.id.txtName);
holder.userPic = (ImageView) v.findViewById(R.id.imgUserPic);
holder.userCity = (TextView) v.findViewById(R.id.txtCity);
holder.userState = (TextView) v.findViewById(R.id.txtstate);
holder.userCountry = (TextView) v.findViewById(R.id.txtContry);
//---------------------------------------------------------------------
v.setTag(holder);
}else{
holder=(ViewHolder)v.getTag();
}
final User o = items.get(position);
holder = (ViewHolder) v.getTag();
if (o != null) {
holder.userName.setText(o.getUserName());
holder.userCity.setText(o.getUserCity()+", ");
holder.userState.setText(o.getUserState()+", ");
holder.userCountry.setText(o.getUserCountry());
System.out.println("PIC: "+o.getUserPic());
holder.userPic.setTag(o.getUserPic());
imageLoader.DisplayImage(o.getUserPic(), a, holder.userPic);
}
return v;
}
}
class ViewHolder {
TextView userName ;
TextView userCity;
TextView userState;
TextView userCountry;
ImageView userPic ;
}
```
Comment me for any dought.
Note: YOU HAVE TO DO SOME CHANGES IN ABOVE CODE AS PER YOUR REQUIREMENT.
If your issue not solve with this then let me know.
It can also happend if you are getting null data so please be confirm with getting data. | I had same issue with view holder pattern and universal image loader.
I was checking my url before i call universal loader display image and if url was null i dit not download image just set imageview background drawable my no image drawable. On Listview scroll my listview images were mixed.
Then i tried to do not check url if its null and just set a no url drawable to universal image loader display image options. This fixed my problem. I don't know if it's a commont solution for this problem but you can try it. |
27,666,020 | I'm just wondering why the color of my border radius isn't changing, can someone please answer my question?
Code:
```
* {
font-family: 'lucida grande',tahoma,verdana,arial,sans-serif;
border: 0px;
padding: 0px;
background-image: url('http://clubpenguincode.com/other/background.png');
}
.header {
background-color: #008aff;
height: 72px;
width: 700px;
border-radius: 5px;
border-style: solid;
border-color: #ff0000 #0000ff;
}
``` | 2014/12/27 | [
"https://Stackoverflow.com/questions/27666020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4397514/"
] | You need to add a border width:
```
border-width: 1px;
``` | try adding `-webkit-` just before the border radius. |
27,795,496 | [ts-guide](http://docs.racket-lang.org/ts-guide/more.html#%28part._.Annotating_.Definitions%29) said:
>
> In addition to the `:` form, almost all binding forms from racket have counterparts which allow the specification of types.
>
>
>
But it does not say when to use which one.
And [ts-reference](http://docs.racket-lang.org/ts-reference/Legacy_Forms.html) said `form:` is legacy, for backwards compatibility.
But in ts-guide, `form:` are used in a lot of places.
So is `: v t` preferred than `form:`?
And what about `form`?
For example:
```
; form:
(define: (id [z : Number]) : Number z)
; : v t + form
(: id (-> Number Number))
(define (id z) z)
; form (it seems recent versions of Racket add this?)
(define (id [z : Number]) : Number z)
``` | 2015/01/06 | [
"https://Stackoverflow.com/questions/27795496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/222893/"
] | Do you need to preserve the history of both projects A & B, as much as possible?
If not, I would suggest the following approach:
* create a repo, and an initial empty commit.
* in addition to master, create two branches off the initial commit: A and B
* Put a snapshot of projects A and B into each respective branch.
At this point, use the existing tools you know how to use in order to find identical parts of both branches, and commit the identical parts to master. Then, you should be able to rebase both branches A and B onto the new commit on master.
Lather, rinse, repeat, and continue taking chunks of identical code from A and B, putting them into master, and rebasing on them. You can do this in small, incremental steps.
At each step of the way you should have a single commit on both A and B branch, that's forked off the master branch.
At some point you will reach the step where you need to look at the differences. Let's take the hypothetical situation of different names for the same variables on branches A and B.
Well, rename the variable on one branch to the other branch's name, and rebase-squash that, so you still have a single commit on the A and B branch. This should end up with more code becoming identical on both branches, which you can pull out, commit on master, then rebase both A and B branches on top of it.
When you reach the point when there's nothing common between A and B, with both of them being one commit away from master, and none of them changing the parts that overlap, then you should be able to merge one branch into the other; with maybe some minor conflict resolution.
At each step in this process, your changes should be fairly small, and you wouldn't need to use a complicated diff or merge tool to work through it.
I would also suggest that after you commit what you think is a common chunk of code to master, and trying to rebase both A and B on top of the master's new commit, tag both branches A and B, and if either one of them fails, you can restore the other branch's tip to the previous tag, get rid of the new commit on master, and then try again.
Another refinement on this process would be that instead of using two branches+master, after creating the initial repo, clone the repo directory twice, then use the two new repos as, essentially branches: after isolating identical code, commit that chunk to the parent repo, re-pull the parent repo in the children, and try to rebase the branches in the child repos. | It sounds like your initial commit to the repository is a copy of project A, which you've then branched from and on the branch replaced with B. Did you try making the parent commit just an empty commit? I think this would give git a better chance of correctly merging, as it's not then assuming that all the changes in project B are as a result of edits to project A. So your git tree would look like this:
```
* A
| * B
|/
* Initial Commit (empty)
```
With the magic of rebasing, you might even be able to start to put some genuinely common code into the parent, which might help too. |
2,183,368 | I want to do partial fraction expansion on $$\frac{1}{x^4+1}.$$
But how to I factor the denominator so that I get a product of two factors? | 2017/03/12 | [
"https://math.stackexchange.com/questions/2183368",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/377157/"
] | **hint**
$x^4+1=(x^2+1)^2-2x^2$
$=(x^2+1+x\sqrt{2})(x^2+1-x\sqrt{2})$ | Every quartic polynomial factors as the product of two quadratic ones. As both the coefficients of $x^4$ and $x^0$ are $1$, the factorization must be of the form
$$(x^2+ax+1)(x^2+bx+1).$$
Developing, you get
$$x^4+(a+b)x^3+(ab+2)x^2+(a+b)x+1.$$
Clearly, $a=-b=\pm\sqrt2$. |
8,582,417 | I want to make a directory list page for my site. The page show all my site articles. And these articles groupe by the title's first letter.
Must I run 26 times mysql query like
```
mysql query like "SELECT * FROM articles Where title like 'a%'"
mysql query like "SELECT * FROM articles Where title like 'b%'"
mysql query like "SELECT * FROM articles Where title like 'c%'"
...
mysql query like "SELECT * FROM articles Where title like 'z%'"
```
And My html output are:
```
<div class="content">
<p>A</p>
<a href="somelink">Anhui</a>
<a href="somelink">Aomen</a>
</div>
<div class="content">
<p>B</p>
<a href="somelink">Beijing</a>
</div>
<div class="content">
<p>C</p>
<a href="somelink">Chongqing</a>
</div>
...
<div class="content">
<p>Z</p>
<a href="somelink">Zhejiang</a>
</div>
```
So is there any good advise that I shall do less mysql query and get the same result? Thanks. | 2011/12/20 | [
"https://Stackoverflow.com/questions/8582417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/783396/"
] | No. Make a single query, and order them alphabetically, like so:
```
SELECT * FROM articles ORDER BY title ASC
```
Then, as you loop through them to show them, keep track of the last article you showed. If the first letter of the current article is different than the last's, put your separation.
```
$prevFirstLetter = '';
while($data = nextResult()) {
$firstLetter = substr($data['title'], 0, 1);
if ($firstLetter != $prevFirstLetter)
echo "<h1>$firstLetter</h1>";
echo "{$data['title']}<br>";
$prevFirstLetter = $firstLetter;
}
``` | You could select everything, in one query, and order by title name. Then, in your PHP code, you need some logic to break over the recordset whenever you encounter a change in the first letter. |
65,730,513 | QUESTION: Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.
Notes:
Only lower case letters will be used (a-z). No punctuation or digits will be included.
Performance needs to be considered
```
MY CODE:
s1 = 'rkqodlw'
s2 = 'world'
def scramble(s1, s2):
unscrambled_word = []
n = 0
x = 0
s1_list = list(s1)
s2_list = list(s2)
s1_letter = s1_list[n]
s2_letter = s2_list[x]
for letters in range(len(s2_list)):
while n > len(s1_list):
if s1_letter == s2_letter:
n = n + 1
x = x + 1
else:
n = n + 1
return 'True' if x == len(s2_list) else 'False'
```
I am trying to get my code to dissect each of the two strings. If the word of the first string does not match the word of the second string then n will +1 and move onto the second letter. If it matches then both n and x will + 1. My thought on my code is if x == the length of the second string before the giant loop ends then it will return True. Otherwise False. The problem is with the loop. The loop only seems to run through the first two letters of both strings and then stops. I am a fairly new coder any input is greatly appreciated! Thanks! | 2021/01/15 | [
"https://Stackoverflow.com/questions/65730513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15001512/"
] | You just need to make sure the letters in str2 are all present in str1 in sufficient quantities
```py
def scramble(str1,str2):
d1 = {}
for c in str1:
if not c in d1:
d1[c] = 0
d1[c] += 1
for c in str2:
if not c in d1 or d1[c] < 1:
return False
d1[c] -= 1
return True
```
The ideas is to go through all the characters in str2 and if for example, str2 has three "a" letters, make sure that str1 has at least three "a" letters. This requires counting the number of times each character occurs in str1. This is most naturally done with a dictionary. A dictionary maps things, called keys, to other things, called values. In this case we map keys which are single characters to a values which are numeric counts.
First step is to create an empty dictionary `d1={}`.
Next is to go character by character in str1 which is the first for loop. For each of these characters, we ask if this character has ever been previously placed into d1. If it has not, then we create a new mapping within d1 for that character to a starting value of zero. Every time a character is encountered in this loop through str1, the count value mapped from that character in d1 is incremented by 1. After the first for loop (that goes through str1) is complete, the dictionary contains counts of every letter in str1.
The next idea is to iterate through every character in str2. If it is a character not present in d1, then that means the character was not present in str1, so str1 is missing a character it would need to scramble into str2. At that point, you can stop processing and just return False.
Otherwise, if you only encounter characters that exist as keys in d1, you subtract one from the d1 mapped count value every time you encounter that character while for looping through str2. If the subtraction would ever cause the d1 count value to go below zero, then that means str2 has a higher number of that particular character than str1 had, so once again str1 cannot scramble into str2. Therefore you can return False at that point and stop processing.
Finally, if we make it through the entire 2nd loop (through str2) without encountering either of the return False cases mentioned above, that means that str1 has at least as many of every character that str2 has and can therefore scramble into str2 using some of its letters. You then return True. | Alternative:
```
s1 = 'rkqodlw'
s2 = 'world'
def scramble(s1, s2):
s1_list = list(s1)
for char in s2:
if char in s1_list:
s1_list.pop(s1_list.index(char))
else:
return False
return True
print(scramble(s1,s2))
```
Here's how it works: You run through the loop for each letter in s2, and if that letter is also in a list version of s1, you delete it from that list version. That way, if s2 was `'rabbit'` for example, and s1 was `'braintrain'`, you would meet the first `'r'`, `'a'`, and the first `'b'`, delete it from `'braintrain'` to get `'intrain'`, and the next `'b'`would then fail the test and a `False` would be returned. If there were enough `'b'`s though, the scrambler would return `True`. The final `True`is returned if the test is never failed (that is, all letters in s2 are also in s1) when the function finishes. |
6,813,948 | I'm working on REST web-service written with jersey and I'm trying to output some XML with CDATA sections in it. I understand [the reference implementation of JAXB doesn't support that](https://stackoverflow.com/questions/3136375/how-to-generate-cdata-block-using-jaxb/3153660#3153660), so I've downloaded EclipseLink's MOXy and I'm trying to get the @XmlCDATA annotation to work.
My JAXB mapped bean looks like this
```
package com.me.entities;
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD)
public class MyBean {
@XmlAttribute
private URI thumbnail;
@XmlElement(name="longdescription") @XmlCDATA
private String description;
public MyBean() { }
public final String getDescription() { return description; }
public final void setDescription(String d) { this.description = d; }
}
```
and I have the `jaxb.properties` file in the `com/me/entities` along with the class files. The properties file has
```
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
```
in it. I'm sure it gets loaded successfully since if I replace the factory class name with some nonsense the app breaks down. Also, explicitly marshaling the file creating the JAXBContext on my own works fine, so the problem seems related to jersey. According to [this](http://bdoughan.blogspot.com/2010/07/cdata-cdata-run-run-data-run.html) my setup is fine, but when my jersey resource returns an instance of MyBean
```
...
@GET @Produces(MediaType.TEXT_XML)
public MyBean getMyBean() {
MyBean b = new MyBean();
b.setDescription("Some blurb plenty of invalid chars like <<< && >>>");
return b;
}
```
what I get back has no CDATA in it, but looks like
```
<?xml version="1.0" encoding="UTF-8"?>
<info><longdescription>Some blurb plenty of invalid chars like <<< && >>></longdescription></info>
```
What am I doing wrong? | 2011/07/25 | [
"https://Stackoverflow.com/questions/6813948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6069/"
] | Looks like the problem was my application server: I am running this with **WebLogic 10.3.5** in development mode, which comes with a lot of common libraries pre-installed that in the default configuration take precedence over those deployed in the webapp `WEB-INF/lib` folder.
To fix this a weblogic specific application description is needed, just create a `weblogic.xml` file inside `WEB-INF` containing the `prefer-web-inf-classes` option. The file I used is this:
```
<?xml version='1.0' standalone='yes'?>
<weblogic-web-app>
<container-descriptor>
<prefer-web-inf-classes>true</prefer-web-inf-classes>
</container-descriptor>
</weblogic-web-app>
```
I still have no idea which library was the problem though, anyone knows feel free to edit this answer. | Please download Jaxb Extension:
This is Eclipselink open source extension for Jaxb.
Get jar file: eclipselink.jar copy into Project lib.
```
http://www.eclipse.org/eclipselink/downloads/
EclipseLink 2.4.1 Installer Zip (37 MB)
```
And see example at:
<http://theopentutorials.com/tutorials/java/jaxb/jaxb-marshalling-and-unmarshalling-cdata-block-using-eclipselink-moxy/>
Good look!. |
13,410,507 | I'm doing this...
```
<?php $term = ucfirst($_GET['term']);?>
```
And doing this multiple times on the page:
```
<?php if (empty($term)) echo 'X'; else echo $term; ?>
```
Is there a better way to go about this? | 2012/11/16 | [
"https://Stackoverflow.com/questions/13410507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373779/"
] | You can specify the placeholder value when you first assign the value:
```
<?php $term = ucfirst($_GET['term']) or $term = "X"; ?>
```
(Works because the OR has lower precedence than the assignment.)
Then just print that variable henceforth:
```
<?= $term ?>
```
It will contain either the input value, or your `X`. | ```
<?php
$term = isset($_GET['term']) ? ucfirst($_GET['term']) : 'X';
echo $term;
//...
?>
```
If you don't need it anywhere else than you could make it even shorter :-)
```
echo (isset($_GET['term']) ? ucfirst($_GET['term']) : 'X');
``` |
10,713 | I'm interested in running a promotion ...
I'd like to make a product free if the customer's cart total is $10.
I was able to do that with this module: <http://drupal.org/project/uc_discounts_alt>
Everything is working great, but I don't want my customer to be able to add the product to their cart unless they are buying $10 worth of regular products.
The products I'm giving away could be placed in another ubercart class, but I can't find a module that will allow me to prevent the node from being sold unless the cart total is $10 or more.
Any ideas or help would be greatly appreciated.
I've already explored the "free" checkout options; I'm really simply looking how to make a product not sellable unless the cart total has a minimum of $10. | 2011/09/06 | [
"https://drupal.stackexchange.com/questions/10713",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/1813/"
] | To prevent your customers to add the product to their cart if it's $10 with regular products, You can use ubercart [hook\_add\_to\_cart](http://drupalcontrib.org/api/drupal/contributions!ubercart!docs!hooks.php/function/hook_add_to_cart/6) .
for example:
```
function MODULENAME_add_to_cart($nid, $qty, $data) {
$contents= uc_cart_get_contents();
//check your condition such as total, and product type based on cart contents
if (condition true) {
$result[] = array(
'success' => FALSE,
'message' => t('Sorry, you can not add this product now!.'),
);
}
return $result;
}
``` | Rules can be the better solution to it as you don't want to restrict the user every time but just on some special products. Here is a general flow of what you can do.
1. Add a cck/ubercart class to the products that you want to add to the promotion
2. Then create a rule, and in there, add a condition to check whether that field which you added is set. If so, don't, add an action to not allow user to proceed to checkout.
This should work as far as I know. |
3,895,954 | I need a clarification regarding the difference between the NSString and NSMutableString. Can any one expand briefly? | 2010/10/09 | [
"https://Stackoverflow.com/questions/3895954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/466377/"
] | An NSString instance cannot be modified once it's initialized - it is "immutable." No NSString methods can modify the string's value.
NSMutableString on the other hand can be modified after it's initialized. | Just to expand on Andy White's answer, there may be performance benefits to using NSString instead of NSMutableString in your code (as always, test using Apple's performance tools to make sure this is truly where your performance bottleneck is). In the situation where you want to change the value of an NSString, one option is to create a entirely new NSString with the altered value in it and then destroy the old NSString. |
8,042,065 | I am creating a file based on the another. So if the original is called doc.txt and is in myDocs I want to have it called docv2.txt and also saved in myDocs.
All I need is to define the new files path I can do the rest. Please help me determine what that path would be. | 2011/11/07 | [
"https://Stackoverflow.com/questions/8042065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1011477/"
] | Use a queue instead of a list. Enqueue the dequeued item for each step.
Another alternative is to use a circular buffer. Just keep the array as is and have a pointer to the first element, move the pointer on each step. Read the array in two phases. 1. From the pointer to the end. 2. From the beginning to the pointer.
A third alternative is to just swap element one by one.
```
int tmp = arr[0];
for(int i = 0; i < arr.Length - 1; i++)
{
arr[i] = arr[i+1];
}
arr[arr.Length - 1] = tmp;
``` | You just want to rotate the array?
```
// Rotate left
int temp = a[0];
for (int i = 0; i < a.Length-1; ++i)
a[i] = a[i+1];
a[a.Length-1] = temp;
// Rotate right
int temp = a[a.Length-1];
for (int i = a.Length-1; i > 0; --i)
a[i] = a[i-1];
a[0] = temp;
``` |
1,294,901 | $$12-\sin(\theta)=\cos(2\theta)$$
What's the correct answer on the $[0,2\pi]$?
I started with $12-\sin(\theta)=1-2\sin^2(\theta)$ and then i cant get anything sensible as i end up with $12=\sin(\theta)+2\sin^2(\theta)$ | 2015/05/23 | [
"https://math.stackexchange.com/questions/1294901",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242803/"
] | you are almost there. $$2\sin^2 \theta + \sin \theta - 12=0 $$ so $$\sin \theta = \frac{-1 \pm \sqrt{49}}{4} = -2, \frac32$$ neither of them leads to a solution for $\theta.$
we should have seen this from the equation itself. reason is $$1 \ge |\cos 2\theta| = |12 - \sin \theta | \ge 11$$ a contradiction. | From
>
> $$12-\sin(\theta)=\cos(2\theta)$$
>
>
>
you get
$$12-\sin(\theta)=\cos^2(\theta)-\sin^2(\theta),$$
this is
$$12-\sin(\theta)=1-2\sin^2(\theta).$$
Hence
$$2\sin^2(\theta)-\sin(\theta)+11=0$$
and
$$\sin(\theta)=\frac{1\pm\sqrt{1-4\cdot2\cdot11}}{4}=\frac{1\pm\sqrt{-87}}{4}.$$
So, no real solution for $\sin(\theta)$ means no real solution for $\theta$ and, in particular, no solution $\theta\in[0,2\pi)$.
Indeed, $12-\sin(\theta)\in[11,13]$ while $\cos(2\theta)\in[-1,1]$, for all $\theta\in\Bbb R$. |
8,600,657 | What should be straight forward is not here and I couldnt find a way yet in spite of reading a lot.
I have a button which executes a time consuming function. So on clicking the button should show time elapsed in milliseconds in a label with an interval of 500 ms. And when the desired result is achieved I want the timer to stop. **I dont just need the final time (the total time consumed) in a label, but the label should dynamically show the time being elapsed.** My code would be:
```
private void btnHistory_Click(object sender, EventArgs e)
{
Class1 c = new Class1();
c.StartClock(ref label12);
Utility.PopulateHistory(dgvRecords_history, _util); //time consuming function
c.StopClock();
}
```
And in `Class1` I write this:
```
internal void StartClock(ref Label l)
{
Timer t = new Timer();
t.Interval = 500;
t.Enabled = true;
t.Tag = l;
t.Tick += new EventHandler(t_Tick);
t.Start();
}
int i;
bool stop;
void t_Tick(object sender, EventArgs e)
{
if (stop)
{
((Timer)sender).Stop();
return;
}
((Label)((Timer)sender).Tag).Text = (++i).ToString();
}
internal void StopClock()
{
i = 0;
stop = true;
}
```
What happens is, the `t_Tick` event is fired only after the complete code under button event is fired. That is the tick event is fired after it goes through the StopClock function! I got no idea why on earth it should be that!
2 questions basically:
1. How can my requirement be achieved in the right way to handle these? I know I should use other built in classes to evaluate performance, but this is just for display purpose. For this, what is the ideal approach?
2. Why is my code not working?
EDIT: I have used here `System.Windows.Forms Timer` here, but the result is not any different with `System.Timers Timer` | 2011/12/22 | [
"https://Stackoverflow.com/questions/8600657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/661933/"
] | The problem is that your long-running task is also running on the UI thread. So the timer can't fire and update the UI, since the thread is busy handling the long-running task.
Instead, you should use a [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) to handle the long-running task.
In code:
```
private void btnHistory_Click(object sender, EventArgs e)
{
Class1 c = new Class1(ref label12);
c.StartClock();
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (s, e) =>
{
// time consuming function
Utility.PopulateHistory(dgvRecords_history, _util);
};
backgroundWorker.RunWorkerCompleted += (s, e) =>
{
c.StopClock();
};
backgroundWorker.RunWorkerAsync();
}
```
As ChrisWue noted, since you now have the long-running task in a separate thread, it needs to invoke any access to the UI controls on the UI thread.
If your long-running task just needs some data from the UI to start, you can pass that data as parameter of `RunWorkerAsync()`. If you need to output some result data to the UI, you can do that in the handler of the `RunWorkerCompleted` event. If you occasionally need to update the UI as progress is being made, you can do that in the handler of the `ProgressChanged` event, calling `ReportProgress()` in your DoWork handler.
If none of the above are needed, you could use the ThreadPool, as in StaWho's answer. | Your time consuming function is blocking the main thread. You can use `BackgroundWorker` or below trick:
```
public Form1()
{
InitializeComponent();
t.Tick +=new EventHandler(t_Tick);
t.Interval = 500;
}
int timeElapsed = 0;
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
private void button1_Click(object sender, EventArgs e)
{
t.Start();
ThreadPool.QueueUserWorkItem((x) =>
{
TimeConsumingFunction();
});
}
void TimeConsumingFunction()
{
Thread.Sleep(10000);
t.Stop();
}
void t_Tick(object sender, EventArgs e)
{
timeElapsed += t.Interval;
label1.Text = timeElapsed.ToString();
}
``` |
16,146,401 | I have this db table
```
CREATE TABLE IF NOT EXISTS `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`inherit` enum('Y','N') NOT NULL DEFAULT 'N',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
--
-- Dumping data for table `category`
--
INSERT INTO `category` (`id`, `parent_id`, `name`, `inherit`) VALUES
(1, 0, 'Fruits', 'N'),
(2, 0, 'Electronics', 'N'),
(3, 0, 'Furniture', 'N'),
(4, 0, 'Garden', 'N'),
(5, 1, 'Apples', 'N'),
(6, 1, 'Bananas', 'N'),
(7, 5, 'Green Apples', 'Y'),
(8, 5, 'Red Apples', 'N'),
(9, 2, 'Mobiles', 'Y'),
(10, 2, 'Televisions', 'N'),
(11, 9, 'Android', 'N'),
(12, 9, 'iPhone', 'Y'),
(13, 7, 'One Dozen Green Apples', 'Y'),
(14, 7, 'Two Dozens Green Apples', 'N');
```
There is another table where I keep user\_id, category\_id e.g.
user\_id 1000 can see 1 and 5, I put this info in the sessions so that my query becomes
```
SELECT *
FROM `category`
WHERE id
IN ( 1, 5 )
```
this query shows `Fruits > Apples` - all this works fine. But, I have marked "`Green Apples`" as `Inherit = 'Yes'` so user 1000 should see "`Green Apples`" too but not "`Red Apples`". If there are sub-categories under Green Apples marked as inherit = 'Y'... e.g. "One Dozen Green Apples" should be listed too!!
I thought to give UNION a go but can't figure out how to get more than 2 levels deeper ...
```
SELECT * FROM (
SELECT *
FROM `category`
WHERE id
IN ( 1, 5 )
UNION
SELECT c.*
FROM `category` c
INNER JOIN `category` parent ON parent.id = c.id AND c.inherit = 'Y'
WHERE c.parent_id
IN ( 1, 5 )
) all_cats
```
What would you suggest to me? I am open table structure changes if that'd make querying any easier? thanks | 2013/04/22 | [
"https://Stackoverflow.com/questions/16146401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1421214/"
] | To get all categories with one query in mysql you will need as many self-joins as there are levels of depth in your category tree.
This is obviously impossible if your depth level is not limited.
However you can use a stored procedure to do id.
Assuming you have a table with categories for a user like:
```
CREATE TABLE IF NOT EXISTS `user_category` (
`user_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
PRIMARY KEY (`user_id`,`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
```
with some data like:
```
INSERT INTO `user_category` ( `user_id`, `category_id` ) VALUES
( 1000, 1 ),
( 1000, 5 );
```
you can create a temporary table `cat_tree` storing id's of categories, initialize it with all parent categories for a given user\_id from the user\_category table and repeat self-joins down the tree as long as the last join inserted at least one category that wasn't there yet.
```
DELIMITER //
DROP PROCEDURE IF EXISTS show_user_categories//
CREATE PROCEDURE show_user_categories( uid INT(11) )
BEGIN
DECLARE found INT(11) DEFAULT 1;
DROP TABLE IF EXISTS cat_tree;
CREATE TABLE cat_tree (cat_id int(11) PRIMARY KEY) ENGINE=HEAP;
INSERT INTO cat_tree
SELECT category_id FROM user_category
WHERE user_id = uid;
SET found = ROW_COUNT();
WHILE found > 0 DO
INSERT IGNORE INTO cat_tree
SELECT c_child.id FROM cat_tree c JOIN category c_child
WHERE c.cat_id = c_child.parent_id AND c_child.inherit = 'Y';
SET found = ROW_COUNT();
END WHILE;
SELECT cat_id FROM cat_tree;
DROP TABLE cat_tree;
END;//
DELIMITER ;
```
This procedure gives you a full list of category id's for a given user\_id.
```
CALL show_user_categories( 1000 );
```
See a working example at [sqlfiddle](http://sqlfiddle.com/#!2/a618f/1). | In SQL Server:
```
;with CTE as
(
select id,name from category where id in(1,5)
union all
select c.id,c.name from category c join CTE ct on c.parent_id=ct.id and c.inherit='Y'
)
select * from CTE
``` |
2,757,195 | For any square matrix $C$ with real entries, denote by $\rho(C)$ its spectral radius, i.e. the maximum magnitude of its eigenvalues. For symmetric matrices $A$ and $B$ with $AB=BA$ show that $$\rho(AB)\le \rho(A)\rho(B)$$
I think simultaneous diagonalization of $A$ and $B$ is to be used here, but couldn't find my way out.
Also will the proposition hold if the condition of symmetry is dropped? | 2018/04/28 | [
"https://math.stackexchange.com/questions/2757195",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/91884/"
] | Since both matricea are simultaneously diagonalizable you can also simultaneously diagonlize $AB$ and find a link between its eigenvalues and the eigenvalues of $A$ and $B$.
A further hint: Calculate $P^{-1}AP\cdot P^{-1}BP$ | If $A$ and $B$ are symmetric with $AB = BA$, you have the following even simpler proof :
$$\|AB\|\_2 = \sqrt{\rho((AB)^TAB)} = \sqrt{\rho((AB)^2)} = \rho(AB)$$
so that by sub-multiplicativity of the spectral norm, $\rho(AB) \leq \|A\|\_2 \cdot \|B\|\_2$ and the result follows by symmetry of $A$ and $B$ for which $\|\cdot\|\_2 = \rho$. |
68,242,451 | I have a code
```
char str1[15];
char str2[15];
memcpy(str1,"abcdef",6);
memcpy(str2,"abcdef",6);
```
so str1 should have null termination at index 7.
but when I do `printf("--%d--",strlen(str1));` it prints `--9--` which is why its making me think that `memcpy` is not considering null termination when copy into `str1` the string literal `"abcdef".
so shouldnt it also read null termination or is something I did in printf gives me print `--9--`? | 2021/07/04 | [
"https://Stackoverflow.com/questions/68242451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4808760/"
] | Give searchbar `z-index:50` and `z-index:10` to sidebar. This way searchbar will stay beneath the sidebar. | navbar :
position:'sticky'
main:
z-index:100 |
34,154,324 | I'm interested in reordering a list in such a manner as to maximize the sum of the squares of the differences between adjacent elements (cyclic). Here is a piece of Python code that brute-forces the solution in factorial time, so you can see what I mean:
```
def maximal_difference_reorder(input):
from itertools import permutations
best_sum = 0
best_orderings = []
for x in permutations(input):
d = np.sum(np.diff(x)**2) + (x[0] - x[-1])**2
if d > best_sum:
best_orderings = [x]
best_sum = d
elif d == best_sum:
best_orderings.append(x)
return best_orderings
```
This yields the following results for `maximal_difference_reorder(range(4))`:
```
[(0, 2, 1, 3),
(0, 3, 1, 2),
(1, 2, 0, 3),
(1, 3, 0, 2),
(2, 0, 3, 1),
(2, 1, 3, 0),
(3, 0, 2, 1),
(3, 1, 2, 0)]
```
As you can see, all the results are cyclic rotations and reflections of each other. If the score was determined with the sum of the differences, not squared, I believe all permutations would be evenly scored, given an evenly-spaced input.
Brute forcing works well, but O(n!) is terrible, so is it possible to do this in a smaller asymptotic computational time? Bonus points if it works for an uneven input mesh, or for other scoring functions.
Incidentally, this isn't homework or an interview question, though perhaps it would make a good one. Rather, I'm trying to generate a spectrum of colours for a series of parameterised data, and I'm trying to avoid having similar colours next to each other. | 2015/12/08 | [
"https://Stackoverflow.com/questions/34154324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/465750/"
] | Your problem is a slightly disguised instance of the [Traveling Salesman Problem](https://en.wikipedia.org/wiki/Travelling_salesman_problem).
Call the input list `c` (for "cities"). Pick any `M` which is an upper bound on `(c[i]-c[j])**2` This is easily done in linear time since the min and the max of the list can be computed in a single pass, in which case `M = (max - min)**2` works. Define the distance, `d[i,j]` from `c[i]` to `c[j]` by:
```
d(i,j) = 0 if i == j else M - (c[i]-c[j])**2
```
It is easy to see that for any cyclic permutation the cost of that permutation (computed according to `d`) is `n*M - sum of squares of differences` hence it is minimized if and only the sum of the squares of the differences is maximized.
There are a wealth of approaches to solving a TSP. Even though it is NP-hard, in practice state-of-the art methods are phenomenally good at solving problems that arise in practice. Furthermore, good heuristic methods can typically get to within a fraction of a percent of optimal.
Your particular problem is a special case of a TSP. As such it is possible that this special case is easier and in fact has a polynomial time solution, but I doubt it. I conjecture that it is NP-hard as well but don't have a proof. Also -- even if it is NP-hard, it might be that there is a solution (perhaps an Integer Programming formulation) which is more efficient than reducing it to TSP as above.
On Edit: based on comments by Dave Gavin and the answer by @SergeBallesta I now think that a polynomial time algorithm is possible. I'll leave this answer up, if for no other reason than if a polynomial time algorithm works then this problem would be a nice example for showing that certain subclasses of the TSP have simpler solutions. | I think we can have an O(n) solution
The key to solve this problem is to generate the first seed for the cyclic group. Considering we should be pairing the elements wherein the pairwise square difference sum is maximum which is possible if we pair an element with its farthest neighbor.
Which means if hi is the ith highest number, then the neighbors of hi are (hn-i-1, hn-i+1). As the sequence is cyclic so the numbers would wrap around for negative index i.e. h-1 = h0
This will generate the first seed list as `[0, 6, 2, 4, 3, 5, 1, 7]`
This sequence can easily be generating by swapping every odd index pair i.e. [(a1, an-1), (a3, an-3),...]
The subsequent sequence can be generated by generating a singular sequential rotation and then reflecting the rotated sequence
Here is a sample implementation
```
def maximal_difference_reorder1(x):
def maximal_difference_seeder(x):
for i in range(1, len(x) / 2):
x[i:len(x) - i] = x[i:len(x) - i][::-1]
return x
def rotate_left(x):
start = x
while True:
x = x[1:] + x[0:1]
if x == start: break
yield x
x = maximal_difference_seeder(x)
rotated = [x] + (list(rotate_left(x)) if len(x) > 1 else [])
reflected = [e[::-1] for e in rotated] if len(x) > 2 else []
return map(tuple, rotated + reflected)
```
**Sample Run**
```
def display(lst, width = 80):
it_lst = iter(lst)
try:
print '[',
while True:
for _ in range(80/(len(lst[0])*3 + 2)):
print "{},".format(next(it_lst)),
print '\n ',
except StopIteration:
print ']'
display(maximal_difference_reorder1(range(10)))
[ (0, 8, 2, 6, 4, 5, 3, 7, 1, 9), (8, 2, 6, 4, 5, 3, 7, 1, 9, 0),
(2, 6, 4, 5, 3, 7, 1, 9, 0, 8), (6, 4, 5, 3, 7, 1, 9, 0, 8, 2),
(4, 5, 3, 7, 1, 9, 0, 8, 2, 6), (5, 3, 7, 1, 9, 0, 8, 2, 6, 4),
(3, 7, 1, 9, 0, 8, 2, 6, 4, 5), (7, 1, 9, 0, 8, 2, 6, 4, 5, 3),
(1, 9, 0, 8, 2, 6, 4, 5, 3, 7), (9, 0, 8, 2, 6, 4, 5, 3, 7, 1),
(9, 1, 7, 3, 5, 4, 6, 2, 8, 0), (0, 9, 1, 7, 3, 5, 4, 6, 2, 8),
(8, 0, 9, 1, 7, 3, 5, 4, 6, 2), (2, 8, 0, 9, 1, 7, 3, 5, 4, 6),
(6, 2, 8, 0, 9, 1, 7, 3, 5, 4), (4, 6, 2, 8, 0, 9, 1, 7, 3, 5),
(5, 4, 6, 2, 8, 0, 9, 1, 7, 3), (3, 5, 4, 6, 2, 8, 0, 9, 1, 7),
(7, 3, 5, 4, 6, 2, 8, 0, 9, 1), (1, 7, 3, 5, 4, 6, 2, 8, 0, 9),
]
```
**Note** It is assumed that the data is sorted. If not, it is trivial to sort it wherein the solution complexity would be O(nlog n) |
27,693,332 | I am trying to do an off-canvas sidebar and I am using the `.toggleClass` function to make it active or not. When it is active I would like the button (.btn) to say "hide" and when it is not say "show". I have already tried to do an if statement and it has failed. I have also looked at other stackoverflow questions with no success. Can anybody help with how to detect a class has been toggled or not?
```
$(document).ready(function () {
$('[data-toggle="offcanvas"]').click(function () {
$('.row-offcanvas').toggleClass('active');
// if active "hide"
$('.btn').html("HIDE");
// if not active "show"
$('.btn').html("SHOW");
});
});
``` | 2014/12/29 | [
"https://Stackoverflow.com/questions/27693332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3582087/"
] | You should have another way to select your objects, for example by id, as follows:
```
$("#myid")...
```
Then you can use the hasClass function (<http://api.jquery.com/hasclass/>) to verify if the class has already been added to the object.
```
$("#myid").hasClass("xxx")
``` | I think you are looking for something like this. You just need to add an if/else statement to check the class
```
$(document).ready(function () {
$('[data-toggle="offcanvas"]').click(function () {
$('.row-offcanvas').toggleClass('active');
if ($('.row-offcanvas').hasClass('active')){
$('.btn').html("HIDE");
}
else{
$('.btn').html("SHOW");
}
});
});
```
<http://jsfiddle.net/GregWebBandit/Lmfok39k/> |
21,660,346 | I am learning about recursion in python and I have this code:
```
def search(l,key):
"""
locates key in list l. if present, returns location as an index;
else returns False.
PRE: l is a list.
POST: l is unchanged; returns i such that l[i] == key; False otherwise.
"""
if l: # checks if list exists
if l[0] == key: # base case - first index is key
return True
s = search(l[1:], key) # recursion
if s is not False:
return s
return False # returns false if key not found
```
Can someone explain to me what the line
```
s = search(l[1:], key)
```
does exactly? and what does l[1:] do to the list? | 2014/02/09 | [
"https://Stackoverflow.com/questions/21660346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3267920/"
] | It recursively calls the `search` function, with the sliced data from `l`. `l[1:]` means all the data excluding the elements till the index `1`. For example,
```
data = [1, 2, 3, 4, 5]
print data[1:] # [2, 3, 4, 5]
print data[2:] # [3, 4, 5]
```
You can use the slicing notation to get values between ranges, for example
```
print data[1:4] # [2, 3, 4]
print data[2:3] # [3]
```
You can also get all the elements till the specific index (excluding the element at the index)
```
print data[:4] # [1, 2, 3, 4]
print data[:3] # [1, 2, 3]
```
Sometimes you may not know the index of the elements from the end. So, you can use negative indices, like this
```
print data[-2:] # [4, 5]
print data[1:-2] # [2, 3]
print data[:-3] # [1, 2]
```
When you use negative indices, the last element is represented with `-1`, last but one with `-2` and so on. You can read more about this slicing notation in this [excellent answer.](https://stackoverflow.com/questions/509211/pythons-slice-notation) | Cool. This is where the recursion happens (as you noted), by calling the function itself given the same `key` but a subset of the list `l` (the first element isn't included).
Basically, it will keep doing this until the `key` is found in the list. If so, `True` will be returned. Otherwise, the entire list will be gone over until the list is empty (all elements have been checked for equality with `key`. At that point, the algorithm gives up and returns `False`.
This will just tell you if the `key` is in the list but not what index can be found at. |
21,447,554 | Hi There so I have a project that basically finds all numbers i have and multiplies them by 2. I have it like 90% done but for the other 10% certain inputs don't work.
So my code finds all the numbers in a user input and multiplies them by 2.
(eg. 123woah becomes 246woah and woah888 becomes woah1776)
Can anyone find my error and explain to me what i need to do?
EDIT: For example a case that doesn't work is like 1abc1. The code doesn't work if the numbers are in different spots.
Thanks
```
import java.util.Scanner;
public class MultiplyBy2
{
public static void main(String[] args)
{
int EXIT = 0;
while(EXIT == 0)
{
Scanner kbReader = new Scanner(System.in);
System.out.println("input?");
String String1 = kbReader.nextLine();
if(String1.equalsIgnoreCase("exit"))
{
break;
}
else
{
String String2 = String1;
String1 = String1.replaceAll("\\D", "");
int i = Integer.parseInt(String1);
int j = i * 2 ;
String2 = String2.replaceAll("" + i, "" + j);
System.out.println(String2);
}
}
}
}
``` | 2014/01/30 | [
"https://Stackoverflow.com/questions/21447554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3201634/"
] | In a Little Endian architecture, the integer value 0x1 will be written out in memory like
```
0x1 0x0 0x0 ....
```
so that function will return 1
Conversely, in a Big Endian architecture, the order of bytes will be
```
0x0 0x0 ... 0x1
```
however many bytes are in an int (greater or equal to 2 for it to work), and so
this function will return 0.
Here's a reference for why it [can't be done in Java directly](https://stackoverflow.com/questions/362384/are-integers-in-java-little-endian-or-big-endian), but you could use [JNI](http://en.wikipedia.org/wiki/Java_Native_Interface) to escape out to a C library and return the result. | You may use System.getProperty("sun.cpu.endian"). Alternately, you may use SIGAR (<https://github.com/hyperic/sigar>), Java native access, JNI etc. to get this information. |
45,012,289 | When I use call getFromLocationName I get an IOException with description "grpc failed".
Code that's ran
```
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> listAdresses = geocoder.getFromLocationName("London", 10);
Log.i("PlaceInfo", listAdresses.get(0).toString());
} catch (IOException e) {
e.printStackTrace();
}
}
```
Error the console outputs:
```
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: java.io.IOException: grpc failed
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: at android.location.Geocoder.getFromLocationName(Geocoder.java:178)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: at co.siqve.maplocationdemo.MapsActivity.onMapReady(MapsActivity.java:70)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: at com.google.android.gms.maps.zzaj.zza(Unknown Source)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: at com.google.android.gms.maps.internal.zzaq.onTransact(Unknown Source)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: at android.os.Binder.transact(Binder.java:499)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: at com.google.android.gms.maps.internal.aq.a(:com.google.android.gms.DynamiteModulesB:5)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: at com.google.maps.api.android.lib6.impl.bb.run(:com.google.android.gms.DynamiteModulesB:5)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: at android.os.Looper.loop(Looper.java:154)
07-10 12:01:38.781 13712-13712/co.siqve.maplocationdemo W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
07-10 12:01:38.782 13712-13712/co.siqve.maplocationdemo W/System.err: at java.lang.reflect.Method.invoke(Native Method)
07-10 12:01:38.782 13712-13712/co.siqve.maplocationdemo W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
07-10 12:01:38.782 13712-13712/co.siqve.maplocationdemo W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
```
Android SDK Version (API Level): 25
Android Studio plugins are up to date.
Thanks in advance!
**EDIT:**
Problem seems to be fixed now, here is my [solution.](https://stackoverflow.com/a/45056065/8283581) | 2017/07/10 | [
"https://Stackoverflow.com/questions/45012289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8283581/"
] | AOA! turn the accuracy **Mode of device Gps to (only gps)** instant of other option and then try......
worked for me[settings are like this , i am postie you can also find them on emulators](https://i.stack.imgur.com/gueGa.jpg) | It works for me if introduce Geocoder as singleton for application rather than create it every time. Make sure to call Geocoder.getFromLocationName() from worker thread.
For example:
```
class Application {
private val geoCoder = Geocoder(context, Locale.getDefault())
...
}
class SomeClass {
@WorkerThread
fun doSmth(){
application.geoCoder.getFromLocationName("London", 10)
...
}
}
``` |
8,957,559 | I need to create a music sequencer for the iPad but have no experience yet on this platform. I have several questions about this subject, hopefully I can find some answers here.
* OpenFrameworks seems to be the way to go for this kind of things. I want my application to be able to play both synth sounds and samples. Are both of those things possible with oF? Any suggestions/alternatives?
* Does iOS have some sort of alternative to the android NDK? I don't have any experience with Objective C but I do know some C++ and I would like to do as much as possible in that language. Is it possible to do the 'heavy' work in C++ and only do the views etc. in Objective C?
* Are there any free sample packs that I could use for my sounds? I'm only looking for basic instruments like guitar, bass, drums and maybe a piano.
Any other suggestions or tips you might have are welcome! | 2012/01/21 | [
"https://Stackoverflow.com/questions/8957559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | >
> OpenFrameworks seems to be the way to go for this kind of things. I want my application to be able to play both synth sounds and samples. Are both of those things possible with oF? Any suggestions/alternatives?
>
>
>
As of iOS 5, you can use MusicSequence and MusicPlayer APIs for MIDI. Then you can use AUSampler for sample playback.
>
> Does iOS have some sort of alternative to the android NDK? I don't have any experience with Objective C but I do know some C++ and I would like to do as much as possible in that language. Is it possible to do the 'heavy' work in C++ and only do the views etc. in Objective C?
>
>
>
For realtime audio, ObjC is not an option. C++ and C are the common langs in this domain.
>
> Are there any free sample packs that I could use for my sounds? I'm only looking for basic instruments like guitar, bass, drums and maybe a piano.
>
>
>
Yes. First, you should choose your sample/map format. Then see what the musicians recommend for free samples - [www.kvraudio.com](http://www.kvraudio.com) would be a good place to ask. | I can't help with frameworks, but you can freely mix objective-C and c/c++. |
60,775,983 | I have
```
df<-data.frame(time=c("one", "two", "three", "four", "five"), A=c(1,2,3,4,5), B=c(5,1,2,3,4), C=c(4,5,1,2,3), D=c(3,4,5,1,2), E=c(2,3,4,5,1), EF=c(1,2,3,4,5))
```
I would like to select for example df[df$time=="one,] and order the columns in descending order (if possible in `base R` and `dplyr`), and output a data frame. For example for `df[df$time=="one,]` it would be
```
output.one<-data.frame(time=c("one"), B=c(5), C=c(4), D=c(3), E=c(2), A=c(1))
output.one
time B C D E A
1 one 5 4 3 2 1
```
and for `df[df$time=="five,]`
```
> output.five<-data.frame(time=c("five"), A=c(5), B=c(4), C=c(3), D=c(2), E=c(1))
> output.five
time A B C D E
1 five 5 4 3 2 1
``` | 2020/03/20 | [
"https://Stackoverflow.com/questions/60775983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/906592/"
] | I re-installed python.
This fixed the problem. The code in the example worked perfectly.
The "w" replaces contents of the file.
<https://docs.python.org/3/library/functions.html#open> | Use this:
```
f = open("test.txt", "w")
f.write("this is a test")
f.close()
f2 = open("test.txt", "w")
f2.write("this is also a test")
f2.close()
```
I think the issue is you're trying to work with another instance of the same file without closing it, that being said writing this should also work:
```
f2.close()
``` |
35,354,923 | I'm trying to create a MySQL `UPDATE` statement with an `IF` condition.
I would like to update the user's particulars if the email and username are not duplicate or found in database.
I'm stuck with this code:
```
<?php
include "connection.php";
$user = $_REQUEST['user'];
$em = $_REQUEST['email'];
$id = $_REQUEST['id_user'];
//Check Email in Database
$query = mysqli_query($con,"SELECT username, email from `user` where id_user = '$id'");
$result = mysqli_fetch_object($query);
if (strtolower(trim($query->email)) == strtolower(trim($em))
|| strtolower(trim($user->username)) == strtolower(trim($user))
) {
//next to condition username
} else {
$data_email = mysqli_query($con,"select email from user where em='".$em."'");
$total_email = mysqli_num_rows($data_email);
if($total_email > 0) {
echo "Email Not Available";
} else {
//next to condition username
}
}
//Check Username in Database
$data_us_user = mysqli_query($con,"select username from user where id_user='".$id."'");
$us_user = mysqli_fetch_object($data_us_user);
if (strtolower(trim($us_user->username))==strtolower(trim($user))) {
//next to query update
} else {
$data_username = mysqli_query($con,"select username from user where username='".$em."'");
$total_username = mysqli_num_rows($data_username);
if($total_username > 0) {
echo "Username Not Available";
} else {
//next to query update
}
} else {
//Finally Query Update
mysqli_query($con,"update user set username='".$user."',em='".$em."' where id_user='".$id."' ");
echo "OK";
}
``` | 2016/02/12 | [
"https://Stackoverflow.com/questions/35354923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4570451/"
] | The following PHP script will check for
* IF the user's updated email and updated username are the same
* IF the user's new email and username is already in use by another user
* IF both conditions are not met, the user's details will be updated
**PHP code:**
```
<?php
include "connection.php";
$user = $_REQUEST['user'];
$em = $_REQUEST['email'];
$id = $_REQUEST['id_user'];
//Getting user' details in database
$query = mysqli_query($con, "SELECT username, email from `user` where id_user = '$id'");
$result = mysqli_query($query);
//Query to find if email exists
$query2 = mysqli_query($con,"SELECT `email` from `user` WHERE em = '$em'");
$result2 = mysqli_num_rows($query2);
//Query to find if username exists
$query3 = mysqli_query($con,"SELECT `email` from `user` WHERE id_user = '$user");
$result3 = mysqli_num_rows($query3);
while ($row = mysqli_fetch_row($result)){
list($userfromdb, $emfromdb) = $row;
}
if (strtolower(trim($userfromdb)) == strtolower(trim($user))){
//will return true if user's username is the same before updating
echo 'Username cannot be the same!';
} else if(strtolower(trim($emfromdb)) == strtolower(trim($em))) {
//will return true if user's email is the same before updating
echo 'Email cannot be the same!';
} else if($result2 > 0) {
echo "Email Not Available";
} else if($result3 > 0) {
echo "Username Not Available";
} else {
//Finally Query Update
mysqli_query($con, "UPDATE `user` set username = '$user',em = '$em' WHERE id_user = '$id'");
//check if row updated successfully
$result4 = mysqli_affected_rows($con);
if ($result4 > 0) {
echo "Updated details successfully";
} else {
echo "An error occurred while updated details.";
}
}
?>
```
This should work, thanks! | >
> If specifying column related message is not the concern,
>
>
>
```
<?php
include "connection.php";
$user = $_REQUEST['user'];
$em = $_REQUEST['email'];
$id = $_REQUEST['id_user'];
$data_us_em = mysqli_query($con,"select count(email) as count from user where id_user='".$id."' OR em='".$em."' OR username='".$em."'");
if($data_us_em)
{
$us_em = mysqli_fetch_assoc($data_us_em);
$count=$us_em['count'];
if($count)
{
echo 'Can not update';
}else
{
mysqli_query($con,"update user set username='".$user."',em='".$em."' where id_user='".$id."' ");
echo "OK";
}
}
?>
``` |
59,326,351 | I am using the ReactiveElasticsearchClient from spring-data-elasticsearch 3.2.3 with spring-boot 2.2.0. When upgrading to spring-boot 2.2.2 i have got org.springframework.core.io.buffer.DataBufferLimitException: Exceeded limit on max bytes to buffer : 262144.
It's indicated to fixe that to use spring.codec.max-in-memory-size but i still got the same exception.
Bellow the whole exception:
```
org.springframework.core.io.buffer.DataBufferLimitException: Exceeded limit on max bytes to buffer : 262144
at org.springframework.core.io.buffer.LimitedDataBufferList.raiseLimitException(LimitedDataBufferList.java:101)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Assembly trace from producer [reactor.core.publisher.MonoCollect] :
reactor.core.publisher.Flux.collect(Flux.java:3273)
org.springframework.core.io.buffer.DataBufferUtils.join(DataBufferUtils.java:553)
Error has been observed at the following site(s):
|_ Flux.collect ⇢ at org.springframework.core.io.buffer.DataBufferUtils.join(DataBufferUtils.java:553)
|_ Mono.filter ⇢ at org.springframework.core.io.buffer.DataBufferUtils.join(DataBufferUtils.java:554)
|_ Mono.map ⇢ at org.springframework.core.io.buffer.DataBufferUtils.join(DataBufferUtils.java:555)
|_ Mono.map ⇢ at org.springframework.core.codec.AbstractDataBufferDecoder.decodeToMono(AbstractDataBufferDecoder.java:96)
|_ checkpoint ⇢ Body from POST http://localhost:9200/_bulk?timeout=1m [DefaultClientResponse]
|_ Mono.map ⇢ at org.springframework.data.elasticsearch.client.reactive.DefaultReactiveElasticsearchClient.readResponseBody(DefaultReactiveElasticsearchClient.java:669)
|_ Mono.doOnNext ⇢ at org.springframework.data.elasticsearch.client.reactive.DefaultReactiveElasticsearchClient.readResponseBody(DefaultReactiveElasticsearchClient.java:670)
|_ Mono.flatMap ⇢ at org.springframework.data.elasticsearch.client.reactive.DefaultReactiveElasticsearchClient.readResponseBody(DefaultReactiveElasticsearchClient.java:671)
|_ Mono.flatMapMany ⇢ at org.springframework.data.elasticsearch.client.reactive.DefaultReactiveElasticsearchClient.sendRequest(DefaultReactiveElasticsearchClient.java:591)
|_ Flux.publishNext ⇢ at org.springframework.data.elasticsearch.client.reactive.DefaultReactiveElasticsearchClient.bulk(DefaultReactiveElasticsearchClient.java:448)
|_ Flux.flatMap ⇢ at com.energisme.ds.reactive.aggregation.service.SensorAggregationService.save(SensorAggregationService.java:32)
|_ Flux.map ⇢ at com.energisme.ds.reactive.aggregation.service.SensorAggregationService.save(SensorAggregationService.java:33)
|_ Flux.reduce ⇢ at com.energisme.ds.reactive.aggregation.service.SensorAggregationService.save(SensorAggregationService.java:34)
|_ Mono.zip ⇢ at com.energisme.ds.reactive.aggregation.service.AggregateSensorFlowService.nonIndexDifferenceAggregateSensorData(AggregateSensorFlowService.java:178)
|_ Mono.map ⇢ at com.energisme.ds.reactive.aggregation.service.AggregateSensorFlowService.nonIndexDifferenceAggregateSensorData(AggregateSensorFlowService.java:179)
Stack trace:
at org.springframework.core.io.buffer.LimitedDataBufferList.raiseLimitException(LimitedDataBufferList.java:101)
at org.springframework.core.io.buffer.LimitedDataBufferList.updateCount(LimitedDataBufferList.java:94)
at org.springframework.core.io.buffer.LimitedDataBufferList.add(LimitedDataBufferList.java:59)
at reactor.core.publisher.MonoCollect$CollectSubscriber.onNext(MonoCollect.java:119)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:121)
at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onNext(FluxPeekFuseable.java:203)
at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onNext(FluxPeekFuseable.java:203)
at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:114)
at reactor.netty.channel.FluxReceive.drainReceiver(FluxReceive.java:218)
at reactor.netty.channel.FluxReceive.onInboundNext(FluxReceive.java:351)
at reactor.netty.channel.ChannelOperations.onInboundNext(ChannelOperations.java:348)
at reactor.netty.http.client.HttpClientOperations.onInboundNext(HttpClientOperations.java:571)
at reactor.netty.channel.ChannelOperationsHandler.channelRead(ChannelOperationsHandler.java:89)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352)
at io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:287)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352)
at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:438)
at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:326)
at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:313)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:427)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:281)
at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:253)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1422)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:931)
at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:792)
at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:502)
at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:407)
at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1050)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:834)
```
Can anyone tell me what i am doing wrong or is that a bug?
Thank you | 2019/12/13 | [
"https://Stackoverflow.com/questions/59326351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11867433/"
] | Using the plain reaction `WebClient` I ran into the same issue (going from 2.1.9 to 2.2.1.) I had no luck setting `spring.codec.max-in-memory-size` and later found a hint that this wasn't the way to go anyway:
>
> … On the client side, the limit can be changed in WebClient.Builder.
>
>
> ([source](https://github.com/spring-projects/spring-framework/blob/master/src/docs/asciidoc/web/webflux.adoc#limits), including dead link :-S )
>
>
>
I still haven't found out where `WebClient.Builder` gets the [default 256K limit](https://github.com/spring-projects/spring-framework/blob/master/src/docs/asciidoc/web/webflux-webclient.adoc#maxinmemorysize)1. However, the following enabled me to raise the buffer size limit to 16M:
```
WebClient.builder()
.…
.exchangeStrategies(ExchangeStrategies.builder()
.codecs(configurer -> configurer
.defaultCodecs()
.maxInMemorySize(16 * 1024 * 1024))
.build())
.build();
```
So, it seems to me (without knowing the intricacies of `spring-data-elasticsearch`) that *if* you can somehow get your hands on the `WebClient` as returned from the [`WebClientProvider`](https://github.com/spring-projects/spring-data-elasticsearch/blob/master/src/main/java/org/springframework/data/elasticsearch/client/reactive/WebClientProvider.java#L84) you should be able to mutate it to include the `ExchangeStrategies` from above.
Perhaps you can provide your own override of `DefaultWebClientProvider` along the lines of (absolutely untested!):
```
class MyDefaultWebClientProvider extends DefaultWebClientProvider {
@Override
public WebClient get(InetSocketAddress endpoint) {
return super.get(endpoint)
.mutate() // Obtain WebClient.Builder instance.
.exchangeStrategies(ExchangeStrategies.builder()
.codecs(configurer -> configurer
.defaultCodecs()
.maxInMemorySize(16 * 1024 * 1024))
.build())
.build();
}
}
```
YMMV.
---
**UPDATE #1:**
1) Now I found it. *And* it explains why setting `spring.codec.max-in-memory-size` has no effect; the property is [hardcoded at 256K](https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/core/codec/AbstractDataBufferDecoder.java#L51) in the base class uses by all default codecs, cf. `BaseDefaultCodecs`. | or:
```
final Consumer<ClientCodecConfigurer> consumer = configurer -> {
final ClientCodecConfigurer.ClientDefaultCodecs codecs = configurer.defaultCodecs();
codecs.maxInMemorySize(maxBufferMb * 1024 * 1024);
};
WebClient.builder().codecs(consumer).build();
``` |
6,922,866 | I have the following text as an example:
`\n\t\t\t\t\t3 comments`
Can anyone help me to construct PHP regex formula for extracting the number? (in this case `number = 3`)
The number can be prefixed by any text, but after the number there should be a `<space>` followed by `comments`.
Thanks. | 2011/08/03 | [
"https://Stackoverflow.com/questions/6922866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861112/"
] | ```
preg_match('/\d+(?= comments)/', $text, $match);
``` | ```
$str = "\n\t\t\t\t\t3 comments";
preg_match('/\.*(\d+)\scomments/',$str,$m);
var_dump($m[1]);
``` |
13,789,436 | I am using Raspbian, a Debian distro for the Raspberry Pi. I tried using the task manager but was unable to change the process priority (I was trying to decrease Python's priority). After decreasing the priority and checking again it remained at zero (no change). Is this because of me not being a superuser? If so how do I open the task manager GUI in sudo? If not what else could be the problem? | 2012/12/09 | [
"https://Stackoverflow.com/questions/13789436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1850751/"
] | You should consider to use Terminal:
```
sudo top
```
this will show you the processes with pid
```
renice {priority} pid
```
this will change the priority (niceness) of the process. The nicer the process is, the lower priority it will have. It's nicer because leave its time-slot to other processes ;-)
{priority} is from -20 to 19 | Find the process id (using ps aux|grep 'your\_process')
Use `renice` command
```
$sudo renice -n <nice_value> -p <PID>
``` |
5,245,430 | Can anybody try to take a look at the code please, i am new in jQuery. Thank you, guys.
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Registration</title>
<script type="text/javascript" src="lib/jquery/jquery-1.4.2.js"></script>
<script type="text/javascript" src="/dateplugin.js"></script>
<link rel="stylesheet" type="text/css" href="/stylez.css" />
<script type="text/jscript">
$(document).ready(function(){
//$.dateSelectBoxes('mon','da','yea');
//form validation
var hasError = false;
var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;
var email = $("#em").val();
var fname=$("#fn").val();
var lname=$("#ln").val();
var school=$("#sch").val();
var classes=$("#clas").val();
var grade=$("#yr").val();
var month=$("#mon").val();
var days=$("#da").val();
var years=$("#yea").val();
var pass=$("#pas").val();
var zipcode=$("#zip").val();
$("#submitbutton").click(function(e){
if (fname==''){
$("#fn").after("Please enter your first name ");
hasError=true;
}
if (lname==''){
$("#ln").after("Please enter your last name");
hasError=true;
}
if(school==''){
$("#sch").after("Please enter the name of your institution");
hasError=true;
}
if (classes==''){
$("#clas").after("Please enter current classes you are taking");
hasError=true;
}
if (month=='' || day=='' || year==''){
$("#mon").after("Please enter your birthday");
hasError=true;
}
if (pass==''){
$("#pas").after("Please enter the password");
hasError=true;
}
if (zipcode==''){
$("#zip").after("Please enter your zipcode");
hasError=true;
}
if (grade==''){
$("#yr").after("Please enter the year you are in");
hasError=true;
}
if(email == '') {
$("#em").after("You forgot to enter the email address to send ");
hasError = true;
} else if(!emailReg.test(email)) {
$("#em").after("Enter a valid email address to send to.");
hasError = true;
}
if (hasError == true) {
e.preventDefault();
}
else {
//submit form via ajax
}
});
});
</script>
<style type="text/css">
</style>
</head>
<body class="fancy">
<form action="" method="" accept-charset="utf-8">
<table width="800" border="0" cellpadding="1" cellspacing="0">
<tr>
<td id="column1">
</td>
<td id="column2">
<div class="Sintext">
<h1>
Sign Up</h1>
</div>
<div>
<label>
First Name</label>
<input type="text" name="fnam" class="fields" id="fn" />
</div>
<div>
<label>
Last Name</label>
<input type="text" name="lnam" class="fields" id="ln" />
</div>
<div>
<label>
School</label>
<input type="text" name="scname" class="fields" id="sch" />
</div>
<div>
<label>
Major</label>
<select id="majo" name="major">
<option value="5">—undeclared—</option>
</select>
</div>
<div>
<label>
Current Classes</label>
<input type="text" name="class" id="clas" class="fields" />
<span>
add class field</span>
</div>
<div>
<label>
Year</label>
<select id="yr" name="year">
<option value="">—Select the year —</option>
<option value="10">Freshman </option>
<option value="20">Sophomore</option>
<option value="30">junior</option>
<option value="40">senior</option>
<option value="50">Alumni </option>
<option value="60">HighSchool </option>
</select>
</div>
<div>
<label>
Campus</label>
<input type="text" name="campus" class="fields" />
</div>
<div>
<label>
Email</label>
<input type="text" name="email" id="em" class="fields" />
</div>
<div>
<label>
Password</label>
<input type="text" name="passwd" id="pas" class="fields" />
</div>
<div>
<label>
Sex</label>
<select name="sex" class="sexfield">
<option value="3">Male</option>
<option value="4">Female </option>
</select>
</div>
<div id="bdate">
<label>
Birthday</label>
<select id="mon" name="mont">
<option value="0">Month</option>
</select>
<select id="da" name="day">
<option value="1">Day</option>
</select>
<select id="yea" name="year">
<option value="2">Year</option>
</select>
</div>
<div>
<label>
Zipcode</label>
<input type="text" name="zipcod" id="zip" class="zipfield" />
</div>
<div>
<button id="submitbutton" class="sinbutton">
Sign Up</button>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
``` | 2011/03/09 | [
"https://Stackoverflow.com/questions/5245430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612222/"
] | I think you have two errors, neither of them related to calling after().
1. Your regular expression has a syntax error. Instead of `[w-.]`, say `[w.-]`.
2. You've mixed up the variable names for the birthday: month,days,years in one place, month,day,year in the other.
If I fix these then clicking the submit button does for me what I think you intended it to do. | I would just use one div which display all the errors. Also, the documentation says HTML String. Have you tried some paragraph tags? I know it should not matter but worth a shot. Can you elaborate on the results you are getting? |
30,526,707 | When I tried jbosseap6.3 install as service. I got below error. Anyone have any idea on the below error. Any one shed light means it is very helpful for me.
```
java.lang.IllegalArgumentException: Failed to instantiate class "org.jboss.logmanager.handlers.PeriodicRotatingFileHandler" for handler "FILE"
at org.jboss.logmanager.config.AbstractPropertyConfiguration$ConstructAction.validate(AbstractPropertyConfiguration.java:119)
at org.jboss.logmanager.config.LogContextConfigurationImpl.doPrepare(LogContextConfigurationImpl.java:338)
at org.jboss.logmanager.config.LogContextConfigurationImpl.prepare(LogContextConfigurationImpl.java:291)
at org.jboss.logmanager.config.LogContextConfigurationImpl.commit(LogContextConfigurationImpl.java:300)
at org.jboss.logmanager.PropertyConfigurator.configure(PropertyConfigurator.java:542)
at org.jboss.logmanager.PropertyConfigurator.configure(PropertyConfigurator.java:97)
at org.jboss.as.logging.logmanager.ConfigurationPersistence.configure(ConfigurationPersistence.java:149)
at org.jboss.logmanager.LogManager.readConfiguration(LogManager.java:300)
at org.jboss.logmanager.LogManager.readConfiguration(LogManager.java:262)
at java.util.logging.LogManager$3.run(LogManager.java:399)
at java.util.logging.LogManager$3.run(LogManager.java:396)
at java.security.AccessController.doPrivileged(Native Method)
at java.util.logging.LogManager.readPrimordialConfiguration(LogManager.java:396)
at java.util.logging.LogManager.access$800(LogManager.java:145)
at java.util.logging.LogManager$2.run(LogManager.java:345)
at java.security.AccessController.doPrivileged(Native Method)
at java.util.logging.LogManager.ensureLogManagerInitialized(LogManager.java:338)
at java.util.logging.LogManager.getLogManager(LogManager.java:378)
at org.jboss.modules.Main.main(Main.java:443)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at org.jboss.logmanager.config.AbstractPropertyConfiguration$ConstructAction.validate(AbstractPropertyConfiguration.java:117)
... 18 more
Caused by: java.io.FileNotFoundException: C:\jboss-eap-6.3\standalone\log\server.log (The process cannot access the file because it is being used by another process)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at org.jboss.logmanager.handlers.FileHandler.setFile(FileHandler.java:154)
at org.jboss.logmanager.handlers.PeriodicRotatingFileHandler.setFile(PeriodicRotatingFileHandler.java:105)
at org.jboss.logmanager.handlers.FileHandler.setFileName(FileHandler.java:192)
at org.jboss.logmanager.handlers.FileHandler.<init>(FileHandler.java:122)
at org.jboss.logmanager.handlers.PeriodicRotatingFileHandler.<init>(PeriodicRotatingFileHandler.java:73)
... 23 more
Shutdown JBossEAP6.3.0 service [2015-05-29 09:58:27]
``` | 2015/05/29 | [
"https://Stackoverflow.com/questions/30526707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4863157/"
] | Right click the installation directory of Jboss EA (mine is C:\program files\EAP6.1, then Properties, Security tab. Given everyone permissions on this folder (all users you can see just give full control). This should then be able to create logs etc files within the required folder.
This is just a workaround though only works for local installs. | I got the same exception
Try changing the path from c to another destination, that solved my issue and I am able to start the server |
64,127,408 | I am trying to use ngForm by following an online tutorial for building the full-stack application but save button isn't triggered, I am totally new to angular 8 I had followed each step kidly help me to get rid of this thanks in advance
**My form code adduer.component.html**
```
<h1>Add User</h1>
<form #recievedUser="ngForm">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="user name" [(ngModel)]="user.name" name="name">
<label for="type">Type</label>
<input type="text" class="form-control" id="type" placeholder="type name" [(ngModel)]="user.type" name="name">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="password" [(ngModel)]="user.password" name="password">
<br>
<button type="button" class="btn btn-success" (click)="addUser()">Save</button>
</form>
```
**My adduser.Component.ts file**
```
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { User } from '../../../model/User';
import { HttpClientService } from '../../../service/http-client.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-adduser',
templateUrl: './adduser.component.html',
styleUrls: ['./adduser.component.css']
})
export class AdduserComponent implements OnInit {
@Input()
user: User
@Output()
userAddedEvent = new EventEmitter();
newUser: User;
message: string;
password: string;
constructor(private httpClientService: HttpClientService,
private router: Router) { }
ngOnInit() {
this.newUser = Object.assign({}, this.user);
}
addUser() {
this.httpClientService.addUser(this.newUser).subscribe(
(user) => {
this.userAddedEvent.emit();
this.router.navigate(['admin', 'users']);
}
);
}
}
```
**app.module.ts**
```
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MenuComponent } from './menu/menu.component';
import { UsersComponent } from './admin/users/users.component';
import {HttpClientModule} from '@angular/common/http';
import { AdduserComponent } from './admin/users/adduser/adduser.component';
import {FormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
MenuComponent,
UsersComponent,
AdduserComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
I am following [this link](https://www.javainuse.com/fullstack/ecommerce/user2) to build an application | 2020/09/29 | [
"https://Stackoverflow.com/questions/64127408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4384793/"
] | Go to Laravel folder
```
/public
```
open
```
index.php
```
Look for the comment block
```
|---------------------
| Run The Application
|---------------------
```
**Under** that block just place
```
phpinfo();
```
Then start Laravel application with
```
php artisan serve
```
And open the application in browser.
Don't forget to remove the line.
**Please note:**
This is only for local debugging purposes, as you reveal confidential information about PHP config. | If you want a separate Info file for debugging purpose only
Go to project root folder
`cd public`
`nano phpinfo.php`
```php
<?php
// Show all information, defaults to INFO_ALL
phpinfo();
?>
```
**Run Laravel :**
`php artisan serve`
**VIEW YOUR PHPINFO PAGE**
To view your php info page, open a browser and go to the URL
http://localhost/phpinfo.php
***Please note:***
This is only for local debugging purposes, You expose everything in this file , Remove this before putting code in production |
29,617,206 | Using Ruby 2.1.3 and Rails 4.1.6.
I have been using .titleize to clean up some user input such as
```
'new york'.titleize
=> "New York"
```
However, titleize can also break correct user input by downcasing when not desired:
```
'New York, NY'.titleize
=> "New York, Ny"
```
Is there a clean way to titleize without any downcasing? | 2015/04/14 | [
"https://Stackoverflow.com/questions/29617206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2917386/"
] | If you expect mix case words and want to keep them mix cased I would something like this:
```
def titleize_without_downcasing(string)
string.gsub(/(\w|')(\w*)/) { $1.upcase + $2 }
end
titleize_without_downcasing('new york, NY, UsA')
#=> 'New York, NY, UsA'
titleize_without_downcasing("doctor's")
#=> "Doctor's"
``` | ```
def titlize(str)
r = str.split.map { |word| word.size > 2 ? word.titleize : word.capitalize }
r.join(" ")
end
``` |
1,054,076 | How can I generate a random hexadecimal number with a length of my choice using C#? | 2009/06/28 | [
"https://Stackoverflow.com/questions/1054076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124550/"
] | Depends on how random you want it, but here are 3 alternatives:
1. I usually just use Guid.NewGuid and pick a portion of it (dep. on how large number I want).
2. System.Random (see other replies) is good if you just want 'random enough'.
3. System.Security.Cryptography.RNGCryptoServiceProvider | .... with LINQ
```
private static readonly Random _RND = new Random();
public static string GenerateHexString(int digits) {
return string.Concat(Enumerable.Range(0, digits).Select(_ => _RND.Next(16).ToString("X")));
}
``` |
5,404,257 | how to check entered value in text box have B as first letter using c# | 2011/03/23 | [
"https://Stackoverflow.com/questions/5404257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672875/"
] | ```
if(myTextBox.Text.StartsWith("B")) ....
``` | You can use the string `StartsWith()` method.
```
if("Bar".StartsWith("B")) // ....
if(Textbox.Text.StartsWith("B")) // ....
``` |
12,836,966 | I have to modify the PHPTAL template below by adding another field, "location"
```
<tal:block tal:repeat="contact Model/contactList">
<div class="contactCell">
Name: <span content="contact/name">contact name</span><br/>
Number: <span content="contacy/number">2374687234</span><br/>
<-- THIS NEEDS ADDING-->
Location: <span content="contact/location">contact's location</span>
</div>
</tal:block>
```
My problem is that I don't know what methods and properties are available in the model and I don't want to read the PHP code to trace this either. I would like to be able to dump out all the properties of the model from within the template so it's easy to see if the property I need is already available or whether I have to ask the backend dev to make it available. Something like this would be good.
```
<div class="debug panel">
<tal:dumpObject Model/contactList>
</div>
```
which would then produce something like this in my HTML output:
```
<div class="debug panel">
contact Array
[
{
[name] => John Smith
[number] => 374862378
[address] => 22 Acacia Avenue
[location] => London
},{
[name] => Billy Bragg
[number] => 384567365
[address] => 10 Downing Street
[location] => London
},
...
]
</div>
```
This way I would be able to immediately see what I can use and what I need to request from other devs. | 2012/10/11 | [
"https://Stackoverflow.com/questions/12836966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/297440/"
] | You can get pretty far with:
```
<pre tal:content="php:print_r(object, true)"/>
```
if the object is a plain array or a `stdClass` object.
However, PHPTAL can also read object's methods and invokes magic `__get()` methods, so if the object is from some fancy ORM it may not be possible to list all properties that would work. | You can use var\_dump inside PHPTAL as well:
```
<pre tal:content="php:var_dump(object)"/>
``` |
51,494,829 | I have been trying to figure out an issue with spring boot and as i am new to spring I thought of getting some help here.
I have a spring boot based java application which runs as a daemon and makes some GET request to a remote server. (Acts only as a client).
But my spring boot application internally starts an embedded tomcat container.
My understanding is that if the java app acts as a server, it would need tomcat. But my application being only a consumer of remote machine's GET APIs, why would it need an embedded tomcat ?
In my pom file I have specified spring-boot-starter-web,
on assumption that it is needed for even making GET calls.
But after doing some research on disabling embedded tomcat, I found a solution.
To make following changes,
```
@SpringBootApplication(exclude = {EmbeddedServletContainerAutoConfiguration.class,
WebMvcAutoConfiguration.class})
```
&
in application.yml
```
spring:
main:
web-environment: false
```
With the application.yml changes, my jar is not even getting started, aborts directly, without even logging anything in logback logs.
Now, if i remove the application.yml change, my jar starts (only with first change in @SpringBootApplication anno.) but goes into some exception.
```
[main] o.s.boot.SpringApplication : Application startup failed
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
```
My Doubts here are,
1) Is tomcat, be it standalone or embedded, really needed for a application which just makes GET API calls to remote machine ?
2) How do i overcome this exception and safely remove the embedded tomcat and still perform the GET API calls ? | 2018/07/24 | [
"https://Stackoverflow.com/questions/51494829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2218666/"
] | Here is the most simple solution for me, make spring boot application just a restful api consumer.
Replace the dependence
```
implementation("org.springframework.boot:spring-boot-starter-web")
```
with
```
implementation("org.springframework.boot:spring-boot-starter-json")
```
`RestTemplate` and `jackson` are available in the project without embedded tomcat. | Answering your questions:
1) embedded by defaut - not needed for clients HTTP requests;
2) You can use CommandLineRunner for spring boot applications without any web:
```
@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringBootConsoleApplication.class, args);
}
@Override
public void run(String... args) {
// TODO: start you thread here to execute client HTTP REST requests (or any other job you need)
}
}
```
This will disable web completelly - no issues with manual miss-configuration.
Here is some docs:
<http://www.baeldung.com/spring-boot-console-app>
You also need replase spring-boot-starter-web dependency with spring-boot-starter:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
``` |
24,822,262 | Here is the xml
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="@+id/buttonGnc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Güncelle" />
<ListView
android:id="@+id/listView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="@+id/Doviz" >
</ListView>
**<Button
android:layout_toLefttOf="@+id/Doviz"
android:id="@+id/Altin"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_above="@+id/listView1"
android:layout_alignParentRight="true"
android:layout_weight="1"
android:text="Altın" />
<Button
android:id="@+id/Doviz"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/buttonGnc"
android:layout_weight="1"
android:text="Döviz" />
</RelativeLayout>**
```
Ok the buttons whict i want to fill the parent with are Doviz and Altin others are irrelevant.
I tried making width for both of them fill\_parent hoping they might get half - half didn't work.
I tried giving them width as "0dp" didnt work.
My question is how i can make them(buttons) get the width %50-%50. | 2014/07/18 | [
"https://Stackoverflow.com/questions/24822262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842868/"
] | wrap both buttons around LinearLayout and set their width to fill\_parent as well as same layout weight
```
<LinearLayout layout_width="fill_parent" ... >
<Button layout_width="fill_parent" layout_weight="1" ... />
<Button layout_width="fill_parent" layout_weight="1" ... />
</LinearLayout>
```
Buttons will be assigned 50% of the width of the parent layout | ```
Try this code it will help you in every device
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="@+id/buttonGnc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Güncelle" />
<ListView
android:id="@+id/listView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="@+id/linear" >
</ListView>
<LinearLayout
android:id="@+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/buttonGnc"
android:orientation="horizontal" >
<Button
android:id="@+id/Altin"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_above="@+id/listView1"
android:layout_alignParentRight="true"
android:layout_weight="1"
android:text="Altın" />
<Button
android:id="@+id/Doviz"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/buttonGnc"
android:layout_weight="1"
android:text="Döviz" />
</LinearLayout>
</RelativeLayout>
``` |
50,399,320 | I want to have a layout like:
[](https://i.stack.imgur.com/XTqBG.png)
But is not working, the layout appears like <https://jsfiddle.net/0knckvfh/1/>. Do you know where is the issue?
HTML:
```
<div class="container">
<div class="row">
<h6 class="font-weight-bold">Title</h6>
<p><strong>Name:</strong> John</p>
<p><strong>Email:</strong> emailtest...</p>
<h6 class="font-weight-bold">User 1</h6>
<p><strong>Name:</strong> John</p>
<p><strong>Surname:</strong> Y</p>
<p><strong>Email:</strong>emailtest...</p>
</div>
</div>
``` | 2018/05/17 | [
"https://Stackoverflow.com/questions/50399320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9548602/"
] | Your layout is displaying incorrectly because you have forgotten to wrap your content within one of Bootstrap's `.col-*-*` classes. Without that wrapper everything defaults to `flex-wrap: wrap` as defined by the `row`.
If you're just learning Bootstrap this would be an opportune moment to read the documentation on its Grid system: <https://getbootstrap.com/docs/4.1/layout/grid/>
Once you apply the `col` wrapper correctly your code structures *mostly* how you want it. Applying a few more of Bootstrap's utility classes results in your code looking something like this:
```html
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<div class="container">
<div class="row">
<div class="col">
<h6 class="font-weight-bold">Title</h6>
<p><strong class="mr-1">Name:</strong>John</p>
<p><strong class="mr-1">Email:</strong>emailtest...</p>
<h6 class="font-weight-bold border-top pt-3">User 1</h6>
<p><strong class="mr-1">Name:</strong>John</p>
<p><strong class="mr-1">Surname:</strong>Y</p>
<p><strong class="mr-1">Email:</strong>emailtest...</p>
</div>
</div>
</div>
```
I would like to acknowledge that @zgood correctly noted this issue in the comments to your initial post. Why so many people followed that comment with answers involving the nonexistent 'column' class is beyond me. | ```
<div class="container">
<div class="row">
<div class="column">
<h6 class="font-weight-bold">Title</h6>
<p><strong>Name:</strong> John</p>
<p><strong>Email:</strong> emailtest...</p>
<h6 class="font-weight-bold">User 1</h6>
<p><strong>Name:</strong> John</p>
<p><strong>Surname:</strong> Y</p>
<p><strong>Email:</strong>emailtest...</p>
</div>
</div>
</div>
```
Will give you what you want, minus the black bar separating the two as shown in your example, but as you didnt include this in your code and you are just after formatting im guessing you know this. |
143,043 | This might be an easy question but currently I'm fighting over it with our TA who gave it in the final exam.
Let $X, Y$ random variables and define $Z= \max \{X, Y\}$ what is the distribution of
$Z \mid \{X > Y\}$?
Should be $Z\mid \{X>Y\}\sim X$, right?!
Thank you all. | 2012/05/09 | [
"https://math.stackexchange.com/questions/143043",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/30968/"
] | Let rephrase the question this way: What is the conditional distribution of $X$, given that $X>Y$?
Suppose $\displaystyle X\sim\left.\begin{cases} 1 & \text{with probability }p, \\ 0 & \text{with probability }1-p \end{cases}\right\}$, and $Y$ is an independent copy of $X$.
What is the conditional probability distribution of $X$, given that $X>Y$? It is $$\Pr(X=1\mid X>Y)=1.$$
What is the conditional probability distribution of $X$, given that $X\ge Y$? It is $$\Pr(X=1\mid X \ge Y) = \frac{p}{1-p+p^2}.$$
**POSTSCRIPT:** I dislike phrasing this as
$$\text{the distribution of }Z\mid\{X>Y\},$$
because students misconstrue it as
$$\text{the distribution of }\Big( Z\mid\{X>Y\}\Big),$$
as if there were a thing called $Z\mid\{X>Y\}$ whose distribution is sought. It's actually
$$\Big( \text{the distribution of }Z \Big) \mid\{X>Y\}.$$ | The conditional PDF of $Z$ conditionally on $[X\gt Y]$ is the only function $g$ such that, for every bounded measurable function $u$,
$$
\int u(z)g(z)\mathrm dz=\mathrm E(u(Z)\mid X\gt Y)\propto\mathrm E(u(X); X\gt Y),
$$
where $\propto$ means that a factor independent of $u$ was omitted.
**Let us assume that $X$ and $Y$ are independent**. Write $f\_X$ for the PDF of $X$ (when this exists) and $G\_Y$ for the function defined by $G\_Y(y)=\mathrm P(Y\lt y)$ for every $y$ (thus, $G\_Y$ is a modified CDF of $Y$ where the inequality sign is strict). Then,
$$
\mathrm E(u(X); X\gt Y)=\iint u(x)\,[x\gt y]f\_X(x)\mathrm d\mathrm P\_Y(y)=\int u(x)G\_Y(x)f\_X(x)\mathrm dx.
$$
By identification, $g(z)\propto f\_X(z)G\_Y(z)$, hence
$$
\color{red}{g(z)=c^{-1}f\_X(z)G\_Y(z)},\qquad c=\int f\_X(x)F\_Y(x)\mathrm dx=\mathrm E(G\_Y(X))=\mathrm P(X\gt Y).
$$
In particular, $g=f\_X$ means that $G\_Y$ is constant on $S\_X=\{x\mid f\_X(x)\ne0\}$. Two examples: (i) If $S\_X$ is the whole real line, this is impossible. (ii) If $S\_X=(0,+\infty)$, this means that $Y\leqslant0$ with full probability.
In general, assuming the distribution of $X$ is $\mu$, one sees that the distribution of $Z$ conditionally on $[X\gt Y]$ is $\nu$ with
$$
\color{blue}{\mathrm d\nu(z)=c^{-1}G\_Y(z)\mathrm d\mu(z)},\qquad c=\int G\_Y(x)\mathrm d\mu(x)=\mathrm E(G\_Y(X))=\mathrm P(X\gt Y).
$$ |
1,936,462 | I have used [`LinkedHashMap`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html) because it is important the order in which keys entered in the map.
But now I want to get the value of key in the first place (the first entered entry) or the last.
Should there be a method like `first()` and `last()` or something like that?
Do I need to have an iterator to just get the first key entry? That is why I used [`LinkedHashMap`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html)!
Thanks! | 2009/12/20 | [
"https://Stackoverflow.com/questions/1936462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/178132/"
] | `LinkedHashMap` current implementation (Java 8) keeps track of its tail. If performance is a concern and/or the map is large in size, you could access that field via reflection.
Because the implementation may change it is probably a good idea to have a fallback strategy too. You may want to log something if an exception is thrown so you know that the implementation has changed.
It could look like:
```
public static <K, V> Entry<K, V> getFirst(Map<K, V> map) {
if (map.isEmpty()) return null;
return map.entrySet().iterator().next();
}
public static <K, V> Entry<K, V> getLast(Map<K, V> map) {
try {
if (map instanceof LinkedHashMap) return getLastViaReflection(map);
} catch (Exception ignore) { }
return getLastByIterating(map);
}
private static <K, V> Entry<K, V> getLastByIterating(Map<K, V> map) {
Entry<K, V> last = null;
for (Entry<K, V> e : map.entrySet()) last = e;
return last;
}
private static <K, V> Entry<K, V> getLastViaReflection(Map<K, V> map) throws NoSuchFieldException, IllegalAccessException {
Field tail = map.getClass().getDeclaredField("tail");
tail.setAccessible(true);
return (Entry<K, V>) tail.get(map);
}
``` | Though linkedHashMap doesn't provide any method to get first, last or any specific object.
But its pretty trivial to get :
```
Map<Integer,String> orderMap = new LinkedHashMap<Integer,String>();
Set<Integer> al = orderMap.keySet();
```
now using iterator on `al` object ; you can get any object. |
68,444,222 | I have the following jinja2 template
```
[
{% for items in hosts %}
{
"name":"{{ items.name }}",
"display_name":"{{ items.display_name }}",
"services": {{ host_group | from_json | json_query('[*].services[0]') | to_json }},
}
{% endfor %}
]
```
i need to replace **services[0]** by a variable **{{ loop.index0 }}**, i tried this syntax
```
"services": {{ host_group | from_json | json_query('[*].services[loop.index0]') | to_json }}
```
but i'm getting an error :
```
AnsibleFilterError: JMESPathError in json_query filter plugin:
Expecting: star, got: unquoted_identifier: Parse error at column 13, token "loop" (UNQUOTED_IDENTIFIER), for expression:
"[*].services[loop.index0]"
```
I tried another syntax:
```
"services": {{ host_group | from_json | json_query('[*].services[' + {{ loop.index0 }} +']') | to_json }},
```
and it gives also an error :
```
AnsibleError: template error while templating string: expected token ':', got '}'. String: [
``` | 2021/07/19 | [
"https://Stackoverflow.com/questions/68444222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4686080/"
] | There are two things to keep in mind when working with Jinja:
1. You never nest the `{{...}}` template markers.
2. If you put something in quotes, it's a literal string.
So when you write:
```
json_query('[*].services[loop.index0]')
```
You are passing `json_query` the *literal string* `[*].services[loop.index0]`, which isn't a valid JMESPath query. If you want to substitute the value of a variable in a string, you need to either build the string via concatenation, or use string formatting logic.
Concatenation
-------------
Using concatenation might look like:
```
json_query('[*].services[' ~ loop.index0 ` ']')
```
Here, `~` is the string concatenation operator -- it's like `+`, but it makes sure to convert everything into a string. Compare this:
```
ansible localhost -m debug -a 'msg={{ "there are " + 4 + " lights" }}'
```
To this:
```
ansible localhost -m debug -a 'msg={{ "there are " ~ 4 ~ " lights" }}'
```
String formatting
-----------------
Using string formatting might look like:
```
json_query('[*].services[%s]' % (loop.index0))
```
Or:
```
json_query('[*].services[{}]'.format(loop.index0))
```
These are two forms of string formatting available in Python; for more details, start [here](https://pyformat.info/). | Using Ansible `2.9.23`.
For the string placeholders `{}` and `%s` I had to use backticks, otherwise it wouldn't work:
```
json_query('results[?name==`{}`].version'.format(query))
json_query('results[?name==`%s`].version' % (query))
```
Given the example json:
```
{
(...)
"results": [
{
"envra": "0:ntp-4.2.6p5-29.el7_8.2.x86_64",
"name": "ntp",
"repo": "installed",
"epoch": "0",
"version": "4.2.6p5",
"release": "29.el7_8.2",
"yumstate": "installed",
"arch": "x86_64"
},
(...)
],
(...)
}
```
created by:
```
- name: list installed packages
yum:
list: installed
register: installed_list
```
with a defined variable `query: ntp`, pass this variable to `json_query` in two ways:
```
- name: pass var to json_query - string formatting (1)
debug:
msg: "{{ installed_list|json_query('results[?name==`{}`].version'.format(query))|first }}"
- name: pass var to json_query - string formatting (2)
debug:
msg: "{{ installed_list|json_query('results[?name==`%s`].version' % (query))|first }}"
```
Results:
```
TASK [pass var to json_query - string formatting (1)] *****************************************************************************************************
ok: [host] => {
"msg": "4.2.6p5"
}
TASK [pass var to json_query - string formatting (2)] *****************************************************************************************************
ok: [host] => {
"msg": "4.2.6p5"
}
``` |
43,230,731 | I have a variable that has few lines. I would like to remove the last line from the contents of the variable. I searched the internet but all the links talk about removing the last line from a file.
Here is the content of my variable
```
$echo $var
$select key from table_test
UNION ALL
select fob from table_test
UNION ALL
select cal from table_test
UNION ALL
select rot from table_test
UNION ALL
$
```
I would like to get rid of UNION ALL appearing in the last line alone. | 2017/04/05 | [
"https://Stackoverflow.com/questions/43230731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5658836/"
] | `sed` can do it the same way it would do it from a file :
```
> echo "$var" | sed '$d'
```
EDIT : `$` represents the last line of the file, and `d` deletes it.
See [here](http://sed.sourceforge.net/sedfaq3.html#s3.1) for details | Try this:
```
last_line=`echo "${str##*$'\n'}"` # "${str##*$'\n'}" value gives the last line for 'str'
str=${str%$last_line} # subtract last line from 'str'
echo "${str}"
``` |
14,582,661 | I'm developing Spring MVC application. In my application I have two profiles, test and production. Test is enable when I deploy my app to test envirionemnt, Production on production environment.
I need to get current profile in jsp file. Is it possible ? I don't want to send additional variable to get this information because file is included to lot of others files.
Thanks | 2013/01/29 | [
"https://Stackoverflow.com/questions/14582661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1958008/"
] | You can use something like the following:
```
ServletContext sc = request.getSession().getServletContext();
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
String[] profiles = applicationContext.getEnvironment().getActiveProfiles();
``` | For a more elegant way, you can create a custom JSP tag. Here is a tutorial you can use to achieve this: <http://blog.florianlopes.io/access-spring-profiles-with-custom-jsp-tag/>
With this custom tag, you will be able to restrict an area based on the active Spring profile.
This idea is to extend the Spring ***RequestContextAwareTag***. It will give your custom tag access to Spring profiles. Extending this class, the implementation is straightforward:
```
public class ProfileConditionTag extends RequestContextAwareTag {
private String expectedProfile;
@Override
protected int doStartTagInternal() throws Exception {
final Environment environment = this.getRequestContext().getWebApplicationContext().getEnvironment();
if (environment != null) {
final String[] activeProfiles = environment.getActiveProfiles();
if (ArrayUtils.contains(activeProfiles, this.expectedProfile)) {
return EVAL_BODY_INCLUDE;
}
}
return SKIP_BODY;
}
// Getters, setters
}
```
The **SKIP\_BODY** return value tells the JSP processor to skip the tag body if the active profile is not the one expected.
1. Create the taglib description and import the tag:
```
<%@ taglib prefix="tagprefix" uri="/WEB-INF/taglib/profile.tld" %>
```
2. Use it:
`<tagprefix:profile value="dev">
Only displayed if the active Spring profile is "dev".
</tagprefix:profile>` |
32,637,368 | I purchased a new macbook and I am now working on getting my apps to run on a 64bit mac.
However I haven't been able to remove the default menubar.
Is there anyway to change my app name from Electron to something else within Electron via app.js so I don't see Electron in Finder (revert to screenshot for better understanding)? Is there any way to remove the edit, view window, and help menus?

**package.json**:
```
{
"name": "hello",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "electron ."
},
"author": "",
"license": "ISC",
"devDependencies": {
"electron-prebuilt": "^0.33.0"
}
}
```
**app.js**:
```
var app = require("app"),
BrowserWindow = require("browser-window");
app.on("ready", function() {
var mainWindow = new BrowserWindow({
toolbar: false,
"skip-taskbar": true,
"auto-hide-menu-bar": true,
width: 800,
height: 600
});
mainWindow.loadUrl("file://" + __dirname + "/index.html");
mainWindow.setMenuBarVisibility(false);
mainWindow.setAutoHideMenuBar(true);
mainWindow.openDevTools();
});
```
**index.html**:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
Hello world!
</body>
</html>
``` | 2015/09/17 | [
"https://Stackoverflow.com/questions/32637368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/710887/"
] | I got same problem here with my electron app
I tried `mainWindow.setMenu(null);` but it didn't work
but I noticed that when app is running, there was an electron icon show in the dock which is your app
I think maybe this is the point to cause the problem here
just give it a try
```
app.dock.hide();
```
**Notice: it's an os x only method ([documentation](https://electronjs.org/docs/api/app#appdockhide-macos))**
there you go
[](https://i.stack.imgur.com/pSfMH.jpg)
after hide dock icon, you app no longer have default functions of ApplicationMenu or dockMenu, such as Quit, About, Hide etc...
so you can consider about give your app a [Tray](http://electron.atom.io/docs/v0.37.3/api/tray/#tray) | The name Electron is in the `Info.plist` file inside Electron.app, change it to what you want. |
20,203,363 | Looking through a [fundamental C++ type reference](http://en.cppreference.com/w/cpp/language/types), you see that on LP64, `long` is 64 bits, just like `long long` on the same platform. Does that mean that these two types are identical on an LP64 platform? | 2013/11/25 | [
"https://Stackoverflow.com/questions/20203363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/916907/"
] | No, it doesn't. It only means that they are equally wide. | No, take for instance:
```
void foo(long);
void bar()
{
foo(5L);
}
void foo(long long val)
{
std::cout << val;
}
```
This fails to link. |
2,044 | My 2.5 year old has recently developed what can be best described as a stutter.
It only seems to occur with us, and mostly when asking a question ("Wh, wh, wh, wh, what's that Daddy?). It's especially pronounced if he is tired.
It doesn't concern us greatly yet, he's happy and sociable. In fact it doesn't tend to occur around strangers.
**Update**: He's started to garble whole sentences recently, again mostly when he's tired, but he's also started getting noticeably frustrated.
His vocabulary is very wide and still growing quickly - if anything, it feels like his mouth can't keep up with this brain!
Is this similar to others experiences - how did you approach it? Should we ignore it (for now) and make no special effort, or would simple speech therapies help?
**Update - 2.5 years later**: It was just a phase, passed in a few months. He's near top of his class for reading, writing and spelling (phonetically or not).
As suggested in the great answers (and common with so many aspects of kids growing up), keep an eye on it to make sure it's not an early warning - but don't panic :) | 2011/06/20 | [
"https://parenting.stackexchange.com/questions/2044",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/43/"
] | It depends. Certain things should be treated right away with therapy but stuttering of certain types, switching vowels or consonants, and many other "issues" may be completely normal speech progression, especially in a 2.5 year old. We got my son's speech checked out for a similar reason and the professional determined that it was normal. She turned out to be correct. He progressed past it naturally. Since it is causing concern you should certainly talk to a professional who will be able to tell the difference better than a forum. | I wouldn't worry about it. Our son did the same thing when his vocabulary was expanding, sometime starting around two years old. He grew out of it after a 2-6 months, he is 5 now and doesn't exhibit any of the stuttering behaviors.
*There is enough things to spend energy on when it comes to parenting (modeling and teaching integrity, enjoying your children, having a healthy marriage, etc.) Don't worry too much about your child's vocal-explorations :)* |
154,052 | In content type setting in drupal, we have tab comment setting .The comment setting on future content of this type will default to:
* **Hidden:** No comments are allowed, and past comments are hidden.
* Closed: No comments are allowed, but any past comments remain visible.
* Open: Any future content of this type is open to new comments.
**Why do we need HIDDEN option?** It does not make sense in content type setting . If we set this option - in any new nodes that will be created next - comment will be closed.
This option has sense only in particular material, if it has comments.
Please explain me why this option need in content type settings?
Thanks... | 2015/04/06 | [
"https://drupal.stackexchange.com/questions/154052",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/45872/"
] | I found this link, it is very simple. <http://bonify.io/blog/2014/09/limit-quantity-when-adding-product-cart>
1. Events
* Before saving a commerce line item
2. condition
* Entity is of bundle
data selector: commerce-line-item, value: product
* Data comparison
Data to compare : commerce-line-item:commerce-product:product-id, operator: equal, Value:1
3. Action
* set a data value
data: commerce-line-item:quantity, value: 1
* Save Entity
Data selector: commerce-line-item,
* Show a message on the site
Message: This product only available for 1., Value: warning | October 2022: Running Commerce Core on Drupal 7
So I struggled with this. On my website we sell digital products so the quantity never needed to be larger than one. I tried using spinners to prevent double clicking on the "Add to Cart" buttons but somehow users still found ways to double click. I still don't know how but they did. I started my solution from trying to follow the drupal commerce user guide.
<https://docs.drupalcommerce.org/commerce1/user-guide/shopping-cart/working-with-cart-rules-events>
The problem I ran into was that when I tried to set the condition to
commerce-line-item:quantity > 1 it tried to force me to use data selectors which doesn't give me any value option.
The only thing I could do was set
commerce-line-item:quantity = 2 and then the routine would work. But if someone triple and went really crazy with the clicks this would not work because the QTY would get to three before the rule would finish firing. I then tried adding more conditions in an OR statement but found the performance of the rule was unreliable even in non stress situations. THEN THE EUREKA MOMENT.
I didn't need any condition since everything on my website is to be set to 1. So no product type conditions, no pre-existing quantity conditions, etc... needed to be checked.
So here is what appears to be working for me. I'll come back and edit this if it fails at any point.
1. Create new Rule
2. Set Event to "After adding a product to the cart"
3. Set Actions to
1st Action: Set a Data Value commerce-line-item:quantity = 1
2nd Action: Set Save Entity commerce-line-item:order I left "Force Immediate Save to false (or unchecked).
Comments: On my website you must be logged in to make a purchase. It appears to work for regular registered users and the admin role. I'll come back and update if I have any new problems with this running. What this routine does is make sure that after the user has finally stopped clicking the "Add to Cart" button, line item quantity is set back to 1 and the cart is recalculated. I imagine it increases the "Add to Cart" time a little bit. But it should be worth it not to have calls from people that didn't realize they had overpaid because they added the product to the cart twice. I'm a bit surprised but it happens all the time. Especially on my website cause when I was on drupal 6 I used a different commerce solution and forcing a quantity of 1 was already coded in. So many customers never bothered to check. |
53,651,598 | Consider I have multiple lists
```
A = [1, 2, 3]
B = [1, 4]
```
and I want to generate a Pandas DataFrame in long format as follows:
```
type | value
------------
A | 1
A | 2
A | 3
B | 1
B | 4
```
What is the easiest way to achieve this? The way over the wide format and melt is not possible(?) because the lists may have different lengths. | 2018/12/06 | [
"https://Stackoverflow.com/questions/53651598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2080295/"
] | Here's a NumPy-based solution using a dictionary input:
```
d = {'A': [1, 2, 3],
'B': [1, 4]}
keys, values = zip(*d.items())
res = pd.DataFrame({'type': np.repeat(keys, list(map(len, values))),
'value': np.concatenate(values)})
print(res)
type value
0 A 1
1 A 2
2 A 3
3 B 1
4 B 4
``` | Check this, this borrows the idea from dplyr, tidyr, R programming languages' 3rd libs, the following code is just for demo, so I created two df: df1, df2, you can dynamically create dfs and concat them:
```
import pandas as pd
def gather(df, key, value, cols):
id_vars = [col for col in df.columns if col not in cols]
id_values = cols
var_name = key
value_name = value
return pd.melt(df, id_vars, id_values, var_name, value_name)
df1 = pd.DataFrame({'A': [1, 2, 3]})
df2 = pd.DataFrame({'B': [1, 4]})
df_messy = pd.concat([df1, df2], axis=1)
print(df_messy)
df_tidy = gather(df_messy, 'type', 'value', df_messy.columns).dropna()
print(df_tidy)
```
And you got output for df\_messy
```
A B
0 1 1.0
1 2 4.0
2 3 NaN
```
output for df\_tidy
```
type value
0 A 1.0
1 A 2.0
2 A 3.0
3 B 1.0
4 B 4.0
```
PS: Remeber to convert the type of values from float to int type, I just wrote it down for a demo, and didn't pay too much attention about the details. |
44,743,904 | I use FlatList with large number of items. I get following alert from Expo XDE.
>
> VirtualizedList: You have a large list that is slow to update - make
> sure your renderItem function renders components that follow React
> performance best practices like PureComponent, shouldComponentUpdate,
> etc. {"dt":13861,"prevDt":1498372326027,"contentLength":6624}
>
>
>
I used some optimization approaches to my FlatList for example PureComponent, but I still get this alert. Before I will describe my optimizations, could you tell me if this alert appears always even though FlatList is optimized? Or maybe it indicated actual issues with performance? I ask because performance of my FlatList is good. | 2017/06/25 | [
"https://Stackoverflow.com/questions/44743904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2631871/"
] | I noticed that the answer to this question dosen't proffer solution for those using functional component and hooks. I encountered this problem and i was able to get rid of it by using the hook "useMemo()"
```
<FlatList
keyExtractor={keyExtractor}
data={productsState.products}
renderItem={renderItem}
/>
const renderItem = ({ item }) => (
<ListItem
title={item.ProductName}
subtitle={(item.ProductQuantity) + " " + (item.QuantityType !==
null ? item.QuantityType : " ") }
bottomDivider
topDivider
chevron
checkmark={checkMark}
onLongPress={() => setCheckMark(!checkMark)}
rightSubtitle={(item.Currency !== null ? item.Currency: " " ) +
" " + (item.productCost !== null ? item.productCost: " " )}
rightSubtitleStyle={{ marginTop: -20 }}
badge={{ value: item.sellingPrice, textStyle: { color: 'orange' }, containerStyle: { marginTop: -20 } }}
/>
)
```
The renderItem function is an expensive computation, because it a long list to render. Instead I memoize it as follows
```
const memoizedValue = useMemo(() => renderItem, [productsState.product]);
<FlatList
keyExtractor={keyExtractor}
data={productsState.products}
renderItem={memoizedValue}
/>
const renderItem = ({ item }) => (
<ListItem
title={item.ProductName}
subtitle={(item.ProductQuantity) + " " + (item.QuantityType !==
null ? item.QuantityType : " ") }
bottomDivider
topDivider
chevron
checkmark={checkMark}
onLongPress={() => setCheckMark(!checkMark)}
rightSubtitle={(item.Currency !== null ? item.Currency: " " ) +
" " + (item.productCost !== null ? item.productCost: " " )}
rightSubtitleStyle={{ marginTop: -20 }}
badge={{ value: item.sellingPrice, textStyle: { color: 'orange' }, containerStyle: { marginTop: -20 } }}
/>
)
```
Don't forget to import useMemo from react, inorder to make this work.
Good Luck! | I figured it out, why this bug is happened. The main problem is, when your onEndReached event is happened, im sure you are loading something from server, which means, you need to wait until your loading is finished from server, so after that you can call onEndReached event.
But in your case there is multilple calling of onEndReached event. So when it happens, your application was trying to load datas from server again and again.
Ok, how to solve this problem: you need to create new state, for example
this is realization of infinite scrolling by pagination.
```
const [loader, setLoader] = useState<boolean>(false);
const onEndReached = (page) => {
if (next && !loader) {
setPage(page + 1)
}
}
const loadData = async () => {
setLoader(true);
const resp = await getData();
setLoader(false);
}
<FlatList ...someprops onEndReached={onEndReached} />
``` |
273,344 | I am trying to include an `.eps` figure in a document and build with pdflatex:
```
\documentclass[12pt,a4paper]{report}
\usepackage{graphicx}
\usepackage{epstopdf}
\begin{document}
\includegraphics{figure}
\end{document}
```
The error I get is:
```
sh: epstopdf: command not found
Package pdftex.def Error: File `figure-eps-converted-to.pdf' not found. \includegraphics{figure}
```
Adding `-shell-escape` as mentioned in previous posts does not solve the issue. I have reinstalled `epstopdf` with TeX Live. I am using TeXstudio 2.10.2 on Mac OS X 10.10.5.
Edit:
Apparently, this is an editor-related issue since everything works fine if called from command line. | 2015/10/16 | [
"https://tex.stackexchange.com/questions/273344",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/90022/"
] | With TeXLive 2015, `eps` files should be converted to `pdf` automatically when using pdflatex. There is no need to load the `epstopdf` package. The error you are getting suggests that the system is looking for the `epstopdf` script in the wrong place. According to [the user manual](http://texstudio.sourceforge.net/manual/current/usermanual_en.html#SECTION02), there are various settings that TeXStudio uses when looking for commands of this type. If there is a setting for `epstopdf`, then do
```
which epstopdf
```
in the terminal and paste the result in its place. Failing this, compile the following document with shell escape enabled:
```
\documentclass{article}
\begin{document}
\immediate\write18{echo $PATH > tmp1}
\immediate\write18{which epstopdf > tmp2}
\end{document}
```
(Note that this will destroy any existing files called `tmp1` and `tmp2` in the current directory.) Then edit your question by adding the contents of the files `tmp1` and `tmp2`.
**EDIT**
Integrated development environments are the work of Satan. I just downloaded TeXStudio and reproduced exactly the same problem. Using the code above, I determined that it is searching for epstopdf in a nonexistent TeXLive2012 directory. In the file
```
~/.config/texstudio/texstudio.ini
```
I found the following:
```
Tools\Search%20Paths=/usr/local/texlive/2012/bin/x86_64-darwin
```
I can't find an option to change this from within TeXStudio (someone else who knows the software better than me may know how to do it). I tried editing the file, since I think it should be
```
Tools\Search%20Paths=/usr/texbin
```
but when I restarted TeXStudio the `.ini` file changed back automatically. Here is a workaround (which requires admin privileges). In the terminal:
```
sudo tsch
```
and enter your password to make yourself root. Now create the missing directory as follows:
```
cd /usr/local/texlive
mkdir 2012
cd 2012
mkdir bin
cd bin
mkdir x86_64-darwin
cd x86_64-darwin
```
Finally, create a symbolic link to the real location of `epstopdf`:
```
ln -s `which epstopdf` ./epstopdf
```
Now when TeXStudio looks for epstopdf it will find the symbolic link leading to the proper location. | You can basically remove the `\usepackage{epstopdf}` and just leave the code as it is.
So you will have:
```
\documentclass[12pt,a4paper]{report}
\usepackage{graphicx}
\begin{document}
\includegraphics{figure}
\end{document}
```
Of course you have to be sure that the file `figure.eps` is in the same folder of the .tex file you are trying to compile.
You need to use LaTex. I actually use : PdfLaTex. It works fine.
Let me know if it works. |
188,004 | I suggest that SO uses low votes per view as a reason to to raise questions for review.
Each time someone views a question, there is a chance they will vote it up, or vote it down. Someone that searches for questions on a particular subject and is lead to a question that is *irrelevant* to what they are interested are unlikely to up-vote the question, but if the question is not inherently bad they are unlikely to down-vote it.
A question with many views but few votes is therefore a question that superficially seems relevant to many people, but in fact is not. I suggest that questions with overly general titles are particular likely to be in this category. Let us call them *click-bait*: the title in some search-engine results (including a SE "related questions" list) draws the visitor in, to click on the link... but the visitor wastes their time. Those questions are a kind of low quality question.
I suggest that SE automatically searches for questions that have had quite a few views, but a low votes/views ratio, and adds them to the "Low quality posts" queue, so they can be edited to have a better title and/or tagging. | 2013/07/09 | [
"https://meta.stackexchange.com/questions/188004",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/170084/"
] | The problem with this suggestion is that there is a class of questions that is not likely to be downvoted or upvoted yet is high quality: Questions about specialized or difficult subjects.
They won't be downvoted because they look like effort posts.
But, they won't be upvoted because the viewer doesn't have enough knowledge in that field to determine that it's a meaningful question. | I like this feature request because I did some [research about these questions especially on SO](https://meta.stackexchange.com/a/274590/270345) and my impression is that most of these questions are indeed close worthy, but some of them also may profit a lot from improvement. Being in a review queue should be a good thing in any case for them.
The clickbait might actually be involuntary, i.e. the result of the design of search engine algorithms, not the result of conscious decisions by the content creators.
Additionally I suggest to
* limit the selection to a maximal score (for example <5 otherwise it's not low quality anymore) and a minimal view count (say 80% quantile) to focus on only those that are likely high impact and low quality
* feed high view count questions first (so maybe sort by number votes divided by view count squared) |
21,478,461 | We have two divs:
How to select all the input field as an array with name="divText" that are inside "div2".
//Body of div1
```
<div id="div1>
<input type="text" name="divText" value="v1" />
<input type="text" name="divText" value="v2"/>
<input type="text" name="divText" value="v3"/>
</div>
```
//Body of div2
```
<div id="div2>
<input type="text" name="divText" value="q1" />
<input type="text" name="divText" value="q2"/>
<input type="text" name="divText" value="q3"/>
</div>
``` | 2014/01/31 | [
"https://Stackoverflow.com/questions/21478461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2043769/"
] | Use [Attribute Equals Selector [name="value"]](http://api.jquery.com/attribute-equals-selector/) along with [ID Selector (“#id”)](http://api.jquery.com/id-selector/). There is error in your html the closing quote of div `id` `div1` and `div2` is missing as well.
**[Live Demo](http://jsfiddle.net/9cMqa/1/)**
```
$('#div2 input[name="divText"]')
``` | Another way :
```
$("#div2 input[type=text]")
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.