qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
36,714,152 | ```
var PeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var iceServers = [];
var optional = {
optional: []
};
var constraints = {
'offerToReceiveAudio': true,
'offerToReceiveVideo': true
};
var promiseCreateOffer = function() {
var peer ;
try{
peer = new PeerConnection(iceServers, optional);
}
catch(err){
console.log('error ',err);
return ;
}
peer.createOffer(constraints).then(
function(offer) {
return peer.setLocalDescription(offer);
})
.then(function() {
console.log('ok ',peer.localDescription);
},
function(){
// when promise rejected state,called
console.log('rejected ');
},function(){
//when promise progress state become rejected,called
console.log('progress ');
}
)
.catch(function(reason) {
// An error occurred
console.log('onSdpError: ', reason);
});
}
promiseCreateOffer();
```
when called promiseCreateOffer(),total 20% users has no any response include error event
//this my full js code
function TESTRTCPeerConnection(config) {
var options = {
iceServers: null,
onOfferSDP: null,
onOfferSDPError: null,
onICE: null,
onAnswerSdpSucess: null,
onAnswerSdpError: null,
onRemoteStreamEnded: null,
onRemoteStream: null
};
var peer;
window.moz = !!navigator.mozGetUserMedia;
var w = window;
var PeerConnection = w.mozRTCPeerConnection || w.webkitRTCPeerConnection || w.RTCPeerConnection;
var SessionDescription = w.mozRTCSessionDescription || w.RTCSessionDescription;
var IceCandidate = w.mozRTCIceCandidate || w.RTCIceCandidate;
var iceServers = [];
iceServers.push({
url: 'stun:stun.l.google.com:19302',
urls: 'stun:stun.l.google.com:19302'
});
var self = this;
var getCandidate = false;
iceServers = {
iceServers: iceServers
};
var optional = {
optional: []
};
var nowCreatSdpTime;
```
self.sendUT = function (msg) {
msg.liveuuid = config.liveuuid;
console.log('TestWebrtcSendUT=', msg);
//static function
};
try {
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'TestNewPeerConnection'
});
peer = new PeerConnection(iceServers, optional);
if (!peer) {
console.error('[TESTRTCPeerConnection]peer new fail');
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'TestNewPeerConnectionFail'
});
return;
}
} catch (err) {
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'CatchTestNewPeerConnectionFail',
error: err
});
return;
}
peer.onicecandidate = function (event) {
if (event.candidate) {
if (options.onICE) {
options.onICE(event.candidate);
}
if (getCandidate === false) {
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'TestOnIceCandidateEvent',
time: new Date().getTime() - nowCreatSdpTime
});
getCandidate = true;
}
console.log('[TESTRTCPeerConnection] candidate:', JSON.stringify(event.candidate));
}
};
peer.onsignalingstatechange = function (state) {
console.log('[TESTRTCPeerConnection] onsignalingstatechange', state);
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'TestOnSignalingstatechange',
state: peer.signalingState,
time: new Date().getTime() - nowCreatSdpTime
});
};
peer.onaddstream = function (event) {
var remoteMediaStream = event.stream;
// onRemoteStreamEnded(MediaStream)
remoteMediaStream.onended = function () {
if (options.onRemoteStreamEnded) {
options.onRemoteStreamEnded(remoteMediaStream);
}
};
// onRemoteStream(MediaStream)
if (options.onRemoteStream) {
options.onRemoteStream(remoteMediaStream);
}
console.log('[TESTRTCPeerConnection] on:add:stream', remoteMediaStream);
};
var constraints = {
offerToReceiveAudio: true,
offerToReceiveVideo: true
};
self.createOffer = function () {
peer.createOffer(function (sessionDescription) {
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'TestCreateOfferSucess',
time: new Date().getTime() - nowCreatSdpTime
});
try {
peer.setLocalDescription(sessionDescription);
} catch (error) {
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'CatchTestCreateOfferSucessError',
time: new Date().getTime() - nowCreatSdpTime
});
}
console.log('[TESTRTCPeerConnection] offer-sdp', sessionDescription.sdp);
},
function (message) {
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'TestCreateOfferFail',
time: new Date().getTime() - nowCreatSdpTime
});
console.error('[TESTRTCPeerConnection] onSdpError:', message);
},
constraints);
};
self.promiseCreateOffer = function () {
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'promiseTestCreateOffer',
time: new Date().getTime() - nowCreatSdpTime
});
peer.createOffer(constraints).then(
function (offer) {
console.log('[TESTRTCPeerConnection] promiseCreateOffer onSdp sucess:', offer);
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'promiseTestCreateOfferSucess',
time: new Date().getTime() - nowCreatSdpTime
});
return peer.setLocalDescription(offer);
})
.then(
function () {
console.log('[TESTRTCPeerConnection] promiseCreateOffer onSdp: ', peer.localDescription);
},
function () {
// rejected
console.log('[TESTRTCPeerConnection] promiseCreateOffer rejected ');
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'promiseTestCreateOfferReject',
time: new Date().getTime() - nowCreatSdpTime
});
},
function () {
// progress
console.log('[TESTRTCPeerConnection] promiseCreateOffer progress ');
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'promiseTestCreateOfferProgress',
time: new Date().getTime() - nowCreatSdpTime
});
})
.catch(function (reason) {
// An error occurred, so handle the failure to connect
console.log('[TESTRTCPeerConnection] promiseCreateOffer onSdpError: ', reason);
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'promiseTestCreateOfferCatchFail',
time: new Date().getTime() - nowCreatSdpTime,
error: reason
});
});
};
self.addAnswerSDP = function (sdp) {
var answer = new SessionDescription({
type: 'answer',
sdp: sdp
});
console.log('[TESTRTCPeerConnection] adding answer-sdp', sdp);
peer.setRemoteDescription(answer, self.onAnswerSdpSuccess, self.onAnswerSdpError);
};
self.onAnswerSdpSuccess = function (msg) {
console.log('[TESTRTCPeerConnection] onSdpSuccess', msg);
if (options.onAnswerSdpSuccess) {
options.onAnswerSdpSuccess(msg);
}
};
self.onAnswerSdpError = function (error) {
console.log('[TESTRTCPeerConnection] onAnswerSdpError', error);
if (options.onAnswerSdpError) {
options.onAnswerSdpError(error);
}
};
self.addICE = function (candidate) {
peer.addIceCandidate(new IceCandidate({
sdpMLineIndex: candidate.sdpMLineIndex,
candidate: candidate.candidate
}));
console.log('[TESTRTCPeerConnection] adding-ice', candidate.candidate);
};
nowCreatSdpTime = new Date().getTime();
console.log('[TESTRTCPeerConnection] createoffer start ', nowCreatSdpTime);
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'TestCreateOfferStart'
});
if (window.moz) {
self.promiseCreateOffer();
} else {
self.createOffer();
}
console.log('[TESTRTCPeerConnection] createoffer end ', (new Date().getTime()) - nowCreatSdpTime);
self.sendUT({
type: 'others',
modId: 'webrtc',
country: 'country',
position: 'TestCreateOfferEnd',
time: (new Date().getTime()) - nowCreatSdpTime
});
```
}
var mywebrtc = new TESTRTCPeerConnection({
liveuuid:"123456"
}); | 2016/04/19 | [
"https://Stackoverflow.com/questions/36714152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6223899/"
] | I should say your code worked fine for me in Firefox (I see 'ok'). That said, your code is problematic.
I realize this is a test function, but `peer` is a local variable inside `promiseCreateOffer`, so once `promiseCreateOffer` returns (which it does immediately), you have zero references to `peer`, so what prevents it from being garbage collected?
Garbage collection happens in the background, so that's the only thing I can think of that might explain something like what you are saying is happening to 20% of users (though I didn't observe it myself).
Try moving the reference out to see if it helps.
Other nits:
* You're passing three functions to `then`, which take two arguments.
* Don't start promise chains inside functions without returning a corresponding promise. | I was getting this issue because I had code in the `onnegotiationneeded` event that was not returning. I think `createoffer` waits for `onnegotiationneeded` to return before continuing. |
60,020,447 | I want to show an element and hide an element at the same time, 2 seconds after the page has loaded, I know the below code is not right, but I am just using it to help understand the logic I am trying to achieve.
```
delay(2000).$('#customer_contact').hide().$('#customer_contact_edit_cont').show();
```
How could this logic best be written? | 2020/02/01 | [
"https://Stackoverflow.com/questions/60020447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2305490/"
] | Aside from the syntax issues, the `delay()` function is intended to delay animations from happening which are scheduled to run on jQuery's `fx` queue.
If you want to delay an action from occurring outside of animation then you can use `setTimeout()`, like this:
```
setTimeout(function() {
$('#customer_contact').hide();
$('#customer_contact_edit_cont').show();
}, 2000);
``` | You should use the `setTimeout` function.
```
setTimeout(
function(){
//Do something
}, 5000);
```
Here `5000` being the time in milliseconds. (`1 sec = 1000 ms`) |
58,130,477 | When I publish with VS, an app\_offline.htm file is generated on my IIS website root folder. There is a way to custom this last please ? | 2019/09/27 | [
"https://Stackoverflow.com/questions/58130477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11265167/"
] | In previous versions this was only changeable by tracking down the file in the VS installation.
I've not seen anything to suggest this has changed in 2019. | I'm afraid we can no longer customize VS app\_offline template any more. But I think you can create a custom app\_offline.htm in the root folder of your project. Then You only have to specify the operation to this file in your web deploy publish profile.
<https://learn.microsoft.com/en-us/aspnet/web-forms/overview/deployment/advanced-enterprise-web-deployment/taking-web-applications-offline-with-web-deploy>
[Is there a way to make the VS2010 publish wizard to copy App\_offline.htm while it is publishing the site?](https://stackoverflow.com/questions/3630428/is-there-a-way-to-make-the-vs2010-publish-wizard-to-copy-app-offline-htm-while-i) |
29,459,428 | I can't figure out why this loop does not execute even once:
```
String s = "1 2\n3 4";
Scanner scanner = new Scanner(s);
while(scanner.hasNext("\\d\\s\\d")) {
System.out.printf("%d %d\n", scanner.nextInt(), scanner.nextInt());
}
```
To my understanding, "\d\s\d" means digit followed by whitespace followed by another digit - exactly what the input is like, but the loop never executes even once.
My intention is to use Scanner with stdin where I want to assure that input has a sequence of two-digit pairs separated by whitespace, but the code example above is simplified, as I assume I'm doing something wrong with how I use the regex.
Can anyone offer an explanation? Thanks in advance. | 2015/04/05 | [
"https://Stackoverflow.com/questions/29459428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1986520/"
] | Avoid `while` loops if speed is a concern. The loop lends itself to a `for` loop as start and end are fixed. Additionally, your code does a lot of copying which isn't really necessary. The rewritten function:
```
def ContextualWindows (arrb4,arrb5,pfire):
''' arrb4,arrb5,pfire are 31*31 sampling windows from
large 1500*6400 numpy array '''
for i in range (5, 16):
lo = 15 - i # 10..0
hi = 16 + i # 21..31
# only output the array data when it is 'large' enough
# to have enough good quality data to do calculation
if np.ma.count(arrb4[lo:hi, lo:hi]) >= min(10, 0.25*i*i):
return (arrb4[lo:hi, lo:hi], arrb5[lo:hi, lo:hi], pfire[lo:hi, lo:hi], 0)
else: # unknown pixel: background condition could not be characterized
return (arrb4, arrb5, pfire, 1)
```
For clarity I've used style guidelines from PEP 8 (like extended comments, number of comment chars, spaces around operators etc.). Copying of a windowed `arrb4` occurs twice here but only if the condition is fulfilled and this will happen only once per function call. The `else` clause will be executed only if the `for`-loop has run to it's end. We don't even need a `break` from the loop as we exit the function altogether.
Let us know if that speeds up the code a bit. I don't think it'll be much but then again there isn't much code anyway. | I've run some time tests with `ContextualWindows` and variants. One `i` step takes about 50us, all ten about 500.
This simple iteration takes about the same time:
```
[np.ma.count(arrb4[15-i:16+i,15-i:16+i]) for i in range(5,16)]
```
The iteration mechanism, and the 'copying' arrays are minor parts of the time. Where possible `numpy` is making views, not copies.
I'd focus on either minimizing the number of these `count` steps, or speeding up the `count`.
---
Comparing times for various operations on these windows:
First time for 1 step:
```
In [167]: timeit [np.ma.count(arrb4[15-i:16+i,15-i:16+i]) for i in range(5,6)]
10000 loops, best of 3: 43.9 us per loop
```
now for the 10 steps:
```
In [139]: timeit [arrb4[15-i:16+i,15-i:16+i].shape for i in range(5,16)]
10000 loops, best of 3: 33.7 us per loop
In [140]: timeit [np.sum(arrb4[15-i:16+i,15-i:16+i]>500) for i in range(5,16)]
1000 loops, best of 3: 390 us per loop
In [141]: timeit [np.ma.count(arrb4[15-i:16+i,15-i:16+i]) for i in range(5,16)]
1000 loops, best of 3: 464 us per loop
```
Simply indexing does not take much time, but testing for conditions takes substantially more.
`cumsum` is sometimes used to speed up sums over sliding windows. Instead of taking sum (or mean) over each window, you calculate the `cumsum` and then use the differences between the front and end of window.
Trying something like that, but in 2d - cumsum in both dimensions, followed by differences between diagonally opposite corners:
```
In [164]: %%timeit
.....: cA4=np.cumsum(np.cumsum(arrb4,0),1)
.....: [cA4[15-i,15-i]-cA4[15+i,15+i] for i in range(5,16)]
.....:
10000 loops, best of 3: 43.1 us per loop
```
This is almost 10x faster than the (nearly) equivalent `sum`. Values don't quite match, but timing suggest that this may be worth refining. |
44,948,894 | I am creating a login form and I need to redirect the user to his/her profile page! I am using AJAX Requests so header redirect is not working at all. It just stays on the homepage.
So how can I redirect the user to another page in pure javascript PHP ajax call? Please give the answer in pure javascript. I don't like to use jQuery at all!
Javascript:
```
function ajaxCall(){
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}
xhttp.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
document.getElementById('error').innerHTML = this.responseText;
}
};
var parameters = 'email='+document.getElementById('email')+'&password='+document.getElementById('password');
xhttp.open('POST', 'login.php', true);
xhttp.setRequestHeader('Content-type', 'application/x-www/form/urlencoded');
xhttp.send(parameters);
}
```
Login.php(PHP)
```
<?php
if(isset($_POST['email']) && isset($_POST['password'])){
$ema = $_POST['email'];
$pass = $_POST['password'];
if(!empty($ema) && !empty($pass)){
if($ema === 'Bill' && $pass === 'Cool'){
header('Location: https://www.google.com');
}
}
}
``` | 2017/07/06 | [
"https://Stackoverflow.com/questions/44948894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8220749/"
] | Make an ajax call.
```
<?php
header('Content-Type: application/json');
echo json_encode(['location'=>'/user/profile/']);
exit;
?>
```
The ajax response will return something like
```
{'location':'/user/profile/'}
```
In your ajax success javascript function
```
xhr.onreadystatechange = function () {
if (xhr.status >= 200 && xhr.status <= 299)
{
var response = JSON.parse(xhr.responseText);
if(response.location){
window.location.href = response.location;
}
}
}
``` | try this bill if its works.
```
window.location.replace("http://www.google.com");
``` |
44,948,894 | I am creating a login form and I need to redirect the user to his/her profile page! I am using AJAX Requests so header redirect is not working at all. It just stays on the homepage.
So how can I redirect the user to another page in pure javascript PHP ajax call? Please give the answer in pure javascript. I don't like to use jQuery at all!
Javascript:
```
function ajaxCall(){
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}
xhttp.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
document.getElementById('error').innerHTML = this.responseText;
}
};
var parameters = 'email='+document.getElementById('email')+'&password='+document.getElementById('password');
xhttp.open('POST', 'login.php', true);
xhttp.setRequestHeader('Content-type', 'application/x-www/form/urlencoded');
xhttp.send(parameters);
}
```
Login.php(PHP)
```
<?php
if(isset($_POST['email']) && isset($_POST['password'])){
$ema = $_POST['email'];
$pass = $_POST['password'];
if(!empty($ema) && !empty($pass)){
if($ema === 'Bill' && $pass === 'Cool'){
header('Location: https://www.google.com');
}
}
}
``` | 2017/07/06 | [
"https://Stackoverflow.com/questions/44948894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8220749/"
] | I landed here looking for an Ajax solution, nevertheless MontrealDevOne's answer provided useful. If anyone else is curious about the ajax method too, here you go:
```
$('body').on('submit', '#form_register', function (e) {
var form = $(this);
$.ajax({
type: 'POST',
url: 'form_submissions.php',
data: form.serialize() + "&submit",
dataType:"json",
success: function (data) {
if(data.location){
window.location.href = data.location;
}
},
error: function(data) {
alert("Error!");
}
});
e.preventDefault();
});
```
Just my 2 cents, hope it helps :) | try this bill if its works.
```
window.location.replace("http://www.google.com");
``` |
44,948,894 | I am creating a login form and I need to redirect the user to his/her profile page! I am using AJAX Requests so header redirect is not working at all. It just stays on the homepage.
So how can I redirect the user to another page in pure javascript PHP ajax call? Please give the answer in pure javascript. I don't like to use jQuery at all!
Javascript:
```
function ajaxCall(){
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}
xhttp.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
document.getElementById('error').innerHTML = this.responseText;
}
};
var parameters = 'email='+document.getElementById('email')+'&password='+document.getElementById('password');
xhttp.open('POST', 'login.php', true);
xhttp.setRequestHeader('Content-type', 'application/x-www/form/urlencoded');
xhttp.send(parameters);
}
```
Login.php(PHP)
```
<?php
if(isset($_POST['email']) && isset($_POST['password'])){
$ema = $_POST['email'];
$pass = $_POST['password'];
if(!empty($ema) && !empty($pass)){
if($ema === 'Bill' && $pass === 'Cool'){
header('Location: https://www.google.com');
}
}
}
``` | 2017/07/06 | [
"https://Stackoverflow.com/questions/44948894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8220749/"
] | Make an ajax call.
```
<?php
header('Content-Type: application/json');
echo json_encode(['location'=>'/user/profile/']);
exit;
?>
```
The ajax response will return something like
```
{'location':'/user/profile/'}
```
In your ajax success javascript function
```
xhr.onreadystatechange = function () {
if (xhr.status >= 200 && xhr.status <= 299)
{
var response = JSON.parse(xhr.responseText);
if(response.location){
window.location.href = response.location;
}
}
}
``` | I landed here looking for an Ajax solution, nevertheless MontrealDevOne's answer provided useful. If anyone else is curious about the ajax method too, here you go:
```
$('body').on('submit', '#form_register', function (e) {
var form = $(this);
$.ajax({
type: 'POST',
url: 'form_submissions.php',
data: form.serialize() + "&submit",
dataType:"json",
success: function (data) {
if(data.location){
window.location.href = data.location;
}
},
error: function(data) {
alert("Error!");
}
});
e.preventDefault();
});
```
Just my 2 cents, hope it helps :) |
12,813,171 | Lets take an example of a table adapter (typed data-sets)
I am storing data-set in session. but I don't know what is better for table adapters.
In general, will creating object hit performance badly when compared to storing and getting from session ? | 2012/10/10 | [
"https://Stackoverflow.com/questions/12813171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365053/"
] | The two alternatives uses different resources.
Creating a new instance of an object uses time. Storing the instance in the session uses memory.
If you create a new instance each time you need one, it will only take up memory for the short while that you are using it. If you store it in the session, it will take up memory all the time, and if you don't remove it from the session it will even take up memory for a while after the user has left.
If you were thinking of keeping the table adapter connected to the database while you keep it in the session, that would also use up a connection to the database, which is a resource that is even more limited. That would seriously limit the number of users that the site could handle.
Generally you should only store things in the session that actually has state, i.e. something that really has data that you need to keep. Most objects take so little time to create that there is no point in keeping them just to avoid creating them again. | I am not sure, Why Would you store it in session, But Remember Session is the most **expensive** resource in web development. |
12,813,171 | Lets take an example of a table adapter (typed data-sets)
I am storing data-set in session. but I don't know what is better for table adapters.
In general, will creating object hit performance badly when compared to storing and getting from session ? | 2012/10/10 | [
"https://Stackoverflow.com/questions/12813171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365053/"
] | I am not sure, Why Would you store it in session, But Remember Session is the most **expensive** resource in web development. | It all depends upon your requirement what you want to do and how much the data you have.
according to me session is not a good option to store data-set because once it occupies the memory will not be available.and session has some limitations like if your session has expired then it can throw error of null, you will need to refresh it time to time.
Much better is when you need data-set with large data to give call to database because storing data slow down your application i.e performance may decreases badly. you can use indexes option in sql server to fast return the data. |
12,813,171 | Lets take an example of a table adapter (typed data-sets)
I am storing data-set in session. but I don't know what is better for table adapters.
In general, will creating object hit performance badly when compared to storing and getting from session ? | 2012/10/10 | [
"https://Stackoverflow.com/questions/12813171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365053/"
] | The two alternatives uses different resources.
Creating a new instance of an object uses time. Storing the instance in the session uses memory.
If you create a new instance each time you need one, it will only take up memory for the short while that you are using it. If you store it in the session, it will take up memory all the time, and if you don't remove it from the session it will even take up memory for a while after the user has left.
If you were thinking of keeping the table adapter connected to the database while you keep it in the session, that would also use up a connection to the database, which is a resource that is even more limited. That would seriously limit the number of users that the site could handle.
Generally you should only store things in the session that actually has state, i.e. something that really has data that you need to keep. Most objects take so little time to create that there is no point in keeping them just to avoid creating them again. | Thats always depends on your requirement.
If the data in dataset is less and you are making call to database very frequently to get same data again and again than its better to store that in session, But if data is same for all user than you should make use of Cache because its faster than session.
But if the data is large in dataset than its better to give call to database because storing data slow down your application i.e performance may decreses badly.
**Note** : this always depends on datasize and how frequently you query data from database. |
12,813,171 | Lets take an example of a table adapter (typed data-sets)
I am storing data-set in session. but I don't know what is better for table adapters.
In general, will creating object hit performance badly when compared to storing and getting from session ? | 2012/10/10 | [
"https://Stackoverflow.com/questions/12813171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365053/"
] | Thats always depends on your requirement.
If the data in dataset is less and you are making call to database very frequently to get same data again and again than its better to store that in session, But if data is same for all user than you should make use of Cache because its faster than session.
But if the data is large in dataset than its better to give call to database because storing data slow down your application i.e performance may decreses badly.
**Note** : this always depends on datasize and how frequently you query data from database. | It all depends upon your requirement what you want to do and how much the data you have.
according to me session is not a good option to store data-set because once it occupies the memory will not be available.and session has some limitations like if your session has expired then it can throw error of null, you will need to refresh it time to time.
Much better is when you need data-set with large data to give call to database because storing data slow down your application i.e performance may decreases badly. you can use indexes option in sql server to fast return the data. |
12,813,171 | Lets take an example of a table adapter (typed data-sets)
I am storing data-set in session. but I don't know what is better for table adapters.
In general, will creating object hit performance badly when compared to storing and getting from session ? | 2012/10/10 | [
"https://Stackoverflow.com/questions/12813171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365053/"
] | The two alternatives uses different resources.
Creating a new instance of an object uses time. Storing the instance in the session uses memory.
If you create a new instance each time you need one, it will only take up memory for the short while that you are using it. If you store it in the session, it will take up memory all the time, and if you don't remove it from the session it will even take up memory for a while after the user has left.
If you were thinking of keeping the table adapter connected to the database while you keep it in the session, that would also use up a connection to the database, which is a resource that is even more limited. That would seriously limit the number of users that the site could handle.
Generally you should only store things in the session that actually has state, i.e. something that really has data that you need to keep. Most objects take so little time to create that there is no point in keeping them just to avoid creating them again. | It all depends upon your requirement what you want to do and how much the data you have.
according to me session is not a good option to store data-set because once it occupies the memory will not be available.and session has some limitations like if your session has expired then it can throw error of null, you will need to refresh it time to time.
Much better is when you need data-set with large data to give call to database because storing data slow down your application i.e performance may decreases badly. you can use indexes option in sql server to fast return the data. |
29,069,051 | I'm trying to use ckeditor with code snippet. The easiest would be to use the CDN and include it as a script tag. But the default ck editor doesn't have the code snippet plugin. If I download a custom package with code snippet included, then I have to modify all the files to work with Rails asset pipeline, which I don't want to do.
How can I put my own files or as a CDN for free, or find some other low-hassle way to incorporate ckeditor custom packages without having to "railsify" it? | 2015/03/16 | [
"https://Stackoverflow.com/questions/29069051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951835/"
] | You can still use CKEditor official CDN, but use full-all build, which includes all the official CKEditor plugins.
```
<script src="//cdn.ckeditor.com/4.4.7/full-all/ckeditor.js"></script>
```
And you're good to go. Don't forget to load this plugin, e.g. using [config.extraPlugins](http://docs.ckeditor.com/#!/api/CKEDITOR.config-cfg-extraPlugins). Like so:
```
CKEDITOR.replace( 'editor1', {
extraPlugins: 'codesnippet'
} );
``` | Install additional plugins gem 'ckeditor' codesnippet
```
//adding app/assets/javascripts/ckeditor/plugins/codesnippet
//app/assets/javascripts/ckeditor/config.js
CKEDITOR.editorConfig = function (config) {
config.extraPlugins = 'codesnippet';
}
```
<https://github.com/galetahub/ckeditor#install-additional-plugins>
<https://ckeditor.com/cke4/addon/codesnippetgeshi>
<https://ckeditor.com/cke4/addon/codesnippet>
<https://ckeditor.com/cke4/addon/ajax>
<https://ckeditor.com/cke4/addon/xml> |
22,654,446 | I am dynamically loading content in a page using jQuery Ajax. The content contains images, so I need to know at what point all the images will be loaded, something like DOM Ready.
Initially content will be hidden. After the images were loaded successfully I display the div containing them. Is there a method to detect when the loaded content with Ajax is ready to display? Ajax `success` function is called when the text response is returned from server but I need to execute a function when is all loaded and images are loaded as well. | 2014/03/26 | [
"https://Stackoverflow.com/questions/22654446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422404/"
] | If you have just inserted a bunch of HTML into your document (containing some `<img>` tags) and you want to know when all those new images are loaded, you can do it like this. Let's suppose that the dynamic content was all inserted into the `#root` object. Right after you've inserted the dynamic contend, you can run this code:
```
function notifyWhenImagesLoaded(rootSelector, callback) {
var imageList = $(rootSelector + " img");
var imagesRemaining = imageList.length;
function checkDone() {
if (imagesRemaining === 0) {
callback()
}
}
imageList.each(function() {
// if the image is already loaded, just count it
if (this.complete) {
--imagesRemaining;
} else {
// not loaded yet, add an event handler so we get notified
// when it finishes loading
$(this).load(function() {
--imagesRemaining;
checkDone();
});
}
});
checkDone();
}
notifyWhenImagesLoaded("#root", function() {
// put your code here to run when all the images are loaded
});
```
You call this function after you've inserted the dynamic content. It finds all images tags in the dynamic content and checks if any have already loaded. If they have, it counts them. If they haven't, then it installs a load event handler so it will get notified when the image loads. When the last image finishes loading, it calls the callback. | **ajax**
```
$.ajax({
type: "POST",
url: "myfile.*",
data: {data : params},
cache: false,
success: function(return_data){
//here you have the answer to Ajax
//at this point you have the content ready for use
//in your case here you would find the images that you got back from the file called by ajax
}
});
``` |
22,654,446 | I am dynamically loading content in a page using jQuery Ajax. The content contains images, so I need to know at what point all the images will be loaded, something like DOM Ready.
Initially content will be hidden. After the images were loaded successfully I display the div containing them. Is there a method to detect when the loaded content with Ajax is ready to display? Ajax `success` function is called when the text response is returned from server but I need to execute a function when is all loaded and images are loaded as well. | 2014/03/26 | [
"https://Stackoverflow.com/questions/22654446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422404/"
] | If you have just inserted a bunch of HTML into your document (containing some `<img>` tags) and you want to know when all those new images are loaded, you can do it like this. Let's suppose that the dynamic content was all inserted into the `#root` object. Right after you've inserted the dynamic contend, you can run this code:
```
function notifyWhenImagesLoaded(rootSelector, callback) {
var imageList = $(rootSelector + " img");
var imagesRemaining = imageList.length;
function checkDone() {
if (imagesRemaining === 0) {
callback()
}
}
imageList.each(function() {
// if the image is already loaded, just count it
if (this.complete) {
--imagesRemaining;
} else {
// not loaded yet, add an event handler so we get notified
// when it finishes loading
$(this).load(function() {
--imagesRemaining;
checkDone();
});
}
});
checkDone();
}
notifyWhenImagesLoaded("#root", function() {
// put your code here to run when all the images are loaded
});
```
You call this function after you've inserted the dynamic content. It finds all images tags in the dynamic content and checks if any have already loaded. If they have, it counts them. If they haven't, then it installs a load event handler so it will get notified when the image loads. When the last image finishes loading, it calls the callback. | you can use the on method with load.
Count how many items you have in total and use the load event to have a number of total images loaded. You can even build a progress bar like this.
Something like that and after you have finished with the ajax call
```
$('img').on('load', function(){
// Count items here
});
``` |
18,487,386 | I have an app with login screen. When checking if login is ok, I show a "Loading" `Dialog`.
If I change screen orientation, `Dialog`disappears and I think check of login starts again, but app crashes after that.
I've read some solutions, but I can't do it works.
**Here is my code:**
**MainActivity.java**
```
public void entrar(View view) {
/* Escondemos el teclado */
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editTextUsuario.getWindowToken(), 0);
/* Comprobamos si hay conexión a Internet */
if(myApplication.isOnline()) {
LoadingMainTask myWebFetch = new LoadingMainTask(this);
myWebFetch.execute();
}
/* Si no se dispone de conexión a Internet, mostramos un error */
else {
myApplication.mostrarMensaje(this, R.string.error_conexion_titulo,
R.string.error_conexion_mensaje);
}
}
private class LoadingMainTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
private volatile boolean running = true;
private MainActivity activity;
TuplaUsuario tuplaUsuario = new TuplaUsuario();
private LoadingMainTask(MainActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
dialog.setCancelable(true);
dialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
cancel(true);
}
});
}
/** application context. */
private Context context;
@Override
protected void onCancelled() {
running = false;
}
@Override
protected void onPreExecute() {
this.dialog.setMessage(getString(R.string.loading));
this.dialog.show();
}
@Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
/* Si el login no es correcto, mostramos un error por pantalla */
if (!tuplaUsuario.getOk()) {
myApplication.mostrarMensaje(activity, R.string.error_datos_login_titulo,
tuplaUsuario.getMensaje());
}
/* Entrar */
else {
Intent intent = new Intent(activity, TabsFacturasActivity.class);
startActivity(intent);
}
} else {
System.out.println("throw exception post");
myApplication.throwException(activity);
}
}
@Override
protected Boolean doInBackground(final String... args) {
try{
String usuario = String.valueOf((editTextUsuario).getText());
String password = String.valueOf((editTextPassword).getText());
/* Comprobar datos del login */
try {
tuplaUsuario = myApplication.getDatosUsuario(usuario, password, loginGuardado);
} catch (JSONException e) {
myApplication.throwException(activity);
e.printStackTrace();
} catch (IllegalStateException e) {
myApplication.throwException(activity);
e.printStackTrace();
} catch (IOException e) {
myApplication.throwException(activity);
e.printStackTrace();
}
/* Si el login es correcto, nos guardamos su login, descargamos el resto
* de información y entramos */
if (tuplaUsuario.getOk()) {
boolean rememberMe = myApplication.getRememberMe();
if (rememberMe) {
/* Si el usuario ya estaba guardado, no hace falta volver a guardarlo */
if(!loginGuardado) {
myApplication.guardarUsuario(activity, usuario, password);
}
}
}
return true;
} catch (Exception e){
return false;
}
}
}
```
**AndroidManifest.xml**
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ... >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/StyledIndicators"
android:configChanges="orientation"
android:name="com.example.factorenergia.MyApplication" >
<activity
android:name="com.example.factorenergia.MainActivity"
android:label="@string/app_name"
android:configChanges="orientation"
android:theme="@style/AppTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
...
</application>
</manifest>
``` | 2013/08/28 | [
"https://Stackoverflow.com/questions/18487386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1088643/"
] | Try this in your manifest...
```
<activity android:name="Your Activity Name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:windowSoftInputMode="adjustPan"/>
``` | Android recreates the Activity on every orientation change. In order to persist the current activity state you need to save `instance state` and later retrieve it if possible.
Refer to this tutorial: <http://www.intertech.com/Blog/saving-and-retrieving-android-instance-state-part-1/>
Though easyer solution would be to disable orientation changes on this screen. For that you need to add the following line to the login activity in `AndroidManifest.xml`.
```
android:screenOrientation="portrait"
``` |
61,824,118 | I've been working on integrating FCM in my Vue PWA app. So far I've managed to get the background notification working, but handling notifications when the app's on the foreground doesn't work. Here's my code.
### `src/App.vue`
```js
import firebase from './plugins/firebase'
export default {
// Other stuff here...
methods: {
prepareFcm () {
var messaging = firebase.messaging()
messaging.usePublicVapidKey(this.$store.state.fcm.vapidKey)
messaging.getToken().then(async fcmToken => {
this.$store.commit('fcm/setToken', fcmToken)
messaging.onMessage(payload => {
window.alert(payload)
})
}).catch(e => {
this.$store.commit('toast/setError', 'An error occured to push notification.')
})
}
},
mounted () {
this.prepareFcm()
}
}
```
### `public/firebase-messaging-sw.js`
```js
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-messaging.js')
firebase.initializeApp({
messagingSenderId: '123456789'
})
const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function (payload) {
return self.registration.showNotification(payload)
})
```
### `src/plugins/firebase.js`
```js
import firebase from '@firebase/app'
import '@firebase/messaging'
// import other firebase stuff...
const firebaseConfig = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '123456789',
appId: '...'
}
firebase.initializeApp(firebaseConfig)
export default firebase
```
What did I do wrong? | 2020/05/15 | [
"https://Stackoverflow.com/questions/61824118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2190916/"
] | I've found a solution in another QA here in StackOverflow (which I can't find anymore for some reason).
Turns out you have to use Firebase API v7.8.0 instead of 5.5.6 like the docs said at the time. So those first two lines in `public/firebase-messaging-sw.js` should read like this instead:
```js
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js')
``` | In my case the version on `package.json` (8.2.1) was different from the actual SDK\_VERSION (8.0.1)
After changed service-workers with the same version worked.. |
61,824,118 | I've been working on integrating FCM in my Vue PWA app. So far I've managed to get the background notification working, but handling notifications when the app's on the foreground doesn't work. Here's my code.
### `src/App.vue`
```js
import firebase from './plugins/firebase'
export default {
// Other stuff here...
methods: {
prepareFcm () {
var messaging = firebase.messaging()
messaging.usePublicVapidKey(this.$store.state.fcm.vapidKey)
messaging.getToken().then(async fcmToken => {
this.$store.commit('fcm/setToken', fcmToken)
messaging.onMessage(payload => {
window.alert(payload)
})
}).catch(e => {
this.$store.commit('toast/setError', 'An error occured to push notification.')
})
}
},
mounted () {
this.prepareFcm()
}
}
```
### `public/firebase-messaging-sw.js`
```js
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-messaging.js')
firebase.initializeApp({
messagingSenderId: '123456789'
})
const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function (payload) {
return self.registration.showNotification(payload)
})
```
### `src/plugins/firebase.js`
```js
import firebase from '@firebase/app'
import '@firebase/messaging'
// import other firebase stuff...
const firebaseConfig = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '123456789',
appId: '...'
}
firebase.initializeApp(firebaseConfig)
export default firebase
```
What did I do wrong? | 2020/05/15 | [
"https://Stackoverflow.com/questions/61824118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2190916/"
] | I've found a solution in another QA here in StackOverflow (which I can't find anymore for some reason).
Turns out you have to use Firebase API v7.8.0 instead of 5.5.6 like the docs said at the time. So those first two lines in `public/firebase-messaging-sw.js` should read like this instead:
```js
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js')
``` | I had a bunch of issues setting firebase push notifications for Vue 3 (with Vite), and I had PWA support enabled with `vite-plugin-pwa`, so it felt like I was flying blind half the time. I was finally able to set up support for PWA, but then I ran into the following issues:
* I was getting notifications in the background (when my app was not in focus), but not in the foreground.
* When I did get notifications in the background, it appeared twice.
Here's my complete setup. I have the latest firebase as of this post (`9.12.1`)
```
// firebase-messaging-sw.js file in the public folder
importScripts(
"https://www.gstatic.com/firebasejs/9.12.1/firebase-app-compat.js"
);
importScripts(
"https://www.gstatic.com/firebasejs/9.12.1/firebase-messaging-compat.js"
);
// Initialize Firebase
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: "/icon.png",
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
```
I've seen some posts online provide the `onBackgroundMessage` here in the service worker, but I experimented with commenting it out and it seemed to fix the issue of notifications appearing twice.
Next, is a `firebase.js` file with which I retrieve tokens and subsequently listen for foreground notifications.
```
// firebase.js in same location with main.js
import firebase from "firebase/compat/app";
import { getMessaging } from "firebase/messaging";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
};
const app = firebase.initializeApp(firebaseConfig);
export default getMessaging(app);
```
And then in `main.js`
```
import App from "./App.vue";
import firebaseMessaging from "./firebase";
const app = createApp(App)
app.config.globalProperties.$messaging = firebaseMessaging; //register as a global property
```
And finally, in `App.vue` (or wherever you wish to get tokens and send to your serverside)...
```
import {getToken, onMessage} from "firebase/messaging";
export default {
mounted() {
getToken(this.$messaging, {
vapidKey:
"XXX-XXX",
})
.then((currentToken) => {
if (currentToken) {
console.log("client token", currentToken);
onMessage(this.$messaging, (payload) => {
console.log("Message received. ", payload);
});
//send token to server-side
} else {
console.log(
"No registration token available. Request permission to generate one"
);
}
})
.catch((err) => {
console.log("An error occurred while retrieving token.", err);
});
}
}
```
Of course don't forget the `vapidKey`. Took a minute, but it worked perfectly.
For now, I am not offering any opinion as to what the foreground notification should look like, so I am merely logging the payload. But feel free to show it however you deem fit. |
61,824,118 | I've been working on integrating FCM in my Vue PWA app. So far I've managed to get the background notification working, but handling notifications when the app's on the foreground doesn't work. Here's my code.
### `src/App.vue`
```js
import firebase from './plugins/firebase'
export default {
// Other stuff here...
methods: {
prepareFcm () {
var messaging = firebase.messaging()
messaging.usePublicVapidKey(this.$store.state.fcm.vapidKey)
messaging.getToken().then(async fcmToken => {
this.$store.commit('fcm/setToken', fcmToken)
messaging.onMessage(payload => {
window.alert(payload)
})
}).catch(e => {
this.$store.commit('toast/setError', 'An error occured to push notification.')
})
}
},
mounted () {
this.prepareFcm()
}
}
```
### `public/firebase-messaging-sw.js`
```js
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-messaging.js')
firebase.initializeApp({
messagingSenderId: '123456789'
})
const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function (payload) {
return self.registration.showNotification(payload)
})
```
### `src/plugins/firebase.js`
```js
import firebase from '@firebase/app'
import '@firebase/messaging'
// import other firebase stuff...
const firebaseConfig = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '123456789',
appId: '...'
}
firebase.initializeApp(firebaseConfig)
export default firebase
```
What did I do wrong? | 2020/05/15 | [
"https://Stackoverflow.com/questions/61824118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2190916/"
] | Same issue i was faced. In my case firebase version in **"package.json"** and **"firebase-messaging-sw.js"** importScripts version was different. After set same version in **"firebase-messaging-sw.js"** importScripts which was in
**"package.json"**, my issue is resolved.
**Before change**
```
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js');
```
**After change**
```
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js');
``` | In my case the version on `package.json` (8.2.1) was different from the actual SDK\_VERSION (8.0.1)
After changed service-workers with the same version worked.. |
61,824,118 | I've been working on integrating FCM in my Vue PWA app. So far I've managed to get the background notification working, but handling notifications when the app's on the foreground doesn't work. Here's my code.
### `src/App.vue`
```js
import firebase from './plugins/firebase'
export default {
// Other stuff here...
methods: {
prepareFcm () {
var messaging = firebase.messaging()
messaging.usePublicVapidKey(this.$store.state.fcm.vapidKey)
messaging.getToken().then(async fcmToken => {
this.$store.commit('fcm/setToken', fcmToken)
messaging.onMessage(payload => {
window.alert(payload)
})
}).catch(e => {
this.$store.commit('toast/setError', 'An error occured to push notification.')
})
}
},
mounted () {
this.prepareFcm()
}
}
```
### `public/firebase-messaging-sw.js`
```js
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/5.5.6/firebase-messaging.js')
firebase.initializeApp({
messagingSenderId: '123456789'
})
const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function (payload) {
return self.registration.showNotification(payload)
})
```
### `src/plugins/firebase.js`
```js
import firebase from '@firebase/app'
import '@firebase/messaging'
// import other firebase stuff...
const firebaseConfig = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '123456789',
appId: '...'
}
firebase.initializeApp(firebaseConfig)
export default firebase
```
What did I do wrong? | 2020/05/15 | [
"https://Stackoverflow.com/questions/61824118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2190916/"
] | Same issue i was faced. In my case firebase version in **"package.json"** and **"firebase-messaging-sw.js"** importScripts version was different. After set same version in **"firebase-messaging-sw.js"** importScripts which was in
**"package.json"**, my issue is resolved.
**Before change**
```
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js');
```
**After change**
```
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js');
``` | I had a bunch of issues setting firebase push notifications for Vue 3 (with Vite), and I had PWA support enabled with `vite-plugin-pwa`, so it felt like I was flying blind half the time. I was finally able to set up support for PWA, but then I ran into the following issues:
* I was getting notifications in the background (when my app was not in focus), but not in the foreground.
* When I did get notifications in the background, it appeared twice.
Here's my complete setup. I have the latest firebase as of this post (`9.12.1`)
```
// firebase-messaging-sw.js file in the public folder
importScripts(
"https://www.gstatic.com/firebasejs/9.12.1/firebase-app-compat.js"
);
importScripts(
"https://www.gstatic.com/firebasejs/9.12.1/firebase-messaging-compat.js"
);
// Initialize Firebase
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: "/icon.png",
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
```
I've seen some posts online provide the `onBackgroundMessage` here in the service worker, but I experimented with commenting it out and it seemed to fix the issue of notifications appearing twice.
Next, is a `firebase.js` file with which I retrieve tokens and subsequently listen for foreground notifications.
```
// firebase.js in same location with main.js
import firebase from "firebase/compat/app";
import { getMessaging } from "firebase/messaging";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
};
const app = firebase.initializeApp(firebaseConfig);
export default getMessaging(app);
```
And then in `main.js`
```
import App from "./App.vue";
import firebaseMessaging from "./firebase";
const app = createApp(App)
app.config.globalProperties.$messaging = firebaseMessaging; //register as a global property
```
And finally, in `App.vue` (or wherever you wish to get tokens and send to your serverside)...
```
import {getToken, onMessage} from "firebase/messaging";
export default {
mounted() {
getToken(this.$messaging, {
vapidKey:
"XXX-XXX",
})
.then((currentToken) => {
if (currentToken) {
console.log("client token", currentToken);
onMessage(this.$messaging, (payload) => {
console.log("Message received. ", payload);
});
//send token to server-side
} else {
console.log(
"No registration token available. Request permission to generate one"
);
}
})
.catch((err) => {
console.log("An error occurred while retrieving token.", err);
});
}
}
```
Of course don't forget the `vapidKey`. Took a minute, but it worked perfectly.
For now, I am not offering any opinion as to what the foreground notification should look like, so I am merely logging the payload. But feel free to show it however you deem fit. |
27,322,408 | [JSFIDDLE demo](http://jsfiddle.net/rd61ao0f/1)
HTML
```
<div class="ratio-1439-330 bg-cover" style="background-image: url('https://www.agtinternational.com/wp-content/uploads/2013/11/City-solution.jpg');">
<div class="l-center" style="max-width: 1240px;">
<div class="square-logo bg-cover"
style="background-image:url('http://www.astronautamarcospontes4077.com.br/wp-content/uploads/2014/07/person-icon.png');">
</div>
<div class="header-cover" style="background-color: #373737; opacity: 0.9; position: absolute; bottom: 0; left:0; width: 100%; overflow: hidden; padding: 10px 0;">
<div class="l-center" style="max-width: 1240px">
<div class="nav nav-tabs" style="margin-left: 338px">
<a class="active" href="#overview" data-toggle="tab">
Overview
</a>
<a href="#visits" data-toggle="tab">
Visit
</a>
</div><!-- ./tab-lined-top-->
</div><!--tabs-->
</div><!--header cover-->
</div>
</div>
<div class="tab-content l-center" style="max-width: 1240px;">
<div id="overview" class="tab-pane active">
<div class="l-center" style="max-width: 1240px;background:red;">
TEST 1
</div>
</div><!--#overview-->
<div id="visits" class="tab-pane">
<div>
TeST 2
</div>
</div>
</div><!--tab-content-->
CSS
[class*="ratio"] {
position: relative; }
[class*="ratio"]:after {
content: '';
display: block; }
[class*="ratio"] .cly-ratio-content {
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0; }
.ratio-1439-330:after {
padding-top: 22.932592078%; }
.l-center{
margin: 0 auto;
}
.square-logo{
background: #fff;
position: absolute;
width: 180px;
height: 180px;
bottom: 25px;
left: 0;
margin-left: 115px;
z-index: 800;
opacity: 1;
}
.bg-cover{
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
.nav-tabs{
border-bottom: 0;
}
.nav{
margin-bottom: 0;
}
```
Currently it works on jsfiddle, but not on my local machine so you might not understand what I am asking.
Bootstrap is only there for tabs to be clickable. The logo move from left to right when browser is being resized and it looks jumpy while moving. Another issue is that the div with l-center and max-width seems not to be working well for tab pane content. Suspect that it is because of no height.
Is there any way around to force make logo stay vertically lined to tab content and tabs should move as well while browser is resizing?
Help appreciated! | 2014/12/05 | [
"https://Stackoverflow.com/questions/27322408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/524666/"
] | You are calling cellForRowAtIndexPath outside of a tableView reload. This will either give you a reused cell or a brand new instance but not the cell shown on the screen at the time.
What you should do is call `reloadRowsAtIndexPaths:withRowAnimation.`
Your code should have a dataSource that you update where you are currently trying to update the cell's bottomLabel.
Then your code should look something like this:
```
self.dataSource.megaBytesDownloaded = megaBytesDownloaded;
self.dataSource.totalDownloadEstimate = totalDownloadEstimate;
NSIndexPath *index = [self.fetchedResultsController indexPathForObject:MyObject];
[self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
```
And then in your `cellForRowAtIndexPath:` method, you can update your cell's bottomLabel at that point.
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Your normal setup code here
cell.bottomLabel.text = [NSString stringWithFormat:@"%.1f MB of %.1f MB", self.dataSource.megaBytesDownloaded, self.dataSource.totalDownloadEstimate];
}
```
Since it looks like you are also using AFNetworking to observe the download progress, you should also look into throwing your view update code on the main thread. AFNetworking uses multithreading in this case to prevent any jumps or lags in your UI. I would suggest using GCD to allow the main thread to handle updating your UI code.
It should look something like this:
```
dispatch_async(dispatch_get_main_queue(), ^{
//view update code here.
});
``` | I don't think accessing a cell the way you did is a good idea. I would suggest this
in your - (UITableViewCell \*)tableView:(UITableView \*)tableView cellForRowAtIndexPath:(NSIndexPath \*)indexPath have the following line
```
cell.bottomLabel.text = [NSString stringWithFormat:@"%.1f MB of %.1f MB", megaBytesDownloaded, totalDownloadEstimate];
```
and after NSIndexPath \*index = [self.fetchedResultsController indexPathForObject:MyObject]; add this line of code
```
[self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone;
```
**Hope This Helps** |
27,322,408 | [JSFIDDLE demo](http://jsfiddle.net/rd61ao0f/1)
HTML
```
<div class="ratio-1439-330 bg-cover" style="background-image: url('https://www.agtinternational.com/wp-content/uploads/2013/11/City-solution.jpg');">
<div class="l-center" style="max-width: 1240px;">
<div class="square-logo bg-cover"
style="background-image:url('http://www.astronautamarcospontes4077.com.br/wp-content/uploads/2014/07/person-icon.png');">
</div>
<div class="header-cover" style="background-color: #373737; opacity: 0.9; position: absolute; bottom: 0; left:0; width: 100%; overflow: hidden; padding: 10px 0;">
<div class="l-center" style="max-width: 1240px">
<div class="nav nav-tabs" style="margin-left: 338px">
<a class="active" href="#overview" data-toggle="tab">
Overview
</a>
<a href="#visits" data-toggle="tab">
Visit
</a>
</div><!-- ./tab-lined-top-->
</div><!--tabs-->
</div><!--header cover-->
</div>
</div>
<div class="tab-content l-center" style="max-width: 1240px;">
<div id="overview" class="tab-pane active">
<div class="l-center" style="max-width: 1240px;background:red;">
TEST 1
</div>
</div><!--#overview-->
<div id="visits" class="tab-pane">
<div>
TeST 2
</div>
</div>
</div><!--tab-content-->
CSS
[class*="ratio"] {
position: relative; }
[class*="ratio"]:after {
content: '';
display: block; }
[class*="ratio"] .cly-ratio-content {
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0; }
.ratio-1439-330:after {
padding-top: 22.932592078%; }
.l-center{
margin: 0 auto;
}
.square-logo{
background: #fff;
position: absolute;
width: 180px;
height: 180px;
bottom: 25px;
left: 0;
margin-left: 115px;
z-index: 800;
opacity: 1;
}
.bg-cover{
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
.nav-tabs{
border-bottom: 0;
}
.nav{
margin-bottom: 0;
}
```
Currently it works on jsfiddle, but not on my local machine so you might not understand what I am asking.
Bootstrap is only there for tabs to be clickable. The logo move from left to right when browser is being resized and it looks jumpy while moving. Another issue is that the div with l-center and max-width seems not to be working well for tab pane content. Suspect that it is because of no height.
Is there any way around to force make logo stay vertically lined to tab content and tabs should move as well while browser is resizing?
Help appreciated! | 2014/12/05 | [
"https://Stackoverflow.com/questions/27322408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/524666/"
] | You are calling cellForRowAtIndexPath outside of a tableView reload. This will either give you a reused cell or a brand new instance but not the cell shown on the screen at the time.
What you should do is call `reloadRowsAtIndexPaths:withRowAnimation.`
Your code should have a dataSource that you update where you are currently trying to update the cell's bottomLabel.
Then your code should look something like this:
```
self.dataSource.megaBytesDownloaded = megaBytesDownloaded;
self.dataSource.totalDownloadEstimate = totalDownloadEstimate;
NSIndexPath *index = [self.fetchedResultsController indexPathForObject:MyObject];
[self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
```
And then in your `cellForRowAtIndexPath:` method, you can update your cell's bottomLabel at that point.
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Your normal setup code here
cell.bottomLabel.text = [NSString stringWithFormat:@"%.1f MB of %.1f MB", self.dataSource.megaBytesDownloaded, self.dataSource.totalDownloadEstimate];
}
```
Since it looks like you are also using AFNetworking to observe the download progress, you should also look into throwing your view update code on the main thread. AFNetworking uses multithreading in this case to prevent any jumps or lags in your UI. I would suggest using GCD to allow the main thread to handle updating your UI code.
It should look something like this:
```
dispatch_async(dispatch_get_main_queue(), ^{
//view update code here.
});
``` | I would try using:
```
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
```
Instead directly assigning values to table cell. |
32,070,949 | I would like to prompt the user to give me input in my android application using a dialog.
When the user puts the figure it will go to another screen, but it does not give the user to input the value it does not waiting to the user its going to another activity directly.
What can i do to waiting the user to input the value he needs and after that it will take the user to the activity he needs. This is the code that i use.
```
else
{
{
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(Login.this);
View promptView = layoutInflater.inflate(R.layout.activity_input_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Login.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.editCodeSurvey);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String surveyCode = editText.getText().toString();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
//After Creating Dialog then we asking if the User that signed in is a manager
if(parseUser.getBoolean("isManager"))
{
//open manager Class
startActivity(new Intent(Login.this,ManagerScreen.class));
}
else{
//open Student Class to fill the survey
startActivity(new Intent(Login.this,StudentField.class));
}
``` | 2015/08/18 | [
"https://Stackoverflow.com/questions/32070949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4881731/"
] | You are using the default modifier,declare the fields as public then you'll be able to access it in such way:
```
user.name;
user.surname;
``` | You did'nt call of a right way the attributes in your method, you have to change `userObject.getUserName()` for `userObject.name.toString()`
The code will be like this:
---------------------------
```
public void readUsersSugarDB() {
// SUGAR DB TEST
try {
List<User> users = User.listAll(User.class);
for (int i = 0; i < users.size(); i++) {
User userObject = users.get(i);
Logger.i(userObject.name.toString());
Logger.i(userObject.toString());
}
//Integer userCount = User.getTableName(User.class);
Logger.i("Users list", users);
} catch (Exception e) {
Logger.e("Sugar_db_exception", e.getMessage());
}
}
``` |
9,537,636 | I have a site which has been redeveloped and the URLs are totally different. I've hundreds or 301 to do (the original URLs many were very long - I have no idea why) and I'm getting some funny results where some redirects are happening and others are redirecting, but to odd URLs. I was wondering if there is a specific order 301's need to go in. For example:
```
redirect 301 /News/Smart-Site-Waste-Management.aspx http://...
redirect 301 /News/tabid/96/tagid/68/damaged-doors.aspx http://...
redirect 301 /News/tabid/96/EntryId/91/Smart-Site-Waste-Management.aspx http://...
redirect 301 /News/tabid/96/EntryId/156/Plastic-Surgeon-hits-the-headlines.aspx http://...
redirect 301 /News/RepairoftheWeek/tabid/194/tagid/78/Gallery/RepairoftheWeek/tabid/194/EntryId/221/Scratched-laminate-floor-repair.aspx http://...
```
So my actual question is, should the "smaller" urls (the ones with less directory levels) be lower down this order and the more specific URLs be higher? My instinct tells me that if it's set as above, all those URLs will direct to the new link specified in the FIRST as they all start with "News/". This is what I am seeing in practice. | 2012/03/02 | [
"https://Stackoverflow.com/questions/9537636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1245615/"
] | You need to place the most specific at the top and the least specific at the bottom. Also, make sure you're halting processing using [L] after each redirect rule to make sure apache doesn't process additional rewrite rules after it has found a rule that matches.
Could you please post your .htaccess file? | Order is only important if there are multiple match lines (e.g. if you are also using `RedirectMatch` or the mod\_rewrite `RewriteEngine On` which can interact with redirect directives.
You will experience a performance hit parsing 100s of rule in an htaccess file, especially if the match rate is now small. If your current URIs do not start with /News, then a good trick is to move all of these redirects to `DOCROOT/News/.htaccess` as this will only be parsed for URIs /News/.... and hence out of any other URI path. |
4,773,208 | How any method of WCF application can return custom collection to calling environment.
please help with sample code.
thanks. | 2011/01/23 | [
"https://Stackoverflow.com/questions/4773208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508127/"
] | Give this a try
```
Update t
Set t.yyyy = q.Name
From TableToUpdate t
Join AddressTable q on q.Address = t.Address
```
This assumes that Address field (which you are joining on) is a one to one relationship with the Address field in the table you are updating
This can also be written
```
Update TableToUpdate
Set yyyy = q.Name
From AddressTable q
WHERE q.Address = TableToUpdate.Address
```
Since the update table is accessible in the FROM/WHERE clauses, except it cannot be aliased. | If you're using SQL Server 2005 or up (which you didn't specify ....), you can use a Common Table Expression (CTE):
```
;WITH UpdateData AS
(
SELECT
FullName,
Address
FROM
dbo.SomeTableYouUse
WHERE
(some critiera)
)
UPDATE dbo.yyy
SET fullname = ud.FullName
FROM UpdateData ud
WHERE address = ud.Address
```
Inside your CTE, you can figure out how to determine your `FullName` and `Address`, and the CTE is sort of an "inline" view which is valid for the next statement only - in this case, for the `UPDATE` statement. |
52,626,696 | Is it safe to use 'com.apple.system.config.network\_change' notification to detect network reachability changes? Or is it considered to be a private API? For now my code looks like this:
```
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
nil,
callback,
"com.apple.system.config.network_change" as CFString,
nil,
.deliverImmediately);
```
And then in callback I respond to the notification.
The problem is Reachability in iOS not always detects Wi-Fi switching. For instance, if we are switching from one Wi-Fi AP to the other that system already knows (because we have used it in the past) then it happens so fast that there's no 'Disconnected' event and I cannot track the actual switching moment. Solution above works but I am sure whether my app won't be rejected for publishing in the App Store.
Thanks! | 2018/10/03 | [
"https://Stackoverflow.com/questions/52626696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10363555/"
] | Write your listener code inside `onCreate` or other function & call from `onCreate`.
Like this :
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize the button
Button btn = (Button) findViewById(R.id.button);
// set the button action
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goToSecondPage();
}
});
}
``` | `Button` initialize and set `OnClickListener` should be in `onCreate` method.
Like this:
```
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)
//initialize the button
Button btn = (Button) findViewById(R.id.button);
// set the button action
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
goToSecondPage();
}
});
}
}
``` |
52,626,696 | Is it safe to use 'com.apple.system.config.network\_change' notification to detect network reachability changes? Or is it considered to be a private API? For now my code looks like this:
```
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
nil,
callback,
"com.apple.system.config.network_change" as CFString,
nil,
.deliverImmediately);
```
And then in callback I respond to the notification.
The problem is Reachability in iOS not always detects Wi-Fi switching. For instance, if we are switching from one Wi-Fi AP to the other that system already knows (because we have used it in the past) then it happens so fast that there's no 'Disconnected' event and I cannot track the actual switching moment. Solution above works but I am sure whether my app won't be rejected for publishing in the App Store.
Thanks! | 2018/10/03 | [
"https://Stackoverflow.com/questions/52626696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10363555/"
] | Write your listener code inside `onCreate` or other function & call from `onCreate`.
Like this :
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize the button
Button btn = (Button) findViewById(R.id.button);
// set the button action
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goToSecondPage();
}
});
}
``` | Try this code in java..
```
public class MainActivity2 extends AppCompatActivity implements View.OnClickListener {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* this method initialized all view controls.
*/
private void init() {
btn = findViewById(R.id.button);
}
/**
* this method define all view controls listener.
*/
private void setListener() {
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button:
goToSecondPage();
break;
}
}
```
} |
52,626,696 | Is it safe to use 'com.apple.system.config.network\_change' notification to detect network reachability changes? Or is it considered to be a private API? For now my code looks like this:
```
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
nil,
callback,
"com.apple.system.config.network_change" as CFString,
nil,
.deliverImmediately);
```
And then in callback I respond to the notification.
The problem is Reachability in iOS not always detects Wi-Fi switching. For instance, if we are switching from one Wi-Fi AP to the other that system already knows (because we have used it in the past) then it happens so fast that there's no 'Disconnected' event and I cannot track the actual switching moment. Solution above works but I am sure whether my app won't be rejected for publishing in the App Store.
Thanks! | 2018/10/03 | [
"https://Stackoverflow.com/questions/52626696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10363555/"
] | Write your listener code inside `onCreate` or other function & call from `onCreate`.
Like this :
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize the button
Button btn = (Button) findViewById(R.id.button);
// set the button action
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goToSecondPage();
}
});
}
``` | Try this `onCreate` method:
```
//initialize the button
Button btn = (Button) findViewById(R.id.button);
// set the button action
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goToSecondPage();
}
})
``` |
52,626,696 | Is it safe to use 'com.apple.system.config.network\_change' notification to detect network reachability changes? Or is it considered to be a private API? For now my code looks like this:
```
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
nil,
callback,
"com.apple.system.config.network_change" as CFString,
nil,
.deliverImmediately);
```
And then in callback I respond to the notification.
The problem is Reachability in iOS not always detects Wi-Fi switching. For instance, if we are switching from one Wi-Fi AP to the other that system already knows (because we have used it in the past) then it happens so fast that there's no 'Disconnected' event and I cannot track the actual switching moment. Solution above works but I am sure whether my app won't be rejected for publishing in the App Store.
Thanks! | 2018/10/03 | [
"https://Stackoverflow.com/questions/52626696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10363555/"
] | `Button` initialize and set `OnClickListener` should be in `onCreate` method.
Like this:
```
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)
//initialize the button
Button btn = (Button) findViewById(R.id.button);
// set the button action
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
goToSecondPage();
}
});
}
}
``` | Try this code in java..
```
public class MainActivity2 extends AppCompatActivity implements View.OnClickListener {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* this method initialized all view controls.
*/
private void init() {
btn = findViewById(R.id.button);
}
/**
* this method define all view controls listener.
*/
private void setListener() {
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button:
goToSecondPage();
break;
}
}
```
} |
52,626,696 | Is it safe to use 'com.apple.system.config.network\_change' notification to detect network reachability changes? Or is it considered to be a private API? For now my code looks like this:
```
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
nil,
callback,
"com.apple.system.config.network_change" as CFString,
nil,
.deliverImmediately);
```
And then in callback I respond to the notification.
The problem is Reachability in iOS not always detects Wi-Fi switching. For instance, if we are switching from one Wi-Fi AP to the other that system already knows (because we have used it in the past) then it happens so fast that there's no 'Disconnected' event and I cannot track the actual switching moment. Solution above works but I am sure whether my app won't be rejected for publishing in the App Store.
Thanks! | 2018/10/03 | [
"https://Stackoverflow.com/questions/52626696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10363555/"
] | `Button` initialize and set `OnClickListener` should be in `onCreate` method.
Like this:
```
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)
//initialize the button
Button btn = (Button) findViewById(R.id.button);
// set the button action
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
goToSecondPage();
}
});
}
}
``` | Try this `onCreate` method:
```
//initialize the button
Button btn = (Button) findViewById(R.id.button);
// set the button action
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goToSecondPage();
}
})
``` |
52,626,696 | Is it safe to use 'com.apple.system.config.network\_change' notification to detect network reachability changes? Or is it considered to be a private API? For now my code looks like this:
```
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
nil,
callback,
"com.apple.system.config.network_change" as CFString,
nil,
.deliverImmediately);
```
And then in callback I respond to the notification.
The problem is Reachability in iOS not always detects Wi-Fi switching. For instance, if we are switching from one Wi-Fi AP to the other that system already knows (because we have used it in the past) then it happens so fast that there's no 'Disconnected' event and I cannot track the actual switching moment. Solution above works but I am sure whether my app won't be rejected for publishing in the App Store.
Thanks! | 2018/10/03 | [
"https://Stackoverflow.com/questions/52626696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10363555/"
] | Try this code in java..
```
public class MainActivity2 extends AppCompatActivity implements View.OnClickListener {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* this method initialized all view controls.
*/
private void init() {
btn = findViewById(R.id.button);
}
/**
* this method define all view controls listener.
*/
private void setListener() {
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button:
goToSecondPage();
break;
}
}
```
} | Try this `onCreate` method:
```
//initialize the button
Button btn = (Button) findViewById(R.id.button);
// set the button action
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goToSecondPage();
}
})
``` |
25,855,308 | I need to take a long (max resolution) image and wrap it into a circle. So imagine bending a steel bar so that it is now circular with each end touching.

I have been banging my head against threejs for the last 8 hours and have so far managed to apply the image as a texture on a circle geometry, but can't figure out how to apply the texture to a long mesh and then warp that mesh appropriately. The warping doesn't need to be (and shouldn't be) animated. What we basically have is a 360 panoramic image that we need to "flatten" into a top-down view.
In lieu of sharing my code (as it's not significantly different), I've so far been playing around with this tutorial:
<http://www.johannes-raida.de/tutorials/three.js/tutorial06/tutorial06.htm>
And I do (I think) understand the broad strokes at this point.
Other things I've tried is to use just canvas to slice the image up into strips and warp each strip... this was horribly slow and I couldn't get that to work properly either!
Any help/suggestions? | 2014/09/15 | [
"https://Stackoverflow.com/questions/25855308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031830/"
] | I had the same issue with Luna. I installed Java 1.7.0\_80, which then allowed me to change to the C/C++ Perspective and create new C/C++ projects.
My system previously only had Java 1.6.0\_45, which was sufficient to run Luna but apparently insufficient to run CDT in its entirety. | Your JDK version is below 1.6 which is too old. You should upgrade it to 1.7 or higher. |
25,855,308 | I need to take a long (max resolution) image and wrap it into a circle. So imagine bending a steel bar so that it is now circular with each end touching.

I have been banging my head against threejs for the last 8 hours and have so far managed to apply the image as a texture on a circle geometry, but can't figure out how to apply the texture to a long mesh and then warp that mesh appropriately. The warping doesn't need to be (and shouldn't be) animated. What we basically have is a 360 panoramic image that we need to "flatten" into a top-down view.
In lieu of sharing my code (as it's not significantly different), I've so far been playing around with this tutorial:
<http://www.johannes-raida.de/tutorials/three.js/tutorial06/tutorial06.htm>
And I do (I think) understand the broad strokes at this point.
Other things I've tried is to use just canvas to slice the image up into strips and warp each strip... this was horribly slow and I couldn't get that to work properly either!
Any help/suggestions? | 2014/09/15 | [
"https://Stackoverflow.com/questions/25855308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031830/"
] | I had the same issue with Luna. I installed Java 1.7.0\_80, which then allowed me to change to the C/C++ Perspective and create new C/C++ projects.
My system previously only had Java 1.6.0\_45, which was sufficient to run Luna but apparently insufficient to run CDT in its entirety. | I had the same problem - installing java 8 helped. |
25,855,308 | I need to take a long (max resolution) image and wrap it into a circle. So imagine bending a steel bar so that it is now circular with each end touching.

I have been banging my head against threejs for the last 8 hours and have so far managed to apply the image as a texture on a circle geometry, but can't figure out how to apply the texture to a long mesh and then warp that mesh appropriately. The warping doesn't need to be (and shouldn't be) animated. What we basically have is a 360 panoramic image that we need to "flatten" into a top-down view.
In lieu of sharing my code (as it's not significantly different), I've so far been playing around with this tutorial:
<http://www.johannes-raida.de/tutorials/three.js/tutorial06/tutorial06.htm>
And I do (I think) understand the broad strokes at this point.
Other things I've tried is to use just canvas to slice the image up into strips and warp each strip... this was horribly slow and I couldn't get that to work properly either!
Any help/suggestions? | 2014/09/15 | [
"https://Stackoverflow.com/questions/25855308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031830/"
] | I had the same issue with Luna. I installed Java 1.7.0\_80, which then allowed me to change to the C/C++ Perspective and create new C/C++ projects.
My system previously only had Java 1.6.0\_45, which was sufficient to run Luna but apparently insufficient to run CDT in its entirety. | I had exactly the same problem, using Luna SR 1a on Ubuntu 12.04 LTS.
Switching from Java 1.6.0\_34 to 1.7.0\_75 fixed the issue - everything works now |
21,509,619 | I need to place two EditText side by side, the left one can be multiline, but the right one has to be just one line. I've used a table layout with just one row but I have the following problem, the second column should have just the enough room to show the one single line text but not more. How can I achive that? Thank you very much
```
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<TableRow
android:background="#87F1FF"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:maxLines="3"
android:text="this can take more than a line"
android:textColor="@android:color/black"
android:textSize="40sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#454545"
android:maxLines="1"
android:text="May 25 - 10:00 pm"
android:textColor="@android:color/black"
android:textSize="20sp" />
</TableRow>
</TableLayout>
```
 | 2014/02/02 | [
"https://Stackoverflow.com/questions/21509619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1331539/"
] | Make second TextView without `android:layout_weight="1"` | ***Just change in your 2nd TextView:***
```
android:layout_width="0dp"
```
>
> Instead of
>
>
>
```
android:layout_width="wrap_content"
``` |
59,576,738 | I am working on a Ecommerce Site which needs API's for its mobile application. Seeing the implementation issues at first of GraphQL made me think of integrating **GraphQL** for querying data and **REST** for the mutation operations (store, update, delete).
Is it ok to do these things or should I just stick with any one of them for complete operations? | 2020/01/03 | [
"https://Stackoverflow.com/questions/59576738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3871887/"
] | There's plenty of individual cases where it's more appropriate or even necessary to have separate endpoints. To name a few: authentication, file uploads, third-party webhooks, or any requests that should return something other than JSON.
Saying that all operations with side-effects should be done through separate endpoints seems like overkill. You'll not only lose the typical benefits associated with GraphQL (declarative data fetching, predictable responses, etc.) but you'll also be making things harder for front end developers, particularly if using Apollo. That's because cached query responses can be *automatically* updated based on the data returned in a mutation -- if you don't use GraphQL to mutate that data, though, you'll have to manually update the cache yourself. | I would recommend to stick with a single approach because of the following reasons
1) predictive changes to cached data after the operation otherwise you would have to write lot of duct tape code to ensure that the `REST` based updates mutates the cached data on the client.
2) Single pattern for code maintenance and less overhead while reading code.
3) To have a `schema` at a single place otherwise you might be duplicating code. |
60,361,470 | I am new to phaser and game development.
I followed the below tutorial.
<https://medium.com/@michaelwesthadley/modular-game-worlds-in-phaser-3-tilemaps-1-958fc7e6bbd6>
I downloaded and Tiled software and made a simple map with a tileset I got from OpenGameArt.org. Unfortunately, nothing gets loaded on the browser screen, I just see a black rectangle instead of the map. I find no errors in the console. I am running this using XAMPP in Windows 10.
I will paste all my code here, let me know if you find anything wrong.
```
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/phaser@3.15.1/dist/phaser-arcade-physics.min.js">
</script>
</head>
<body>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
```
The is the index.js file
```
const config = {
type: Phaser.AUTO, // Which renderer to use
width: 100, // Canvas width in pixels
height: 100, // Canvas height in pixels
parent: "game-container", // ID of the DOM element to add the canvas to
scene: {
preload: preload,
create: create,
update: update
}
};
const game = new Phaser.Game(config);
function preload() {
// Runs once, loads up assets like images and audio
this.load.image("tiles", "assets/tilesets/GoldBricks.png");
this.load.tilemapTiledJSON("map", "assets/tilemaps/mario.json");
}
function create() {
// Runs once, after all assets in preload are loaded
const map = this.make.tilemap({ key: "map" });
const tileset = map.addTilesetImage("GoldBricks", "tiles");
// Parameters: layer name (or index) from Tiled, tileset, x, y
const belowLayer = map.createStaticLayer("Tile Layer 1", tileset, 0, 0);
}
function update(time, delta) {
// Runs once per frame for the duration of the scene
}
```
EDIT: Below is the json file
```
{ "compressionlevel":-1,
"height":100,
"infinite":false,
"layers":[
{
"compression":"",
"data":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABUAAAAWAAAAFwAAABgAAAAZAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAVAAAAFgAAABcAAAAYAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAkQAAAJIAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAAA==",
"encoding":"base64",
"height":100,
"id":1,
"name":"Tile Layer 1",
"opacity":1,
"type":"tilelayer",
"visible":true,
"width":100,
"x":0,
"y":0
}],
"nextlayerid":2,
"nextobjectid":1,
"orientation":"orthogonal",
"renderorder":"right-down",
"tiledversion":"1.3.2",
"tileheight":32,
"tilesets":[
{
"columns":16,
"firstgid":1,
"image":"..\/..\/..\/..\/..\/Users\/Shashank A C\/Downloads\/Goldbricksandgrass\/GoldBricks.png",
"imageheight":512,
"imagewidth":512,
"margin":0,
"name":"GoldBricks",
"spacing":0,
"tilecount":256,
"tileheight":32,
"tilewidth":32
}],
"tilewidth":32,
"type":"map",
"version":1.2,
"width":100
}
```
I am also seeing and error in the console now.
```
Uncaught TypeError: Cannot read property '0' of undefined
at StaticTilemapLayer.upload (phaser.js:74806)
at StaticTilemapLayerWebGLRenderer [as renderWebGL] (phaser.js:122959)
at WebGLRenderer.render (phaser.js:65133)
at CameraManager.render (phaser.js:114533)
at Systems.render (phaser.js:27184)
at SceneManager.render (phaser.js:46818)
at Game.step (phaser.js:109346)
at TimeStep.step (phaser.js:106091)
at step (phaser.js:66488)
``` | 2020/02/23 | [
"https://Stackoverflow.com/questions/60361470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9066431/"
] | UPDATE: Check this file structure --
<https://next.plnkr.co/edit/OqywHzLC80aZMGeF>
======
Need to see the JSON file to completely understand the issue, but I will just try to speculate. Make sure your JSON file has below settings correctly:
```
"tilesets":[
{
"image":"path/to/GoldBricks.png",
"name":"GoldBricks"
...
}
]
```
In some cases Tiled includes wrong/different path to the image file, so make sure to check that part. If there is no image path, embed it in Tiled.
In addition, the `name` value should match the first parameter of `map.addTilesetImage()`. Hope it helps! | I had a similar problem myself, the solution was going back to Tiled software and check: 'Embed tileset' on each tileset of the map. |
60,361,470 | I am new to phaser and game development.
I followed the below tutorial.
<https://medium.com/@michaelwesthadley/modular-game-worlds-in-phaser-3-tilemaps-1-958fc7e6bbd6>
I downloaded and Tiled software and made a simple map with a tileset I got from OpenGameArt.org. Unfortunately, nothing gets loaded on the browser screen, I just see a black rectangle instead of the map. I find no errors in the console. I am running this using XAMPP in Windows 10.
I will paste all my code here, let me know if you find anything wrong.
```
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/phaser@3.15.1/dist/phaser-arcade-physics.min.js">
</script>
</head>
<body>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
```
The is the index.js file
```
const config = {
type: Phaser.AUTO, // Which renderer to use
width: 100, // Canvas width in pixels
height: 100, // Canvas height in pixels
parent: "game-container", // ID of the DOM element to add the canvas to
scene: {
preload: preload,
create: create,
update: update
}
};
const game = new Phaser.Game(config);
function preload() {
// Runs once, loads up assets like images and audio
this.load.image("tiles", "assets/tilesets/GoldBricks.png");
this.load.tilemapTiledJSON("map", "assets/tilemaps/mario.json");
}
function create() {
// Runs once, after all assets in preload are loaded
const map = this.make.tilemap({ key: "map" });
const tileset = map.addTilesetImage("GoldBricks", "tiles");
// Parameters: layer name (or index) from Tiled, tileset, x, y
const belowLayer = map.createStaticLayer("Tile Layer 1", tileset, 0, 0);
}
function update(time, delta) {
// Runs once per frame for the duration of the scene
}
```
EDIT: Below is the json file
```
{ "compressionlevel":-1,
"height":100,
"infinite":false,
"layers":[
{
"compression":"",
"data":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABUAAAAWAAAAFwAAABgAAAAZAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAVAAAAFgAAABcAAAAYAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAkQAAAJIAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAAA==",
"encoding":"base64",
"height":100,
"id":1,
"name":"Tile Layer 1",
"opacity":1,
"type":"tilelayer",
"visible":true,
"width":100,
"x":0,
"y":0
}],
"nextlayerid":2,
"nextobjectid":1,
"orientation":"orthogonal",
"renderorder":"right-down",
"tiledversion":"1.3.2",
"tileheight":32,
"tilesets":[
{
"columns":16,
"firstgid":1,
"image":"..\/..\/..\/..\/..\/Users\/Shashank A C\/Downloads\/Goldbricksandgrass\/GoldBricks.png",
"imageheight":512,
"imagewidth":512,
"margin":0,
"name":"GoldBricks",
"spacing":0,
"tilecount":256,
"tileheight":32,
"tilewidth":32
}],
"tilewidth":32,
"type":"map",
"version":1.2,
"width":100
}
```
I am also seeing and error in the console now.
```
Uncaught TypeError: Cannot read property '0' of undefined
at StaticTilemapLayer.upload (phaser.js:74806)
at StaticTilemapLayerWebGLRenderer [as renderWebGL] (phaser.js:122959)
at WebGLRenderer.render (phaser.js:65133)
at CameraManager.render (phaser.js:114533)
at Systems.render (phaser.js:27184)
at SceneManager.render (phaser.js:46818)
at Game.step (phaser.js:109346)
at TimeStep.step (phaser.js:106091)
at step (phaser.js:66488)
``` | 2020/02/23 | [
"https://Stackoverflow.com/questions/60361470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9066431/"
] | UPDATE: Check this file structure --
<https://next.plnkr.co/edit/OqywHzLC80aZMGeF>
======
Need to see the JSON file to completely understand the issue, but I will just try to speculate. Make sure your JSON file has below settings correctly:
```
"tilesets":[
{
"image":"path/to/GoldBricks.png",
"name":"GoldBricks"
...
}
]
```
In some cases Tiled includes wrong/different path to the image file, so make sure to check that part. If there is no image path, embed it in Tiled.
In addition, the `name` value should match the first parameter of `map.addTilesetImage()`. Hope it helps! | Alright, I asked in the phaser community forum itself and got some help.
The tilemap layer is taller than the game canvas so the visible tiles are out of sight. The solution is to add the below code in the `create` function.
```
this.cameras.main.centerOn(800, 1300);
``` |
60,361,470 | I am new to phaser and game development.
I followed the below tutorial.
<https://medium.com/@michaelwesthadley/modular-game-worlds-in-phaser-3-tilemaps-1-958fc7e6bbd6>
I downloaded and Tiled software and made a simple map with a tileset I got from OpenGameArt.org. Unfortunately, nothing gets loaded on the browser screen, I just see a black rectangle instead of the map. I find no errors in the console. I am running this using XAMPP in Windows 10.
I will paste all my code here, let me know if you find anything wrong.
```
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/phaser@3.15.1/dist/phaser-arcade-physics.min.js">
</script>
</head>
<body>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
```
The is the index.js file
```
const config = {
type: Phaser.AUTO, // Which renderer to use
width: 100, // Canvas width in pixels
height: 100, // Canvas height in pixels
parent: "game-container", // ID of the DOM element to add the canvas to
scene: {
preload: preload,
create: create,
update: update
}
};
const game = new Phaser.Game(config);
function preload() {
// Runs once, loads up assets like images and audio
this.load.image("tiles", "assets/tilesets/GoldBricks.png");
this.load.tilemapTiledJSON("map", "assets/tilemaps/mario.json");
}
function create() {
// Runs once, after all assets in preload are loaded
const map = this.make.tilemap({ key: "map" });
const tileset = map.addTilesetImage("GoldBricks", "tiles");
// Parameters: layer name (or index) from Tiled, tileset, x, y
const belowLayer = map.createStaticLayer("Tile Layer 1", tileset, 0, 0);
}
function update(time, delta) {
// Runs once per frame for the duration of the scene
}
```
EDIT: Below is the json file
```
{ "compressionlevel":-1,
"height":100,
"infinite":false,
"layers":[
{
"compression":"",
"data":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABUAAAAWAAAAFwAAABgAAAAZAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAVAAAAFgAAABcAAAAYAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAkQAAAJIAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAANgAAADYAAAA2AAAAA==",
"encoding":"base64",
"height":100,
"id":1,
"name":"Tile Layer 1",
"opacity":1,
"type":"tilelayer",
"visible":true,
"width":100,
"x":0,
"y":0
}],
"nextlayerid":2,
"nextobjectid":1,
"orientation":"orthogonal",
"renderorder":"right-down",
"tiledversion":"1.3.2",
"tileheight":32,
"tilesets":[
{
"columns":16,
"firstgid":1,
"image":"..\/..\/..\/..\/..\/Users\/Shashank A C\/Downloads\/Goldbricksandgrass\/GoldBricks.png",
"imageheight":512,
"imagewidth":512,
"margin":0,
"name":"GoldBricks",
"spacing":0,
"tilecount":256,
"tileheight":32,
"tilewidth":32
}],
"tilewidth":32,
"type":"map",
"version":1.2,
"width":100
}
```
I am also seeing and error in the console now.
```
Uncaught TypeError: Cannot read property '0' of undefined
at StaticTilemapLayer.upload (phaser.js:74806)
at StaticTilemapLayerWebGLRenderer [as renderWebGL] (phaser.js:122959)
at WebGLRenderer.render (phaser.js:65133)
at CameraManager.render (phaser.js:114533)
at Systems.render (phaser.js:27184)
at SceneManager.render (phaser.js:46818)
at Game.step (phaser.js:109346)
at TimeStep.step (phaser.js:106091)
at step (phaser.js:66488)
``` | 2020/02/23 | [
"https://Stackoverflow.com/questions/60361470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9066431/"
] | Alright, I asked in the phaser community forum itself and got some help.
The tilemap layer is taller than the game canvas so the visible tiles are out of sight. The solution is to add the below code in the `create` function.
```
this.cameras.main.centerOn(800, 1300);
``` | I had a similar problem myself, the solution was going back to Tiled software and check: 'Embed tileset' on each tileset of the map. |
12,384,188 | In rails, if I want to override an attribute method, eg. a setter, or getter etc, I might need the instance method to be defined.
However, activerecord does not define attribute methods until an instance is first synchronized.
This can be seen in:
```
class MyModel < ActiveRecord::Base
end
MyModel.attribute_methods_generated? # => false
MyModel.instance_method(:a_db_column)
# => NameError Exception: undefined method `a_db_column' for class `MyModel'
MyModel.new # implicitly calls define_attribute_methods
# MyModel.define_attribute_methods # can also use this instead of MyModel.new
MyModel.attribute_methods_generated? # => true
MyModel.instance_method(:a_db_column)
#<UnboundMethod: MyModel(#<Module:0x000000030a20a0>)#__temp__>
```
Is there any problem that could occur in calling `define_attribute_methods` early? Even doing something like:
```
class MyModel < ActiveRecord::Base
define_attribute_methods
# is there any code here which might cause problems?
end
``` | 2012/09/12 | [
"https://Stackoverflow.com/questions/12384188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1578925/"
] | <https://github.com/claudemamo/file-attach-cordova-upload-jqm> use this | This JavaScript function, confirms that the user has selected a file to upload. If the user has not selected a file, then the function displays an error message.
```
<script type="text/javascript">
function checkForFile() {
if (document.getElementById('file').value) {
return true;
}
document.getElementById('errMsg').style.display = '';
return false;
}
</script>
<form action="URL?nexturl=http%3A%2F%2Fwww.example.com" method="post"
enctype="multipart/form-data" onsubmit="return checkForFile();">
<input id="file" type="file" name="file"/>
<div id="errMsg" style="display:none;color:red">
You need to specify a file.
</div>
<input type="hidden" name="token" value="TOKEN"/>
<input type="submit" value="go" />
</form>
``` |
41,592,833 | I have this input:
`<input type="checkbox" ng-model="area.id" data-id="{{area.id}}"/>`
and some `ng-click` action above, I'm trying to collect all selected checkboxes id's but after check action `data-id` attribute turns to `true/false`, why?
Function from controller:
```
collectSelectedAreas($event) {
let selectedArea = $event.currentTarget.querySelectorAll('input:checked');
let areaIds = [];
[selectedArea].forEach((el) => {
console.log(el.attributes['data-id'].value);
});
}
``` | 2017/01/11 | [
"https://Stackoverflow.com/questions/41592833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029486/"
] | Use `float: left;` for the `p` inside `.inline-block`:
```css
.inline-block {
display: inline-block;
width: 100%;
}
.inline-block p{
float: left;
}
```
```html
<link href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div data-role="collapsible">
<h3> Alarm </h3>
<div class="inline-block">
<p>Alarm Horn:</p>
<select name="flipswitch-1" id="flipswitch-1" data-role="flipswitch" data-wrapper-class="wide-flipswitch">
<option value="off">OFF</option>
<option value="on">ON</option>
</select>
</div>
<div class="inline-block">
<p>Alarm Light:</p>
<select name="flipswitch-2" id="flipswitch-2" data-role="flipswitch" data-wrapper-class="wide-flipswitch">
<option value="off">OFF</option>
<option value="on">ON</option>
</select>
</div>
</div>
<div data-role="collapsible">
<h3> Fault </h3>
<div class="inline-block">
<label for="number-input-1">Start Fault Time:</label>
<button id="number-input-1" class="keyboard-input" data-inline="true">100</button>
<label for="number-input-1">seconds</label>
</div>
</div>
``` | Just add this code to your CSS
```
.inline-block > p {
float: left;
}
``` |
41,592,833 | I have this input:
`<input type="checkbox" ng-model="area.id" data-id="{{area.id}}"/>`
and some `ng-click` action above, I'm trying to collect all selected checkboxes id's but after check action `data-id` attribute turns to `true/false`, why?
Function from controller:
```
collectSelectedAreas($event) {
let selectedArea = $event.currentTarget.querySelectorAll('input:checked');
let areaIds = [];
[selectedArea].forEach((el) => {
console.log(el.attributes['data-id'].value);
});
}
``` | 2017/01/11 | [
"https://Stackoverflow.com/questions/41592833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029486/"
] | Just add this code to your CSS
```
.inline-block > p {
float: left;
}
``` | Just modify your css with this
```css
.inline-block {
display: inline-block;
}
p{
display:inline-block;
}
select{
display:inline-block;
}
```
```html
<link href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div data-role="collapsible">
<h3> Alarm </h3>
<div class="inline-block">
<p>Alarm Horn:</p>
<select name="flipswitch-1" id="flipswitch-1" data-role="flipswitch" data-wrapper-class="wide-flipswitch">
<option value="off">OFF</option>
<option value="on">ON</option>
</select>
</div>
<div class="inline-block">
<p>Alarm Light:</p>
<select name="flipswitch-2" id="flipswitch-2" data-role="flipswitch" data- wrapper-class="wide-flipswitch">
<option value="off">OFF</option>
<option value="on">ON</option>
</select>
</div>
</div>
<div data-role="collapsible">
<h3> Fault </h3>
<div class="inline-block">
<label for="number-input-1">Start Fault Time:</label>
<button id="number-input-1" class="keyboard-input" data- inline="true">100</button>
<label for="number-input-1">seconds</label>
</div>
</div>
``` |
41,592,833 | I have this input:
`<input type="checkbox" ng-model="area.id" data-id="{{area.id}}"/>`
and some `ng-click` action above, I'm trying to collect all selected checkboxes id's but after check action `data-id` attribute turns to `true/false`, why?
Function from controller:
```
collectSelectedAreas($event) {
let selectedArea = $event.currentTarget.querySelectorAll('input:checked');
let areaIds = [];
[selectedArea].forEach((el) => {
console.log(el.attributes['data-id'].value);
});
}
``` | 2017/01/11 | [
"https://Stackoverflow.com/questions/41592833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029486/"
] | Just add this code to your CSS
```
.inline-block > p {
float: left;
}
``` | You can specify your CSS as :
```
.inline-block { /* select the class */
display: inline-block;
}
.inline-block *{ /* select all the child element */
display: inline-block;
}
```
Adding any element to your class will be aligned in a single line. |
41,592,833 | I have this input:
`<input type="checkbox" ng-model="area.id" data-id="{{area.id}}"/>`
and some `ng-click` action above, I'm trying to collect all selected checkboxes id's but after check action `data-id` attribute turns to `true/false`, why?
Function from controller:
```
collectSelectedAreas($event) {
let selectedArea = $event.currentTarget.querySelectorAll('input:checked');
let areaIds = [];
[selectedArea].forEach((el) => {
console.log(el.attributes['data-id'].value);
});
}
``` | 2017/01/11 | [
"https://Stackoverflow.com/questions/41592833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029486/"
] | Use `float: left;` for the `p` inside `.inline-block`:
```css
.inline-block {
display: inline-block;
width: 100%;
}
.inline-block p{
float: left;
}
```
```html
<link href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div data-role="collapsible">
<h3> Alarm </h3>
<div class="inline-block">
<p>Alarm Horn:</p>
<select name="flipswitch-1" id="flipswitch-1" data-role="flipswitch" data-wrapper-class="wide-flipswitch">
<option value="off">OFF</option>
<option value="on">ON</option>
</select>
</div>
<div class="inline-block">
<p>Alarm Light:</p>
<select name="flipswitch-2" id="flipswitch-2" data-role="flipswitch" data-wrapper-class="wide-flipswitch">
<option value="off">OFF</option>
<option value="on">ON</option>
</select>
</div>
</div>
<div data-role="collapsible">
<h3> Fault </h3>
<div class="inline-block">
<label for="number-input-1">Start Fault Time:</label>
<button id="number-input-1" class="keyboard-input" data-inline="true">100</button>
<label for="number-input-1">seconds</label>
</div>
</div>
``` | Just modify your css with this
```css
.inline-block {
display: inline-block;
}
p{
display:inline-block;
}
select{
display:inline-block;
}
```
```html
<link href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div data-role="collapsible">
<h3> Alarm </h3>
<div class="inline-block">
<p>Alarm Horn:</p>
<select name="flipswitch-1" id="flipswitch-1" data-role="flipswitch" data-wrapper-class="wide-flipswitch">
<option value="off">OFF</option>
<option value="on">ON</option>
</select>
</div>
<div class="inline-block">
<p>Alarm Light:</p>
<select name="flipswitch-2" id="flipswitch-2" data-role="flipswitch" data- wrapper-class="wide-flipswitch">
<option value="off">OFF</option>
<option value="on">ON</option>
</select>
</div>
</div>
<div data-role="collapsible">
<h3> Fault </h3>
<div class="inline-block">
<label for="number-input-1">Start Fault Time:</label>
<button id="number-input-1" class="keyboard-input" data- inline="true">100</button>
<label for="number-input-1">seconds</label>
</div>
</div>
``` |
41,592,833 | I have this input:
`<input type="checkbox" ng-model="area.id" data-id="{{area.id}}"/>`
and some `ng-click` action above, I'm trying to collect all selected checkboxes id's but after check action `data-id` attribute turns to `true/false`, why?
Function from controller:
```
collectSelectedAreas($event) {
let selectedArea = $event.currentTarget.querySelectorAll('input:checked');
let areaIds = [];
[selectedArea].forEach((el) => {
console.log(el.attributes['data-id'].value);
});
}
``` | 2017/01/11 | [
"https://Stackoverflow.com/questions/41592833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029486/"
] | Use `float: left;` for the `p` inside `.inline-block`:
```css
.inline-block {
display: inline-block;
width: 100%;
}
.inline-block p{
float: left;
}
```
```html
<link href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div data-role="collapsible">
<h3> Alarm </h3>
<div class="inline-block">
<p>Alarm Horn:</p>
<select name="flipswitch-1" id="flipswitch-1" data-role="flipswitch" data-wrapper-class="wide-flipswitch">
<option value="off">OFF</option>
<option value="on">ON</option>
</select>
</div>
<div class="inline-block">
<p>Alarm Light:</p>
<select name="flipswitch-2" id="flipswitch-2" data-role="flipswitch" data-wrapper-class="wide-flipswitch">
<option value="off">OFF</option>
<option value="on">ON</option>
</select>
</div>
</div>
<div data-role="collapsible">
<h3> Fault </h3>
<div class="inline-block">
<label for="number-input-1">Start Fault Time:</label>
<button id="number-input-1" class="keyboard-input" data-inline="true">100</button>
<label for="number-input-1">seconds</label>
</div>
</div>
``` | You can specify your CSS as :
```
.inline-block { /* select the class */
display: inline-block;
}
.inline-block *{ /* select all the child element */
display: inline-block;
}
```
Adding any element to your class will be aligned in a single line. |
30,936,170 | I'm having trouble getting Angular, CORS, SpringSecurity and Basic Authentication to play nicely. I have the following Angular Ajax call where I'm trying to set the header to include a Basic Authorization header in the request.
```
var headerObj = {headers: {'Authorization': 'Basic am9lOnNlY3JldA=='}};
return $http.get('http://localhost:8080/mysite/login', headerObj).then(function (response) {
return response.data;
});
```
I am running my angular app on localhost:8888 and my backend server on localhost:8080. So I had to add a CORS filter to my server side which is Spring MVC. So I created a filter and added it to my web.xml.
web.xml
```
<filter>
<filter-name>corsFilter</filter-name>
<filter-class>com.abcinsights.controller.SimpleCorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
CorsFilter
```
public class SimpleCorsFilter extends OncePerRequestFilter {
@Override
public void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
Enumeration<String> headerNames = req.getHeaderNames();
while(headerNames.hasMoreElements()){
String headerName = headerNames.nextElement();
System.out.println("headerName " + headerName);
System.out.println("headerVal " + req.getHeader(headerName));
}
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization");
chain.doFilter(req, res);
}
}
```
This all works fine and when I look at the header names/values I see my Authorization header with the Basic value and the hard coded Base64 string.
So then I tried to add SpringSecurity which would use the Authorization header to do basic authentication. Here's my web.xml and spring security config with Spring Security added in.
updated web.xml
```
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/security-config.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
security-config.xml
```
<http auto-config="true" use-expressions="false">
<intercept-url pattern="/**" access="ROLE_USER" />
<http-basic/>
<custom-filter ref="corsHandler" before="SECURITY_CONTEXT_FILTER"/>
</http>
<beans:bean id="corsHandler" class="com.abcinsights.controller.SimpleCorsFilter"/>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"/>
</authentication-provider>
</authentication-manager>
```
As you can see, I had to add my CORS filter to the front of the spring security filter chain (I also removed it from web.xml). This seems to be working in the sense that the CORS filter still gets called when I make a request. But the request coming from my AJAX call no longer has the Authorization header added in. When I remove the SpringSecurity filter chain and just put my CORS filter back into web.xml the Authorization header comes back. I'm at a loss but am wondering if it has something to do with preflight communication working one way when my CORS filter is stand alone in web.xml and another way when it is in the Spring Security filter chain? Any help would be appreciated.
Thanks | 2015/06/19 | [
"https://Stackoverflow.com/questions/30936170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5027831/"
] | The problem was that angular was sending an HTTP OPTIONS request without the HTTP Authorization header. Spring security was then processing that request and sending back a 401 Unauthorized response. So my angular app was getting a 401 response from spring on the OPTIONS request rather than a 200 response telling angular to go ahead and send the POST request that did have the Authorization header in it. So the fix was to
a) Put my CORSFilter and my SpringSecurity filter in web.xml (rather than having my CORS Filter called from within Spring). Not 100% sure this made a difference but that's what my final web.xml looked like.
b) Added the code from the below link to my CORS Filter so that it doesn't delegate to SpringSecurity for OPTIONS request types.
This post was what got me sorted out: [Standalone Spring OAuth2 JWT Authorization Server + CORS](https://stackoverflow.com/questions/30632200/standalone-spring-oauth2-jwt-authorization-server-cors/30638914#30638914)
Here's my code:
web.xml
```
<display-name>ABC Insights</display-name>
<servlet>
<servlet-name>abcInsightsServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abcInsightsServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Stand Alone Cross Origin Resource Sharing Authorization Configuration -->
<filter>
<filter-name>corsFilter</filter-name>
<filter-class>com.abcinsights.controller.SimpleCorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring Security Configuration -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/security-config.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
Here is my CORS Filter:
```
public class SimpleCorsFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization, X-CSRF-TOKEN");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
}
```
Here is my Angular code:
```
var login = function (credentials) {
console.log("credentials.email: " + credentials.email);
console.log("credentials.password: " + credentials.password);
var base64Credentials = Base64.encode(credentials.email + ':' + credentials.password);
var req = {
method: 'GET',
url: 'http://localhost:8080/abcinsights/loginPage',
headers: {
'Authorization': 'Basic ' + base64Credentials
}
}
return $http(req).then(function (response) {
return response.data;
});
};
```
Hope that helps. | A bit late to the party, but I encountered a similar problem, and thought my soulution might help someone. Joe Rice's soulution really helped me, but I had to make some modifications. I should also mention that I'm not an expert on Spring or Tomcat, so this is probably not a perfect solution.
I have a setup with a React client (running on localhost:3000), Tomcat server (localhost:8080) and Spring Security. I had to make Tomcat handle the CORS headers, as I have two .war-files running on the application server: my application and Geowebcache. It was not sufficient for me to make Spring Security handle the headers, as that would mean that the headers would not be added when the client was communicating directly with Geowebcache.
I also use a login-page implemented with Spring Security. Using Tomcat 'CorsFilter' works fine for all regular requests, but for some reason, the CORS headers was not added on the login request from the client, resulting in the response being blocked by the browser because of missing because of missing 'Access-Control-Allow-Origin' header. My solution to this was to manually add the headers to the login-call from the client, and let the Tomcat config handle the rest. This is my setup.
Spring Security - web.xml:
```
<filter>
<filter-name>corsFilter</filter-name>
<filter-class>path.to.cors.filter.security.SimpleCorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
Spring Security Config:
```
http.csrf().disable()
.formLogin().loginPage("/login").permitAll()
.loginProcessingUrl("/perform_login")
.defaultSuccessUrl("/index.html", true)
.failureUrl("/login?error=true");
```
SimpleCorsFilter.java:
```
public class SimpleCorsFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (request.getRequestURI().endsWith("perform_login")) {
response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization, X-CSRF-TOKEN");
}
chain.doFilter(req, res);
}
```
Tomcat - web.xml
```
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>http://localhost:3000</param-value>
</init-param>
<init-param>
<param-name>cors.support.credentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Content-Disposition,Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
I am using Axios to make the requests from the client, and I had to add 'withCredentials: true' to make the server accept the requests. This is my Axios configuration:
```
axios.create({
baseURL: process.env.NODE_ENV === 'development' ? 'http://localhost:8080/api/' : '/api/',
timeout: 300000,
withCredentials: true
});
```
Hope this can help someone! |
18,833,968 | Let's say I have the following for example's sake:
```
$string = "^4Hello World ^5Foo^8Bar";
```
I'm currently using the following function to replace the carets and adjoining numbers, which is the closest I could get to what I wanted.
```
function addColours($input) {
$var = $input;
$var = str_replace('^0', '</span><span style="color: #000000">', $var);
$var = str_replace('^1', '</span><span style="color: #ff0000">', $var);
$var = str_replace('^2', '</span><span style="color: #00ff00">', $var);
$var = str_replace('^3', '</span><span style="color: #ffff00">', $var);
$var = str_replace('^4', '</span><span style="color: #0000ff">', $var);
$var = str_replace('^5', '</span><span style="color: #00ffff">', $var);
$var = str_replace('^6', '</span><span style="color: #ff00ff">', $var);
$var = str_replace('^7', '</span><span style="color: #ffffff">', $var);
$var = str_replace('^8', '</span><span style="color: #CC9933">', $var);
$var = str_replace('^9', '</span><span style="color: #8D8D8D">', $var);
return $var;
}
```
Which would return the following for the string.
```
</span><span style="color: #0000ff">Hello World </span><span style="color: #00ffff">Foo</span><span style="color: #CC9933">Bar
```
It works fine for the middle parts of the string, but obviously it's adding an unneeded `</span>` at the beginning of the string and it isn't closing the end tag.
Is there any way of making this work?
Thanks, Ben. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18833968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615209/"
] | How about this then?
```
function addColours($input) {
$out = '';
$replacements = array(
'1' => '000000',
'2' => 'ff0000'
);
foreach(explode('^', $input) as $span) {
if(in_array($span[0], array_keys($replacements))) {
$out .= '<span style="color: #' . $replacements[$span[0]] . '">' . substr($span, 1) . '</span>';
} else {
$out .= $span;
}
}
return $out;
}
$body = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. ^1Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. ^2It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
print addColours($body);
``` | You really need to be running a preg replace, not a strreplace. The problem you will still run into here is that you need to find a patter such as '^4Some Sentance ^' so that you can end the span correctly. But what would happen if the entry was the last time a tag was used and it wasn't closed? It would fail.
I recommend switching to this format:
```
[4]Some sentence[/4]
```
Then you can run a simple str\_replace correctly:
```
function addColours($input) {
$replacements = array(
'1' => '000000',
'2' => 'ff0000'
);
foreach($replacements as $key => $value) {
$input = str_replace("[$key]", '<span style="color: #' . $value . '">');
$input = str_replace("[/$key]", '</span>');
}
return $input;
}
``` |
18,833,968 | Let's say I have the following for example's sake:
```
$string = "^4Hello World ^5Foo^8Bar";
```
I'm currently using the following function to replace the carets and adjoining numbers, which is the closest I could get to what I wanted.
```
function addColours($input) {
$var = $input;
$var = str_replace('^0', '</span><span style="color: #000000">', $var);
$var = str_replace('^1', '</span><span style="color: #ff0000">', $var);
$var = str_replace('^2', '</span><span style="color: #00ff00">', $var);
$var = str_replace('^3', '</span><span style="color: #ffff00">', $var);
$var = str_replace('^4', '</span><span style="color: #0000ff">', $var);
$var = str_replace('^5', '</span><span style="color: #00ffff">', $var);
$var = str_replace('^6', '</span><span style="color: #ff00ff">', $var);
$var = str_replace('^7', '</span><span style="color: #ffffff">', $var);
$var = str_replace('^8', '</span><span style="color: #CC9933">', $var);
$var = str_replace('^9', '</span><span style="color: #8D8D8D">', $var);
return $var;
}
```
Which would return the following for the string.
```
</span><span style="color: #0000ff">Hello World </span><span style="color: #00ffff">Foo</span><span style="color: #CC9933">Bar
```
It works fine for the middle parts of the string, but obviously it's adding an unneeded `</span>` at the beginning of the string and it isn't closing the end tag.
Is there any way of making this work?
Thanks, Ben. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18833968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615209/"
] | This is what i was talking about in the comments:
```
$colorMap = array(
'000000', // 0
'ff0000', // 1
'00ff00', // 2...
);
$template = '<span style="color:#%s">%s</span>';
// split by "^" followed by 0-9
$parts = preg_split('/\^(\d)/', $string, -1,
PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
$result = '';
// rebuild string (odd elements are delimiters)
foreach($parts as $idx => $part)
if((($idx % 2) === 0) && isset($colorMap[(int)$part]))
$result .= sprintf($template, $colorMap[(int)$part], $parts[$idx + 1]);
``` | You really need to be running a preg replace, not a strreplace. The problem you will still run into here is that you need to find a patter such as '^4Some Sentance ^' so that you can end the span correctly. But what would happen if the entry was the last time a tag was used and it wasn't closed? It would fail.
I recommend switching to this format:
```
[4]Some sentence[/4]
```
Then you can run a simple str\_replace correctly:
```
function addColours($input) {
$replacements = array(
'1' => '000000',
'2' => 'ff0000'
);
foreach($replacements as $key => $value) {
$input = str_replace("[$key]", '<span style="color: #' . $value . '">');
$input = str_replace("[/$key]", '</span>');
}
return $input;
}
``` |
18,833,968 | Let's say I have the following for example's sake:
```
$string = "^4Hello World ^5Foo^8Bar";
```
I'm currently using the following function to replace the carets and adjoining numbers, which is the closest I could get to what I wanted.
```
function addColours($input) {
$var = $input;
$var = str_replace('^0', '</span><span style="color: #000000">', $var);
$var = str_replace('^1', '</span><span style="color: #ff0000">', $var);
$var = str_replace('^2', '</span><span style="color: #00ff00">', $var);
$var = str_replace('^3', '</span><span style="color: #ffff00">', $var);
$var = str_replace('^4', '</span><span style="color: #0000ff">', $var);
$var = str_replace('^5', '</span><span style="color: #00ffff">', $var);
$var = str_replace('^6', '</span><span style="color: #ff00ff">', $var);
$var = str_replace('^7', '</span><span style="color: #ffffff">', $var);
$var = str_replace('^8', '</span><span style="color: #CC9933">', $var);
$var = str_replace('^9', '</span><span style="color: #8D8D8D">', $var);
return $var;
}
```
Which would return the following for the string.
```
</span><span style="color: #0000ff">Hello World </span><span style="color: #00ffff">Foo</span><span style="color: #CC9933">Bar
```
It works fine for the middle parts of the string, but obviously it's adding an unneeded `</span>` at the beginning of the string and it isn't closing the end tag.
Is there any way of making this work?
Thanks, Ben. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18833968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615209/"
] | This is what i was talking about in the comments:
```
$colorMap = array(
'000000', // 0
'ff0000', // 1
'00ff00', // 2...
);
$template = '<span style="color:#%s">%s</span>';
// split by "^" followed by 0-9
$parts = preg_split('/\^(\d)/', $string, -1,
PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
$result = '';
// rebuild string (odd elements are delimiters)
foreach($parts as $idx => $part)
if((($idx % 2) === 0) && isset($colorMap[(int)$part]))
$result .= sprintf($template, $colorMap[(int)$part], $parts[$idx + 1]);
``` | How about this then?
```
function addColours($input) {
$out = '';
$replacements = array(
'1' => '000000',
'2' => 'ff0000'
);
foreach(explode('^', $input) as $span) {
if(in_array($span[0], array_keys($replacements))) {
$out .= '<span style="color: #' . $replacements[$span[0]] . '">' . substr($span, 1) . '</span>';
} else {
$out .= $span;
}
}
return $out;
}
$body = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. ^1Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. ^2It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
print addColours($body);
``` |
18,833,968 | Let's say I have the following for example's sake:
```
$string = "^4Hello World ^5Foo^8Bar";
```
I'm currently using the following function to replace the carets and adjoining numbers, which is the closest I could get to what I wanted.
```
function addColours($input) {
$var = $input;
$var = str_replace('^0', '</span><span style="color: #000000">', $var);
$var = str_replace('^1', '</span><span style="color: #ff0000">', $var);
$var = str_replace('^2', '</span><span style="color: #00ff00">', $var);
$var = str_replace('^3', '</span><span style="color: #ffff00">', $var);
$var = str_replace('^4', '</span><span style="color: #0000ff">', $var);
$var = str_replace('^5', '</span><span style="color: #00ffff">', $var);
$var = str_replace('^6', '</span><span style="color: #ff00ff">', $var);
$var = str_replace('^7', '</span><span style="color: #ffffff">', $var);
$var = str_replace('^8', '</span><span style="color: #CC9933">', $var);
$var = str_replace('^9', '</span><span style="color: #8D8D8D">', $var);
return $var;
}
```
Which would return the following for the string.
```
</span><span style="color: #0000ff">Hello World </span><span style="color: #00ffff">Foo</span><span style="color: #CC9933">Bar
```
It works fine for the middle parts of the string, but obviously it's adding an unneeded `</span>` at the beginning of the string and it isn't closing the end tag.
Is there any way of making this work?
Thanks, Ben. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18833968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615209/"
] | How about this then?
```
function addColours($input) {
$out = '';
$replacements = array(
'1' => '000000',
'2' => 'ff0000'
);
foreach(explode('^', $input) as $span) {
if(in_array($span[0], array_keys($replacements))) {
$out .= '<span style="color: #' . $replacements[$span[0]] . '">' . substr($span, 1) . '</span>';
} else {
$out .= $span;
}
}
return $out;
}
$body = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. ^1Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. ^2It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
print addColours($body);
``` | Here's my two cents. It's the closest to the OPs code, and doesn't require manual rebuilding of the string.
```
function addColours($input) {
$var = $input;
$var = preg_replace('/\^0(.*?)((\^\d)|($))/', '<span style="color: #000000">$1</span>$2', $var);
$var = preg_replace('/\^1(.*?)((\^\d)|($))/', '<span style="color: #ff0000">$1</span>$2', $var);
$var = preg_replace('/\^2(.*?)((\^\d)|($))/', '<span style="color: #00ff00">$1</span>$2', $var);
$var = preg_replace('/\^3(.*?)((\^\d)|($))/', '<span style="color: #ffff00">$1</span>$2', $var);
$var = preg_replace('/\^4(.*?)((\^\d)|($))/', '<span style="color: #0000ff">$1</span>$2', $var);
$var = preg_replace('/\^5(.*?)((\^\d)|($))/', '<span style="color: #00ffff">$1</span>$2', $var);
$var = preg_replace('/\^6(.*?)((\^\d)|($))/', '<span style="color: #ff00ff">$1</span>$2', $var);
$var = preg_replace('/\^7(.*?)((\^\d)|($))/', '<span style="color: #ffffff">$1</span>$2', $var);
$var = preg_replace('/\^8(.*?)((\^\d)|($))/', '<span style="color: #CC9933">$1</span>$2', $var);
$var = preg_replace('/\^9(.*?)((\^\d)|($))/', '<span style="color: #8D8D8D">$1</span>$2', $var);
return $var;
}
``` |
18,833,968 | Let's say I have the following for example's sake:
```
$string = "^4Hello World ^5Foo^8Bar";
```
I'm currently using the following function to replace the carets and adjoining numbers, which is the closest I could get to what I wanted.
```
function addColours($input) {
$var = $input;
$var = str_replace('^0', '</span><span style="color: #000000">', $var);
$var = str_replace('^1', '</span><span style="color: #ff0000">', $var);
$var = str_replace('^2', '</span><span style="color: #00ff00">', $var);
$var = str_replace('^3', '</span><span style="color: #ffff00">', $var);
$var = str_replace('^4', '</span><span style="color: #0000ff">', $var);
$var = str_replace('^5', '</span><span style="color: #00ffff">', $var);
$var = str_replace('^6', '</span><span style="color: #ff00ff">', $var);
$var = str_replace('^7', '</span><span style="color: #ffffff">', $var);
$var = str_replace('^8', '</span><span style="color: #CC9933">', $var);
$var = str_replace('^9', '</span><span style="color: #8D8D8D">', $var);
return $var;
}
```
Which would return the following for the string.
```
</span><span style="color: #0000ff">Hello World </span><span style="color: #00ffff">Foo</span><span style="color: #CC9933">Bar
```
It works fine for the middle parts of the string, but obviously it's adding an unneeded `</span>` at the beginning of the string and it isn't closing the end tag.
Is there any way of making this work?
Thanks, Ben. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18833968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615209/"
] | This is what i was talking about in the comments:
```
$colorMap = array(
'000000', // 0
'ff0000', // 1
'00ff00', // 2...
);
$template = '<span style="color:#%s">%s</span>';
// split by "^" followed by 0-9
$parts = preg_split('/\^(\d)/', $string, -1,
PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
$result = '';
// rebuild string (odd elements are delimiters)
foreach($parts as $idx => $part)
if((($idx % 2) === 0) && isset($colorMap[(int)$part]))
$result .= sprintf($template, $colorMap[(int)$part], $parts[$idx + 1]);
``` | Here's my two cents. It's the closest to the OPs code, and doesn't require manual rebuilding of the string.
```
function addColours($input) {
$var = $input;
$var = preg_replace('/\^0(.*?)((\^\d)|($))/', '<span style="color: #000000">$1</span>$2', $var);
$var = preg_replace('/\^1(.*?)((\^\d)|($))/', '<span style="color: #ff0000">$1</span>$2', $var);
$var = preg_replace('/\^2(.*?)((\^\d)|($))/', '<span style="color: #00ff00">$1</span>$2', $var);
$var = preg_replace('/\^3(.*?)((\^\d)|($))/', '<span style="color: #ffff00">$1</span>$2', $var);
$var = preg_replace('/\^4(.*?)((\^\d)|($))/', '<span style="color: #0000ff">$1</span>$2', $var);
$var = preg_replace('/\^5(.*?)((\^\d)|($))/', '<span style="color: #00ffff">$1</span>$2', $var);
$var = preg_replace('/\^6(.*?)((\^\d)|($))/', '<span style="color: #ff00ff">$1</span>$2', $var);
$var = preg_replace('/\^7(.*?)((\^\d)|($))/', '<span style="color: #ffffff">$1</span>$2', $var);
$var = preg_replace('/\^8(.*?)((\^\d)|($))/', '<span style="color: #CC9933">$1</span>$2', $var);
$var = preg_replace('/\^9(.*?)((\^\d)|($))/', '<span style="color: #8D8D8D">$1</span>$2', $var);
return $var;
}
``` |
26,982,032 | **Edit:** TL;DR
Is there anyone who uses Magento Rest API with angularjs and could give me some hints on how to get started with OAuth?
I'm trying to use the magento Rest API with angularjs. My Problem is that I don't even get the initiate endpoint to work.
To calculate the signature I used <https://github.com/bettiolo/oauth-signature-js> :
```
var initEndpointUrl = "http://magentoserver.com/oauth/initiate"
var parameters = {
oauth_callback: callback,
oauth_consumer_key : consumerKey,
oauth_nonce : nonce,
oauth_signature_method : signatureMethod,
oauth_timestamp : timestamp
}
var signature = oauthSignature.generate('POST', initEndpointUrl, parameters, consumerSecret);
```
I've tried two different approaches:
1: Send the parameters with the Authorization Header:
```
var authHeader = "OAuth "+
"oauth_callback=" + callback + "," +
"oauth_consumer_key=" + consumerKey + "," +
"oauth_nonce=" + nonce + "," +
"oauth_signature_method=" + signatureMethod + "," +
"oauth_timestamp=" + timestamp + "," +
"oauth_signature=" + signature;
$http({
method: 'POST',
url: initEndpointUrl,
header: {
'Authorization': authHeader
}
})
```
The Problem with this approach is, that I get a **400 Bad Request** for the *OPTIONS* method from the server. This is caused (as far as I read) by the request not being a "Simple Request" because of the Authentication header. This in the Pre-flight the *OPTIONS* method is called.
2: Send the parameters as url parameter:
```
http://magentoserver.com/oauth/initiate?
oauth_callback=http%3A%2F%2Flocalhost&
oauth_consumer_key=12345&
oauth_nonce=67890&
oauth_signature_method=HMAC-SHA1&
oauth_timestamp=1234567890&
oauth_signature=abcdefg1234567
```
With this approach I had more success and was able to add all required parameters until the signature was checked, which resulted in **401 oauth\_problem=signature\_invalid**.
I'm quite new to OAuth so I'm thinking maybe the call for generating the signature wasn't correct. On the other hand I could imagine, that by changing the parameters (and with it the URL) I invalidate the signature.
Anybody has experience with this? Thanks in advance!
PS: I already posted this on <https://magento.stackexchange.com/>, because I thought it would be more magento specific. | 2014/11/17 | [
"https://Stackoverflow.com/questions/26982032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4262924/"
] | After a lot of help from Nic Raboy we got it included in his OAuth Library:
[ng-cordova-oauth](https://github.com/nraboy/ng-cordova-oauth)
The library does all the signing, nonce calculation and everything else that is needed. It does however require to run on cordova (using the inAppBrowser plugin).
Before that worked there had to be some fixes for Magento:
[OAuth activation if initiate directs to 404](https://stackoverflow.com/questions/14472228/magento-rest-api-oauth-url-returning-404)
[OAuth fix for missing form\_key](https://stackoverflow.com/questions/23992987/magento-api-rest-customer-not-redirecting-to-authentication-page)
[OAuth fix for redirecting to dashboard](https://gist.github.com/SchumacherFM/9774636)
The last one didn't work on instant, but it is the right direction. If anyone has questions about this, please feel free to ask. I was really surprised that it took this much effort to get it to run.
Thanks Nic, it's really easy now to get the access\_token :) | I am just using OAuth in PHP. I hope to it help you.
Look this example link. When use 'oauth/initiate', oauth\_callback is included on URL. Write it both sides
<http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html#OAuthAuthentication-PHPExamples>
And I saw other OAuth header there are using double quotation marks every value as oauth\_signature\_method="HMAC-SHA1" |
47,586,867 | >
> I want to calculate how many number of months in particular year? For example
> In 1.5 year how many month are ? It's simple but programmatically how do i calculate this??
> Please can anybody tell me??
>
>
> | 2017/12/01 | [
"https://Stackoverflow.com/questions/47586867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4823598/"
] | If you know the number of Year(s), `1.5`, you would calculate this by multiplying it by the number of Months in a year, `12`.
```
function calcMonths($y){
return $y * 12;
}
```
Input: 1.5, Output: 18. | If you have Start Date and End Date then it will easy to calculate months between those two dates try below Code.
```
$date1 = '2000-01-25';
$date2 = '2010-02-20';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);
$month1 = date('m', $ts1);
$month2 = date('m', $ts2);
echo $diff = (($year2 - $year1) * 12) + ($month2 - $month1);
``` |
82,247 | Please suggest some good books for the person who is going to setup windows server 2008 & sql server 2008 for shared hosting service. | 2009/11/06 | [
"https://serverfault.com/questions/82247",
"https://serverfault.com",
"https://serverfault.com/users/21002/"
] | "Windows Server 2008 Unleashed" by SAMS Publishing and "Introducing Microsoft SQL Server 2008" by Microsoft Press are good books. | Whenever somebody asks for a book recommendation, I always feel compelled to mention O'Reilly's [Safari Books Online](http://www.safaribooksonline.com/Corporate/Index/). It's an amazing resource of online books from many publishers. I think I pay about $40 per month and I get full access to thousands of titles. (actually my work pays for it)
A quick search on SQL Server 2008 brings back 385 Results including "SQL Server 2008, Administration in Action" and "Microsoft SQL Server 2008 Management and Administration." Searching for Windows Server 2008 brings back 643 results including "Windows Server 2008 Unleashed" and "Introducing Windows Server 2008".
Sorry this isn't a specific book recommendation, but I use Safari as a "giant book." If you can handle reading online, I recommend it highly over buying a bunch of paper. I especially find it helpful to read about topics in multiple books; some are better in areas than others. |
82,247 | Please suggest some good books for the person who is going to setup windows server 2008 & sql server 2008 for shared hosting service. | 2009/11/06 | [
"https://serverfault.com/questions/82247",
"https://serverfault.com",
"https://serverfault.com/users/21002/"
] | "Windows Server 2008 Unleashed" by SAMS Publishing and "Introducing Microsoft SQL Server 2008" by Microsoft Press are good books. | After you are comfortable with the technology side of Windows and SQL Server then you should be ready for the looking at Systems Administration as a profession - [The Practice of System and Network Administration](http://rads.stackoverflow.com/amzn/click/0321492668). |
82,247 | Please suggest some good books for the person who is going to setup windows server 2008 & sql server 2008 for shared hosting service. | 2009/11/06 | [
"https://serverfault.com/questions/82247",
"https://serverfault.com",
"https://serverfault.com/users/21002/"
] | Whenever somebody asks for a book recommendation, I always feel compelled to mention O'Reilly's [Safari Books Online](http://www.safaribooksonline.com/Corporate/Index/). It's an amazing resource of online books from many publishers. I think I pay about $40 per month and I get full access to thousands of titles. (actually my work pays for it)
A quick search on SQL Server 2008 brings back 385 Results including "SQL Server 2008, Administration in Action" and "Microsoft SQL Server 2008 Management and Administration." Searching for Windows Server 2008 brings back 643 results including "Windows Server 2008 Unleashed" and "Introducing Windows Server 2008".
Sorry this isn't a specific book recommendation, but I use Safari as a "giant book." If you can handle reading online, I recommend it highly over buying a bunch of paper. I especially find it helpful to read about topics in multiple books; some are better in areas than others. | After you are comfortable with the technology side of Windows and SQL Server then you should be ready for the looking at Systems Administration as a profession - [The Practice of System and Network Administration](http://rads.stackoverflow.com/amzn/click/0321492668). |
34,901,756 | ```
import re
phoneNumberRegex = re.compile(r'\d{3}-\d{3}-\d{4}')
mo = phoneNumberRegex.search('My number is 415-55-4242.')
print('Phone number found: ' + mo.group(0))
```
This is the method I have used tried to find some mistakes with the code all resulted in this error
```
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print('Phone number found: ' + mo.group(0))
AttributeError: 'NoneType' object has no attribute 'group'
``` | 2016/01/20 | [
"https://Stackoverflow.com/questions/34901756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5406550/"
] | Usage of [`MatchObject.group`](https://docs.python.org/3/library/re.html#re.match.group) is okay.
But, `415-55-4242` does not match `\d{3}-\d{3}-\d{4}` because the middle part of the string contains only 2 digits.
```
>>> import re
>>> re.search(r'\d{3}-\d{3}-\d{4}', 'My number is 415-55-4242.') # does not match => None
>>> re.search(r'\d{3}-\d{2}-\d{4}', 'My number is 415-55-4242.') # matches => MatchObject
<_sre.SRE_Match object; span=(13, 24), match='415-55-4242'>
```
To prevent the error, you need to guard the last statement:
```
phoneNumberRegex = re.compile(r'\d{3}-\d{3}-\d{4}')
mo = phoneNumberRegex.search('My number is 415-55-4242.')
if mo:
print('Phone number found: ' + mo.group(0))
```
**UPDATE**
If you don't want to match `12345-123-12345`, you need to use word boundary (`\b`):
```
r'\b\d{3}-\d{3}-\d{4}\b'
``` | It works -- group is the right method. However, you need a capturing group in you regex, and the regex is also a bit wrong. Use this code instead:
```
import re
phoneNumberRegex = re.compile(r'(\d{3}-\d{2}-\d{4})')
mo = phoneNumberRegex.search('My number is 415-55-4242.')
print(mo.group(0))
``` |
3,333,990 | For what values of $\alpha,\beta \in \mathbb{R}$ will the function
$$f:(0,1]\times(0,1] \to \mathbb{R}: (x,y) \mapsto x^\alpha y^\alpha (x+y)^\beta$$
be integrable?
Normally, I don't have problems solving these integrals using Fubini's theorem and by a change of variables. However, I don't seem to find the right change of variables? Any hints? Thank you! | 2019/08/25 | [
"https://math.stackexchange.com/questions/3333990",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/356160/"
] | Let $C = (0, 1]^2$. I assume by $f$ being integrable you mean that $\int\_C f < \infty$ (here and throughout I use $\int\_A f$ to denote $\iint\_A f \,dxdy$).
First we'll show that $\int\_C f < \infty$ implies $\alpha > -1$. Let $D = (0, 1] \times [1/2, 1]$, so since $D \subset C$ we have $\int\_C f \geq \int\_D f
$. But for $(x, y) \in D$ we have $1/2 \leq y \leq 1$ and $1/2 \leq x+y \leq 2$, hence $y^{\alpha} \geq 2^{-|\alpha|}$ and $(x+y)^{\beta} \geq 2^{-|\beta|}$, giving
$$\int\_D f = \int\_0^1 \int\_{1/2}^1 x^\alpha y^\alpha (x+y)^\beta \,dy \,dx \geq 2^{-|\alpha|-|\beta|-1}\int\_0^1 x^{\alpha} \,dx$$
so if $\int\_C f < \infty$ we must have $\int\_0^1 x^\alpha \,dx < \infty$, hence $\alpha > -1$.
Now assume $\alpha > -1$. Define $E = \{(x, y) \mid x, y > 0, x+y \leq 1\}$. Then clearly $E \subset C \subset 2E$, where $2E = \{(x, y) \mid x, y > 0, x+y \leq 2\}$, hence $\int\_E f \leq \int\_C f \leq \int\_{2E} f$. But it's easy to check that $\int\_{2E} f = 2^{2\alpha + \beta+2} \int\_E f$ since $f$ is homogeneous of degree $2\alpha + \beta$, which gives $\int\_E f \leq \int\_C f \leq 2^{2\alpha + \beta + 2} \int\_E f$, so it follows that $\int\_C f < \infty$ if and only if $\int\_E f < \infty$.
But we can evaluate $\int\_E f$ using the change of variables $s = x + y$:
$$\int\_E f = \int\_0^1 \int\_0^s x^\alpha(s - x)^{\alpha} s^\beta \,dx \,ds = B(\alpha + 1, \alpha + 1)\int\_0^1 s^{2\alpha + \beta + 1} \,ds$$
where $B(a, b) = \frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)} = \int\_0^1 x^{a-1}(1-x)^{b-1} \,dx$ is the Beta function, defined for $a, b > 0$. Since $\alpha + 1 > 0$, this means $\int\_E f < \infty$ iff $\int\_0^1 s^{2\alpha + \beta + 1} \,ds < \infty$, which is true iff $2\alpha + \beta + 1 > -1$.
We conclude that $\int\_C f < \infty$ iff $\alpha > -1$ and $\beta > -2(\alpha + 1)$. | In the meantime, I did find some change of variables which might allow a simpler way to verify the integrability. If we perform a change of variables $y\mapsto xy$, this gives the integral
$$\int\_0^1\int\_0^{1/x}x^{2\alpha +\beta+1} y^\alpha(1+y)^\beta dy\, dx$$
where the integrability can be easily verified. |
229,501 | During the COVID-19 pandemic, many of us are working from home using meeting apps like Zoom. It's all over the news that Zoom is lacking in its E2E encryption. Let's assume we're using Zoom and can't switch apps.
Considering only the traffic, how can we make these meetings secured/encrypted?
The solution can be hard on 1 group (the company using Zoom) but should be easy on the users (employees of the company). My 1st thought here is to have the company set up a VPN server (in the company or with a 3rd party) and have everyone connect to the VPN before joining a meeting. | 2020/04/09 | [
"https://security.stackexchange.com/questions/229501",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/206331/"
] | You cannot magically secure applications like Zoom without changing the application and the infrastructure it relies on.
The missing end-to-end encryption you want to have fixed is due to the basic architecture of Zoom, in which media streams are processed and mixed together on a central server (which is owned by Zoom). Only this architecture actually allows it to perform well without stressing bandwidth and CPU of endpoints when many users are involved. With E2E instead the requirements for CPU and bandwidth at each end would grow linearly with the number of users and thus would quickly overwhelm clients.
These kind of restrictions apply to any video conferencing solution. This means that you will not get real E2E with any other solution too, at least not if you want conferences which scale to many users without having excessive requirements regarding bandwidth and CPU power. The best you can get is that you control the central mixing and forwarding server yourself and thus don't need to trust a third party.
Even the broken AES ECB mode could not be fixed without changing application and infrastructure since the server actually expects the encryption to be a specific way and if you change it the communication will fail.
Usage of a VPN would not magically solve the problem. The data would still need to be processed on the servers owned by Zoom. | A somewhat trite answer - don't use zoom's native software..
Instead - look around for the "dial-in number" and call the meeting using a regular telephone.
Downsides, you won't get the video stream, and the user creating the meeting has to be in credit and a paying customer. These are not available in the free accounts.
<https://support.zoom.us/hc/en-us/articles/201362663-Joining-a-meeting-by-phone>
Also consider that other participants in the meeting may remain vulnerable, so your words could still become exposed. And any meeting recording will carry your input too. |
229,501 | During the COVID-19 pandemic, many of us are working from home using meeting apps like Zoom. It's all over the news that Zoom is lacking in its E2E encryption. Let's assume we're using Zoom and can't switch apps.
Considering only the traffic, how can we make these meetings secured/encrypted?
The solution can be hard on 1 group (the company using Zoom) but should be easy on the users (employees of the company). My 1st thought here is to have the company set up a VPN server (in the company or with a 3rd party) and have everyone connect to the VPN before joining a meeting. | 2020/04/09 | [
"https://security.stackexchange.com/questions/229501",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/206331/"
] | You cannot magically secure applications like Zoom without changing the application and the infrastructure it relies on.
The missing end-to-end encryption you want to have fixed is due to the basic architecture of Zoom, in which media streams are processed and mixed together on a central server (which is owned by Zoom). Only this architecture actually allows it to perform well without stressing bandwidth and CPU of endpoints when many users are involved. With E2E instead the requirements for CPU and bandwidth at each end would grow linearly with the number of users and thus would quickly overwhelm clients.
These kind of restrictions apply to any video conferencing solution. This means that you will not get real E2E with any other solution too, at least not if you want conferences which scale to many users without having excessive requirements regarding bandwidth and CPU power. The best you can get is that you control the central mixing and forwarding server yourself and thus don't need to trust a third party.
Even the broken AES ECB mode could not be fixed without changing application and infrastructure since the server actually expects the encryption to be a specific way and if you change it the communication will fail.
Usage of a VPN would not magically solve the problem. The data would still need to be processed on the servers owned by Zoom. | *TL;DR: Specifically for Zoom, take a look at [Zoom Meeting Connector](https://support.zoom.us/hc/en-us/sections/200305473-Meeting-Connector)*
First off, to get it out of the way, **encrypted** is not the same as **secure**, and **secure** can be vague depending context.
As schroeder♦ have commented, you need to be clear on what you are actually trying to achieve, what threats you are defending against. Only then you may determine if a solution really solve your problem. It might turn out E2E encryption isn't what you actually need, or want. And like Steffen Ullrich said, you can't just magically add that without significant changes to both its application and infrastructure.
Fortunately, in the case of Zoom, there is a relatively easy way out (depending on you actual needs). Zoom allows you to run your own server for streaming audio and video, while still using Zoom server for other management tasks.
(From <https://support.zoom.us/hc/en-us/articles/201363113-Meeting-Connector-Core-Concepts>)
>
> Zoom offers a public or hybrid cloud service. In the hybrid cloud service, you deploy meeting communication servers known as the Zoom Meeting Connector within your company's internal network. In doing so, user and meeting metadata are managed in the public cloud while the meetings are hosted in your private cloud. All meeting traffic including video, voice and data sharing goes through the on-premise Zoom Meeting Connector.
>
>
> [](https://i.stack.imgur.com/UEupZ.png)
>
>
>
This way, the conference data stays in a server you control. Even if you makes call from outside internal network, the traffic is still encrypted in transit and only decrypted on (your) meeting server. Deployment should not be difficult for a corporate IT team, though might be challenging for laymen. If you want the privacy of E2EE, this is about as close as you can get without actually changing the software or rolling you own service. |
229,501 | During the COVID-19 pandemic, many of us are working from home using meeting apps like Zoom. It's all over the news that Zoom is lacking in its E2E encryption. Let's assume we're using Zoom and can't switch apps.
Considering only the traffic, how can we make these meetings secured/encrypted?
The solution can be hard on 1 group (the company using Zoom) but should be easy on the users (employees of the company). My 1st thought here is to have the company set up a VPN server (in the company or with a 3rd party) and have everyone connect to the VPN before joining a meeting. | 2020/04/09 | [
"https://security.stackexchange.com/questions/229501",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/206331/"
] | You cannot magically secure applications like Zoom without changing the application and the infrastructure it relies on.
The missing end-to-end encryption you want to have fixed is due to the basic architecture of Zoom, in which media streams are processed and mixed together on a central server (which is owned by Zoom). Only this architecture actually allows it to perform well without stressing bandwidth and CPU of endpoints when many users are involved. With E2E instead the requirements for CPU and bandwidth at each end would grow linearly with the number of users and thus would quickly overwhelm clients.
These kind of restrictions apply to any video conferencing solution. This means that you will not get real E2E with any other solution too, at least not if you want conferences which scale to many users without having excessive requirements regarding bandwidth and CPU power. The best you can get is that you control the central mixing and forwarding server yourself and thus don't need to trust a third party.
Even the broken AES ECB mode could not be fixed without changing application and infrastructure since the server actually expects the encryption to be a specific way and if you change it the communication will fail.
Usage of a VPN would not magically solve the problem. The data would still need to be processed on the servers owned by Zoom. | While it is not possible to make E2E encrypted connections with Zoom, your company can probably use an open-source and self-hosted solution like Jitsi. It encrypts the connections between the participants and the server, and only the participants and the server will have the data unencrypted.
So, because you can host the server wherever you want, if you control both the clients and the server you control your data.
Of course, if you use an instance that you don't control, you have to make trust in the instance owner. Similarly, if you use Zoom Meeting Connector , you still have to trust Zoom to not leak - voluntarily or not - your audio. (not saying they will - that's just a possibility)
(From a usability point of view, Jitsi is quite similar to Zoom, although not as feature full, but it works really well) |
229,501 | During the COVID-19 pandemic, many of us are working from home using meeting apps like Zoom. It's all over the news that Zoom is lacking in its E2E encryption. Let's assume we're using Zoom and can't switch apps.
Considering only the traffic, how can we make these meetings secured/encrypted?
The solution can be hard on 1 group (the company using Zoom) but should be easy on the users (employees of the company). My 1st thought here is to have the company set up a VPN server (in the company or with a 3rd party) and have everyone connect to the VPN before joining a meeting. | 2020/04/09 | [
"https://security.stackexchange.com/questions/229501",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/206331/"
] | *TL;DR: Specifically for Zoom, take a look at [Zoom Meeting Connector](https://support.zoom.us/hc/en-us/sections/200305473-Meeting-Connector)*
First off, to get it out of the way, **encrypted** is not the same as **secure**, and **secure** can be vague depending context.
As schroeder♦ have commented, you need to be clear on what you are actually trying to achieve, what threats you are defending against. Only then you may determine if a solution really solve your problem. It might turn out E2E encryption isn't what you actually need, or want. And like Steffen Ullrich said, you can't just magically add that without significant changes to both its application and infrastructure.
Fortunately, in the case of Zoom, there is a relatively easy way out (depending on you actual needs). Zoom allows you to run your own server for streaming audio and video, while still using Zoom server for other management tasks.
(From <https://support.zoom.us/hc/en-us/articles/201363113-Meeting-Connector-Core-Concepts>)
>
> Zoom offers a public or hybrid cloud service. In the hybrid cloud service, you deploy meeting communication servers known as the Zoom Meeting Connector within your company's internal network. In doing so, user and meeting metadata are managed in the public cloud while the meetings are hosted in your private cloud. All meeting traffic including video, voice and data sharing goes through the on-premise Zoom Meeting Connector.
>
>
> [](https://i.stack.imgur.com/UEupZ.png)
>
>
>
This way, the conference data stays in a server you control. Even if you makes call from outside internal network, the traffic is still encrypted in transit and only decrypted on (your) meeting server. Deployment should not be difficult for a corporate IT team, though might be challenging for laymen. If you want the privacy of E2EE, this is about as close as you can get without actually changing the software or rolling you own service. | A somewhat trite answer - don't use zoom's native software..
Instead - look around for the "dial-in number" and call the meeting using a regular telephone.
Downsides, you won't get the video stream, and the user creating the meeting has to be in credit and a paying customer. These are not available in the free accounts.
<https://support.zoom.us/hc/en-us/articles/201362663-Joining-a-meeting-by-phone>
Also consider that other participants in the meeting may remain vulnerable, so your words could still become exposed. And any meeting recording will carry your input too. |
229,501 | During the COVID-19 pandemic, many of us are working from home using meeting apps like Zoom. It's all over the news that Zoom is lacking in its E2E encryption. Let's assume we're using Zoom and can't switch apps.
Considering only the traffic, how can we make these meetings secured/encrypted?
The solution can be hard on 1 group (the company using Zoom) but should be easy on the users (employees of the company). My 1st thought here is to have the company set up a VPN server (in the company or with a 3rd party) and have everyone connect to the VPN before joining a meeting. | 2020/04/09 | [
"https://security.stackexchange.com/questions/229501",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/206331/"
] | While it is not possible to make E2E encrypted connections with Zoom, your company can probably use an open-source and self-hosted solution like Jitsi. It encrypts the connections between the participants and the server, and only the participants and the server will have the data unencrypted.
So, because you can host the server wherever you want, if you control both the clients and the server you control your data.
Of course, if you use an instance that you don't control, you have to make trust in the instance owner. Similarly, if you use Zoom Meeting Connector , you still have to trust Zoom to not leak - voluntarily or not - your audio. (not saying they will - that's just a possibility)
(From a usability point of view, Jitsi is quite similar to Zoom, although not as feature full, but it works really well) | A somewhat trite answer - don't use zoom's native software..
Instead - look around for the "dial-in number" and call the meeting using a regular telephone.
Downsides, you won't get the video stream, and the user creating the meeting has to be in credit and a paying customer. These are not available in the free accounts.
<https://support.zoom.us/hc/en-us/articles/201362663-Joining-a-meeting-by-phone>
Also consider that other participants in the meeting may remain vulnerable, so your words could still become exposed. And any meeting recording will carry your input too. |
229,501 | During the COVID-19 pandemic, many of us are working from home using meeting apps like Zoom. It's all over the news that Zoom is lacking in its E2E encryption. Let's assume we're using Zoom and can't switch apps.
Considering only the traffic, how can we make these meetings secured/encrypted?
The solution can be hard on 1 group (the company using Zoom) but should be easy on the users (employees of the company). My 1st thought here is to have the company set up a VPN server (in the company or with a 3rd party) and have everyone connect to the VPN before joining a meeting. | 2020/04/09 | [
"https://security.stackexchange.com/questions/229501",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/206331/"
] | *TL;DR: Specifically for Zoom, take a look at [Zoom Meeting Connector](https://support.zoom.us/hc/en-us/sections/200305473-Meeting-Connector)*
First off, to get it out of the way, **encrypted** is not the same as **secure**, and **secure** can be vague depending context.
As schroeder♦ have commented, you need to be clear on what you are actually trying to achieve, what threats you are defending against. Only then you may determine if a solution really solve your problem. It might turn out E2E encryption isn't what you actually need, or want. And like Steffen Ullrich said, you can't just magically add that without significant changes to both its application and infrastructure.
Fortunately, in the case of Zoom, there is a relatively easy way out (depending on you actual needs). Zoom allows you to run your own server for streaming audio and video, while still using Zoom server for other management tasks.
(From <https://support.zoom.us/hc/en-us/articles/201363113-Meeting-Connector-Core-Concepts>)
>
> Zoom offers a public or hybrid cloud service. In the hybrid cloud service, you deploy meeting communication servers known as the Zoom Meeting Connector within your company's internal network. In doing so, user and meeting metadata are managed in the public cloud while the meetings are hosted in your private cloud. All meeting traffic including video, voice and data sharing goes through the on-premise Zoom Meeting Connector.
>
>
> [](https://i.stack.imgur.com/UEupZ.png)
>
>
>
This way, the conference data stays in a server you control. Even if you makes call from outside internal network, the traffic is still encrypted in transit and only decrypted on (your) meeting server. Deployment should not be difficult for a corporate IT team, though might be challenging for laymen. If you want the privacy of E2EE, this is about as close as you can get without actually changing the software or rolling you own service. | While it is not possible to make E2E encrypted connections with Zoom, your company can probably use an open-source and self-hosted solution like Jitsi. It encrypts the connections between the participants and the server, and only the participants and the server will have the data unencrypted.
So, because you can host the server wherever you want, if you control both the clients and the server you control your data.
Of course, if you use an instance that you don't control, you have to make trust in the instance owner. Similarly, if you use Zoom Meeting Connector , you still have to trust Zoom to not leak - voluntarily or not - your audio. (not saying they will - that's just a possibility)
(From a usability point of view, Jitsi is quite similar to Zoom, although not as feature full, but it works really well) |
48,313,291 | I'm trying to use AWS Cognito in a Lambda function to authorize a user.
I have some sample code from a Udemy Course (no longer available): <https://www.udemy.com/minimum-viable-aws-cognito-user-auth-in-javascript>
The code uses the script files:
aws-cognito-sdk.min.js
amazon-cognito-identity.min.js
The second seems to available by npm as: amazon-cognito-identity-js
The first file is supposed to be a cut down version of the aws-sdk with just the Cognito api components. The full aws-sdk is available from npm as: aws-sdk but I cannot find the cutdown version in npm.
Is the cutdown file: aws-cognito-sdk.min.js available in npm?
EDIT:
According to Russell I should use the aws-sdk package.
So if I have code:
```
const AWS = require('aws-sdk');
var authenticationDetails = new AWS.AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
```
I get the error:
Cannot read property 'CognitoIdentityServiceProvider' of undefined
What is the correct path to AuthenticationDetails? | 2018/01/18 | [
"https://Stackoverflow.com/questions/48313291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1481505/"
] | Got this working.
package.json needs dependencies:
```
"amazon-cognito-identity-js": "^1.31.0",
"aws-sdk": "^2.182.0",
```
AWS Lambda does not use Javascript ES6 and so you can't use the 'import' keyword.
```
const AWS = require('aws-sdk');
var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
var CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
var AuthenticationDetails = AmazonCognitoIdentity.AuthenticationDetails;
var CognitoUser = AmazonCognitoIdentity.CognitoUser;
var poolData = {
UserPoolId: 'THE USER POOL ID',
ClientId: 'THE CLIENT ID'
};
var userPool = new CognitoUserPool(poolData);
AWS.config.region = 'AWS_REGION';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'THE USERPOOL ID',
});
var email = "someone@somewhere.com";
var password = "password";
var authenticationData = {
Username: email,
Password: password
};
var authenticationDetails = new AuthenticationDetails(authenticationData);
var userData = {
Username: email,
Pool: userPool
};
var cognitoUser = new CognitoUser(userData);
console.log(result);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
callback(null, result);
},
onFailure: function (err) {
console.log('Login error: ' + err);
callback(null, result);
}
});
``` | I believe you are referring to the amazon-cognito-identity-js npm package here:
<https://www.npmjs.com/package/amazon-cognito-identity-js>
The NPM package includes both files.
The package includes the cognito SDK calls (aws-cognito-sdk). It also depends on the core AWS SDK. |
48,313,291 | I'm trying to use AWS Cognito in a Lambda function to authorize a user.
I have some sample code from a Udemy Course (no longer available): <https://www.udemy.com/minimum-viable-aws-cognito-user-auth-in-javascript>
The code uses the script files:
aws-cognito-sdk.min.js
amazon-cognito-identity.min.js
The second seems to available by npm as: amazon-cognito-identity-js
The first file is supposed to be a cut down version of the aws-sdk with just the Cognito api components. The full aws-sdk is available from npm as: aws-sdk but I cannot find the cutdown version in npm.
Is the cutdown file: aws-cognito-sdk.min.js available in npm?
EDIT:
According to Russell I should use the aws-sdk package.
So if I have code:
```
const AWS = require('aws-sdk');
var authenticationDetails = new AWS.AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
```
I get the error:
Cannot read property 'CognitoIdentityServiceProvider' of undefined
What is the correct path to AuthenticationDetails? | 2018/01/18 | [
"https://Stackoverflow.com/questions/48313291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1481505/"
] | For Lambdas use the `aws-sdk` module as such:
```
const { CognitoIdentityServiceProvider } = require('aws-sdk')
//or
const CognitoIdentityServiceProvider = require('aws-sdk/clients/cognitoidentityserviceprovider') // Much smaller size
```
For authentication use the [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) method.
```
const cognitoProvider = new CognitoIdentityServiceProvider({
apiVersion: '2016-04-18',
accessKeyId:...
secretAccessKey: ...
region:...
})
await cognitoProvider.adminInitiateAuth(...)
```
The [`amazon-cognito-identity-js`](https://www.npmjs.com/package/amazon-cognito-identity-js) package is meant for frontend clients (React, React Native, etc). It contains only the functionality necessary to connect to Cognito. It does not require the `aws-sdk` module (unless you need extra features).
While you may be able to use the `amazon-cognito-identity-js` for your use case it's far from ideal as you are just pretending to be an unauthenticated user with limited functionality compared to loading the admin method using your api key thereby providing you with much more functionality. | I believe you are referring to the amazon-cognito-identity-js npm package here:
<https://www.npmjs.com/package/amazon-cognito-identity-js>
The NPM package includes both files.
The package includes the cognito SDK calls (aws-cognito-sdk). It also depends on the core AWS SDK. |
34,513,367 | Are there any Fabric.JS Wizards out there?
I've done my fair research and I can't seem to find much of an explanation on how to add an image to the fabric.JS canvas.
User Journey:
a) User uploads an image from an input file type button.
b) As soon as they have selected an image from their computer I want to place it into the users canvas.
So far I've got to storing the image into an expression, this is my code below:
```
scope.setFile = function(element) {
scope.currentFile = element.files[0];
var reader = new FileReader();
/**
*
*/
reader.onload = function(event) {
// This stores the image to scope
scope.imageSource = event.target.result;
scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
};
```
My HTML/Angular:
```
<label class="app-file-input button">
<i class="icon-enter"></i>
<input type="file"
id="trigger"
onchange="angular.element(this).scope().setFile(this)"
accept="image/*">
</label>
```
If you haven't guessed yet I am using a MEAN stack. Mongoose, Express, Angular and Node.
The scope imageSource is what the image is store in. I've [read this SO](https://stackoverflow.com/questions/15226332/add-image-from-user-computer-to-canvas)
and it talks about pushing the image to the Image object with my result, and then pass it to the fabric.Image object. Has anyone done a similar thing that they can help me with?
Thanks in advance
\*\*\*\* UPDATE \*\*\*\*
Directive defines the canvas variable:
```
var canvas = new fabric.Canvas(attrs.id, {
isDrawingMode: true
});
``` | 2015/12/29 | [
"https://Stackoverflow.com/questions/34513367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070590/"
] | Upload image from computer with Fabric js.
```js
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 0, top: 0, angle: 00,width:100, height:100}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
});
};
reader.readAsDataURL(file);
});
```
```css
canvas{
border: 1px solid black;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file"><br />
<canvas id="canvas" width="450" height="450"></canvas>
``` | once you have a dataURL done, you can do either:
```
reader.onload = function(event) {
// This stores the image to scope
fabric.Image.fromURL(event.target.result, function(img) {
canvas.add(img);
});
scope.$apply();
};
```
Or you put on your image tag an onload event where you do:
```
var img = new fabric.Image(your_img_element);
canvas.add(img);
``` |
34,513,367 | Are there any Fabric.JS Wizards out there?
I've done my fair research and I can't seem to find much of an explanation on how to add an image to the fabric.JS canvas.
User Journey:
a) User uploads an image from an input file type button.
b) As soon as they have selected an image from their computer I want to place it into the users canvas.
So far I've got to storing the image into an expression, this is my code below:
```
scope.setFile = function(element) {
scope.currentFile = element.files[0];
var reader = new FileReader();
/**
*
*/
reader.onload = function(event) {
// This stores the image to scope
scope.imageSource = event.target.result;
scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
};
```
My HTML/Angular:
```
<label class="app-file-input button">
<i class="icon-enter"></i>
<input type="file"
id="trigger"
onchange="angular.element(this).scope().setFile(this)"
accept="image/*">
</label>
```
If you haven't guessed yet I am using a MEAN stack. Mongoose, Express, Angular and Node.
The scope imageSource is what the image is store in. I've [read this SO](https://stackoverflow.com/questions/15226332/add-image-from-user-computer-to-canvas)
and it talks about pushing the image to the Image object with my result, and then pass it to the fabric.Image object. Has anyone done a similar thing that they can help me with?
Thanks in advance
\*\*\*\* UPDATE \*\*\*\*
Directive defines the canvas variable:
```
var canvas = new fabric.Canvas(attrs.id, {
isDrawingMode: true
});
``` | 2015/12/29 | [
"https://Stackoverflow.com/questions/34513367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070590/"
] | Upload image from computer with Fabric js.
```js
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 0, top: 0, angle: 00,width:100, height:100}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
});
};
reader.readAsDataURL(file);
});
```
```css
canvas{
border: 1px solid black;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file"><br />
<canvas id="canvas" width="450" height="450"></canvas>
``` | This is for drag and drop from desktop using the dataTransfer interface.
```
canvas.on('drop', function(event) {
// prevent the file to open in new tab
event.e.stopPropagation();
event.e.stopImmediatePropagation();
event.e.preventDefault();
// Use DataTransfer interface to access the file(s)
if(event.e.dataTransfer.files.length > 0){
var files = event.e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (f.type.match('image.*')) {
// Read the File objects in this FileList.
var reader = new FileReader();
// listener for the onload event
reader.onload = function(evt) {
// put image on canvas
fabric.Image.fromURL(evt.target.result, function(obj) {
obj.scaleToHeight(canvas.height);
obj.set('strokeWidth',0);
canvas.add(obj);
});
};
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
}
});
```
**Resources**
<https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop> |
116,421 | The words in headlines are capitalized. I'm interested in the history of this.
Where and why were capital letters first used in headlines? Where is this practice of capitalization of words in English titles derived from? Is it derived from German? | 2013/06/12 | [
"https://english.stackexchange.com/questions/116421",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/32658/"
] | That seems like an interesting question, so I did a bit of research.
The short version of what I found is that headlines have been capitalized as long has there have been newspaper headlines.
Read on for the long version.
### Everything Started In All Caps
I started with a quick look at the overall development of capitalization. In latin, the earliest occurrences of lowercase letters come from about AD 79. Before that, everything was essentially written in "uppercase". But of course wasn't standardized until the invention of the printing press.
### The First Book Ever Printed Didn't Use Title-Case
The Gutenberg bible (of course the 1st book ever printed) doesn't have too much in the way of "headlines", but the closest thing approximation would be the titles of sections, such as the title for Jermoe's Prologue to the Pentateuch. Lucky for us, the British Library has a couple of [its copies digitized and online](http://molcat1.bl.uk/treasures/gutenberg/pagemax.asp?page=4r&strCopy=G&vol=1). In the image below, from the British Library's paper copy of the Gutenberg, you can see that the title (in red) to Jerome's Prologue isn't in title case, and only the "I" in "Incipit" - the first word of the title - is capitalized.

### Moving On To Newspapers
The first newspaper ever printed (we'll ignore earlier handwritten newspaper-like things) was "The Relation" from Strasbourg, started in 1605. Also lucky for us, the University of Heidelberg has [digital copies available online](http://digi.ub.uni-heidelberg.de/diglit/relation1609) from the 1609 edition. It didn't have "headlines" in the way we'd think of them in modern newspapers, but instead had something more like a dateline. Here's an example of said dateline, from an October 1609 edition.

My high school German is a bit rusty, but I believe this headline reads, "News from *somethingorsomeone*/ From 1. October Year 1609"
We can't really conclude whether or not this is a headline in title case, since it's not truly a headline.
If we move all the way up to an early British paper, "The London Gazette" (which has [great online archives](http://www.london-gazette.co.uk/search)) from 1665 , we run into the same problem.

In fact, all the way up to the 1800s, "The Gazette" still didn't have anything that could be called a proper headline.
The earliest newspaper I could find online with proper headlines was "The New York Herald" (the publication that sent Stanley in search of Livingstone among other things) from 1840. You can find a [digital archive of scanned microfilm online](http://fultonhistory.com/my%20photo%20albums/All%20Newspapers/New%20York%20NY%20Herald/New%20York%20NY%20Herald%201840/index.html). And all of its headlines are in either title-caps, or all-caps.

For further confirmation, you can see that when the [New York Times launched](http://timesmachine.nytimes.com/browser/1851/09/18/P1) in 1851, it also presented headlines in either title-case, or all-caps.

So, barring contradictory information, I gather that headlines have been capitalized at least as long as newspapers have had them. | When and where was there first a "headline"? Capital letters came **first**.
Lowercase letters are strictly a recent invention, dating from certain medieval hands; they weren't completely rectified until 1800 or so, when English dropped the "long lowercase S" in words like *ſize* and *poiſon.* Ngram graphs for "poison" vs "poifon", or any other internal S/F pair cross dramatically about 1800, because OCR picks up the long ſ as an f. |
72,029,069 | i have created a new environment and i installed the jupyterlab server and notebook . But i can't find the jupyterlab widget on the Anaconda navigator home , i mean i can start the jupyterlab server with the conda prompt , but sometimes i accidentally close it and all my work is gone.
[Where i want to find the jupyterlab and notebook](https://i.stack.imgur.com/08Ndc.png)
in my `base` environment i can easily access to , because it has a shortcut on the menu home : here is an exemple :
[my base environment](https://i.stack.imgur.com/gapOr.png) | 2022/04/27 | [
"https://Stackoverflow.com/questions/72029069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18343968/"
] | Did you maybe install the "wrong" version of Jupyterlab or Jupyter Notebook?
I did, and when I uninstalled that version, reinstalled a new version, the widget showed up.
I installed the version 3.4.2 of JupyterLab and the widget didn't show up.
Then I uninstalled it from conda prompt with `conda uninstall jupyterlab`, then reinstalled a stable version with `conda install jupyterlab=3.3.2`. Now the widget shows up. | Do you have checked <https://www.geeksforgeeks.org/how-to-setup-conda-environment-with-jupyter-notebook/> or <https://medium.com/@nrk25693/how-to-add-your-conda-environment-to-your-jupyter-notebook-in-just-4-steps-abeab8b8d084> ?
Otherwise, I can help in another way. You can also you deepnote for example. It is free, and you can save it using internet, and also share with your mates, friends... <https://deepnote.com/> |
30,877,180 | There is a very simple class:
```
public class LinkInformation
{
public LinkInformation(string link, string text, string group)
{
this.Link = link;
this.Text = text;
this.Group = group;
}
public string Link { get; set; }
public string Text { get; set; }
public string Group { get; set; }
public override string ToString()
{
return Link.PadRight(70) + Text.PadRight(40) + Group;
}
}
```
And I create a list of objects of this class, containing multiple duplicates.
So, I tried using `Distinct()` to get a list of unique values.
But it does not work, so I implemented
```
IComparable<LinkInformation>
int IComparable<LinkInformation>.CompareTo(LinkInformation other)
{
return this.ToString().CompareTo(other.ToString());
}
```
and then...
```
IEqualityComparer<LinkInformation>
public bool Equals(LinkInformation x, LinkInformation y)
{
return x.ToString().CompareTo(y.ToString()) == 0;
}
public int GetHashCode(LinkInformation obj)
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + obj.Link.GetHashCode();
hash = hash * 23 + obj.Text.GetHashCode();
hash = hash * 23 + obj.Group.GetHashCode();
return hash;
}
```
The code using the `Distinct` is:
```
static void Main(string[] args)
{
string[] filePath = { @"C:\temp\html\1.html",
@"C:\temp\html\2.html",
@"C:\temp\html\3.html",
@"C:\temp\html\4.html",
@"C:\temp\html\5.html"};
int index = 0;
foreach (var path in filePath)
{
var parser = new HtmlParser();
var list = parser.Parse(path);
var unique = list.Distinct();
foreach (var elem in unique)
{
var full = new FileInfo(path).Name;
var file = full.Substring(0, full.Length - 5);
Console.WriteLine((++index).ToString().PadRight(5) + file.PadRight(20) + elem);
}
}
Console.ReadKey();
}
```
What has to be done to get `Distinct()` working? | 2015/06/16 | [
"https://Stackoverflow.com/questions/30877180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/863502/"
] | You need to actually pass the `IEqualityComparer` that you've created to `Disctinct` when you call it. It has two overloads, one accepting no parameters and one accepting an `IEqualityComparer`. If you don't provide a comparer the default is used, and the default comparer doesn't compare the objects as you want them to be compared. | If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the IEquatable generic interface in the class.
here is a sample implementation:
```
public class Product : IEquatable<Product>
{
public string Name { get; set; }
public int Code { get; set; }
public bool Equals(Product other)
{
//Check whether the compared object is null.
if (Object.ReferenceEquals(other, null)) return false;
//Check whether the compared object references the same data.
if (Object.ReferenceEquals(this, other)) return true;
//Check whether the products' properties are equal.
return Code.Equals(other.Code) && Name.Equals(other.Name);
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public override int GetHashCode()
{
//Get hash code for the Name field if it is not null.
int hashProductName = Name == null ? 0 : Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = Code.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
```
And this is how you do the actual distinct:
```
Product[] products = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 },
new Product { Name = "apple", Code = 9 },
new Product { Name = "lemon", Code = 12 } };
//Exclude duplicates.
IEnumerable<Product> noduplicates =
products.Distinct();
``` |
30,877,180 | There is a very simple class:
```
public class LinkInformation
{
public LinkInformation(string link, string text, string group)
{
this.Link = link;
this.Text = text;
this.Group = group;
}
public string Link { get; set; }
public string Text { get; set; }
public string Group { get; set; }
public override string ToString()
{
return Link.PadRight(70) + Text.PadRight(40) + Group;
}
}
```
And I create a list of objects of this class, containing multiple duplicates.
So, I tried using `Distinct()` to get a list of unique values.
But it does not work, so I implemented
```
IComparable<LinkInformation>
int IComparable<LinkInformation>.CompareTo(LinkInformation other)
{
return this.ToString().CompareTo(other.ToString());
}
```
and then...
```
IEqualityComparer<LinkInformation>
public bool Equals(LinkInformation x, LinkInformation y)
{
return x.ToString().CompareTo(y.ToString()) == 0;
}
public int GetHashCode(LinkInformation obj)
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + obj.Link.GetHashCode();
hash = hash * 23 + obj.Text.GetHashCode();
hash = hash * 23 + obj.Group.GetHashCode();
return hash;
}
```
The code using the `Distinct` is:
```
static void Main(string[] args)
{
string[] filePath = { @"C:\temp\html\1.html",
@"C:\temp\html\2.html",
@"C:\temp\html\3.html",
@"C:\temp\html\4.html",
@"C:\temp\html\5.html"};
int index = 0;
foreach (var path in filePath)
{
var parser = new HtmlParser();
var list = parser.Parse(path);
var unique = list.Distinct();
foreach (var elem in unique)
{
var full = new FileInfo(path).Name;
var file = full.Substring(0, full.Length - 5);
Console.WriteLine((++index).ToString().PadRight(5) + file.PadRight(20) + elem);
}
}
Console.ReadKey();
}
```
What has to be done to get `Distinct()` working? | 2015/06/16 | [
"https://Stackoverflow.com/questions/30877180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/863502/"
] | You need to actually pass the `IEqualityComparer` that you've created to `Disctinct` when you call it. It has two overloads, one accepting no parameters and one accepting an `IEqualityComparer`. If you don't provide a comparer the default is used, and the default comparer doesn't compare the objects as you want them to be compared. | If you are happy with defining the "distinctness" by a single property, you can do
```
list
.GroupBy(x => x.Text)
.Select(x => x.First())
```
to get a list of "unique" items.
No need to mess around with `IEqualityComparer` et al. |
30,877,180 | There is a very simple class:
```
public class LinkInformation
{
public LinkInformation(string link, string text, string group)
{
this.Link = link;
this.Text = text;
this.Group = group;
}
public string Link { get; set; }
public string Text { get; set; }
public string Group { get; set; }
public override string ToString()
{
return Link.PadRight(70) + Text.PadRight(40) + Group;
}
}
```
And I create a list of objects of this class, containing multiple duplicates.
So, I tried using `Distinct()` to get a list of unique values.
But it does not work, so I implemented
```
IComparable<LinkInformation>
int IComparable<LinkInformation>.CompareTo(LinkInformation other)
{
return this.ToString().CompareTo(other.ToString());
}
```
and then...
```
IEqualityComparer<LinkInformation>
public bool Equals(LinkInformation x, LinkInformation y)
{
return x.ToString().CompareTo(y.ToString()) == 0;
}
public int GetHashCode(LinkInformation obj)
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + obj.Link.GetHashCode();
hash = hash * 23 + obj.Text.GetHashCode();
hash = hash * 23 + obj.Group.GetHashCode();
return hash;
}
```
The code using the `Distinct` is:
```
static void Main(string[] args)
{
string[] filePath = { @"C:\temp\html\1.html",
@"C:\temp\html\2.html",
@"C:\temp\html\3.html",
@"C:\temp\html\4.html",
@"C:\temp\html\5.html"};
int index = 0;
foreach (var path in filePath)
{
var parser = new HtmlParser();
var list = parser.Parse(path);
var unique = list.Distinct();
foreach (var elem in unique)
{
var full = new FileInfo(path).Name;
var file = full.Substring(0, full.Length - 5);
Console.WriteLine((++index).ToString().PadRight(5) + file.PadRight(20) + elem);
}
}
Console.ReadKey();
}
```
What has to be done to get `Distinct()` working? | 2015/06/16 | [
"https://Stackoverflow.com/questions/30877180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/863502/"
] | You need to actually pass the `IEqualityComparer` that you've created to `Disctinct` when you call it. It has two overloads, one accepting no parameters and one accepting an `IEqualityComparer`. If you don't provide a comparer the default is used, and the default comparer doesn't compare the objects as you want them to be compared. | Without using Distinct nor the comparer, how about:
```
list.GroupBy(x => x.ToString()).Select(x => x.First())
```
I know this solution is not the answer for the exact question, but I think is valid to be open for other solutions. |
22,155,827 | I am trying to write data into a txt file, but It won't work. there is no error. it just won't work.
here is the code
```
if (isset($_REQUEST['submit']))
{
$hour = $_REQUEST['hour'];
$family = $_REQUEST['family'];
$how = $_REQUEST['how'];
$will = $_REQUEST['will'];
$fun = $_REQUEST['fun'];
$kind = $_REQUEST['kind'];
$device = $_REQUEST['device'];
$study = $_REQUEST['study'];
$agree = $_REQUEST['agree'];
$text = "hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />" ;
fopen('/1.txt', "r");
fwrite('/1.txt',"hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />");
fclose('/1.txt');
}
```
do note that there is an "else" that includes all the aforementioned input fields that I used in the code , and that I am executing on localhost.
thanks | 2014/03/03 | [
"https://Stackoverflow.com/questions/22155827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2870449/"
] | You cannot write to it since you are opening it as read-only:
```
$handle = fopen('/1.txt', "r");
```
Instead:
```
$handle = fopen('/1.txt', "w"); // to write only, if you need to read and write use 'w+'
```
You also need to store fopen in a $handle so you can write to it later.
Documentation: <http://www.php.net/manual/en/function.fopen.php>
Now the first parameter for fwrite should be `$handle`:
```
fwrite($handle, "hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />");
```
Documentation: <http://www.php.net/manual/en/function.fwrite.php>
At the end you should also close with `$handle`:
```
fclose($handle);
```
Documentation: <http://www.php.net/manual/en/function.fclose.php> | You have to pass in a 'w' to write to a file.
```
$handle = fopen('/1.txt', "w");
```
Passing in 'r' makes it so you are opening a 'read-only' file. |
22,155,827 | I am trying to write data into a txt file, but It won't work. there is no error. it just won't work.
here is the code
```
if (isset($_REQUEST['submit']))
{
$hour = $_REQUEST['hour'];
$family = $_REQUEST['family'];
$how = $_REQUEST['how'];
$will = $_REQUEST['will'];
$fun = $_REQUEST['fun'];
$kind = $_REQUEST['kind'];
$device = $_REQUEST['device'];
$study = $_REQUEST['study'];
$agree = $_REQUEST['agree'];
$text = "hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />" ;
fopen('/1.txt', "r");
fwrite('/1.txt',"hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />");
fclose('/1.txt');
}
```
do note that there is an "else" that includes all the aforementioned input fields that I used in the code , and that I am executing on localhost.
thanks | 2014/03/03 | [
"https://Stackoverflow.com/questions/22155827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2870449/"
] | You cannot write to it since you are opening it as read-only:
```
$handle = fopen('/1.txt', "r");
```
Instead:
```
$handle = fopen('/1.txt', "w"); // to write only, if you need to read and write use 'w+'
```
You also need to store fopen in a $handle so you can write to it later.
Documentation: <http://www.php.net/manual/en/function.fopen.php>
Now the first parameter for fwrite should be `$handle`:
```
fwrite($handle, "hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />");
```
Documentation: <http://www.php.net/manual/en/function.fwrite.php>
At the end you should also close with `$handle`:
```
fclose($handle);
```
Documentation: <http://www.php.net/manual/en/function.fclose.php> | You are opening the file as read-only, with the `r`use `w` instead. And you need to pass [`fwrite`](http://at2.php.net/fwrite) the return of `fopen` as first argument, not the filename:
```
$f = fopen('/1.txt', "w");
fwrite($f,"hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />");
fclose($f);
``` |
22,155,827 | I am trying to write data into a txt file, but It won't work. there is no error. it just won't work.
here is the code
```
if (isset($_REQUEST['submit']))
{
$hour = $_REQUEST['hour'];
$family = $_REQUEST['family'];
$how = $_REQUEST['how'];
$will = $_REQUEST['will'];
$fun = $_REQUEST['fun'];
$kind = $_REQUEST['kind'];
$device = $_REQUEST['device'];
$study = $_REQUEST['study'];
$agree = $_REQUEST['agree'];
$text = "hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />" ;
fopen('/1.txt', "r");
fwrite('/1.txt',"hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />");
fclose('/1.txt');
}
```
do note that there is an "else" that includes all the aforementioned input fields that I used in the code , and that I am executing on localhost.
thanks | 2014/03/03 | [
"https://Stackoverflow.com/questions/22155827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2870449/"
] | You cannot write to it since you are opening it as read-only:
```
$handle = fopen('/1.txt', "r");
```
Instead:
```
$handle = fopen('/1.txt', "w"); // to write only, if you need to read and write use 'w+'
```
You also need to store fopen in a $handle so you can write to it later.
Documentation: <http://www.php.net/manual/en/function.fopen.php>
Now the first parameter for fwrite should be `$handle`:
```
fwrite($handle, "hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />");
```
Documentation: <http://www.php.net/manual/en/function.fwrite.php>
At the end you should also close with `$handle`:
```
fclose($handle);
```
Documentation: <http://www.php.net/manual/en/function.fclose.php> | Much simpler:
```
file_put_contents('/1.txt', $text);
``` |
22,155,827 | I am trying to write data into a txt file, but It won't work. there is no error. it just won't work.
here is the code
```
if (isset($_REQUEST['submit']))
{
$hour = $_REQUEST['hour'];
$family = $_REQUEST['family'];
$how = $_REQUEST['how'];
$will = $_REQUEST['will'];
$fun = $_REQUEST['fun'];
$kind = $_REQUEST['kind'];
$device = $_REQUEST['device'];
$study = $_REQUEST['study'];
$agree = $_REQUEST['agree'];
$text = "hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />" ;
fopen('/1.txt', "r");
fwrite('/1.txt',"hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />");
fclose('/1.txt');
}
```
do note that there is an "else" that includes all the aforementioned input fields that I used in the code , and that I am executing on localhost.
thanks | 2014/03/03 | [
"https://Stackoverflow.com/questions/22155827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2870449/"
] | You are opening the file as read-only, with the `r`use `w` instead. And you need to pass [`fwrite`](http://at2.php.net/fwrite) the return of `fopen` as first argument, not the filename:
```
$f = fopen('/1.txt', "w");
fwrite($f,"hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />");
fclose($f);
``` | You have to pass in a 'w' to write to a file.
```
$handle = fopen('/1.txt', "w");
```
Passing in 'r' makes it so you are opening a 'read-only' file. |
22,155,827 | I am trying to write data into a txt file, but It won't work. there is no error. it just won't work.
here is the code
```
if (isset($_REQUEST['submit']))
{
$hour = $_REQUEST['hour'];
$family = $_REQUEST['family'];
$how = $_REQUEST['how'];
$will = $_REQUEST['will'];
$fun = $_REQUEST['fun'];
$kind = $_REQUEST['kind'];
$device = $_REQUEST['device'];
$study = $_REQUEST['study'];
$agree = $_REQUEST['agree'];
$text = "hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />" ;
fopen('/1.txt', "r");
fwrite('/1.txt',"hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />");
fclose('/1.txt');
}
```
do note that there is an "else" that includes all the aforementioned input fields that I used in the code , and that I am executing on localhost.
thanks | 2014/03/03 | [
"https://Stackoverflow.com/questions/22155827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2870449/"
] | You are opening the file as read-only, with the `r`use `w` instead. And you need to pass [`fwrite`](http://at2.php.net/fwrite) the return of `fopen` as first argument, not the filename:
```
$f = fopen('/1.txt', "w");
fwrite($f,"hour :" . $hour . "<br />" . "family" . $family . "<br />" . "تطابفق با درس" . $how . "<br />" . "سرگرمی های غیر مجازی : " . $will . "<br />" . "نوع سرگرمی :" . $fun . "<br />" . "kind : " . $kind . "<br />" . "device " . $device . "<br />" . "اثیر بر درس" . $study . "<br />" . "کنترل " . $agree . "<br />");
fclose($f);
``` | Much simpler:
```
file_put_contents('/1.txt', $text);
``` |
18,304,672 | I am a C++ programmer and I am new to R. Somebody told me that using a for loop in R is a bad idea and that it is better to use `sapply`. I wrote the following code to calculate the probability of a [birthday coincidence](http://en.wikipedia.org/wiki/Birthday_problem):
```
prob <- 1 # prob of no coincidence
days <- 365
k <- 50 # how many people
probability <- numeric() #probability vector (empty right now)
for(i in 1:k){
prob <- (days - i + 1)/days * prob # Formula for no coincidence
probability[i] <- 1 - prob
}
```
How I can do the same thing with `sapply`? I want to do something like:
```
1 - sapply(1:length(m), function(x) prod(m[1:x]))
```
But how to use the formula for no coincidence of birthday? | 2013/08/18 | [
"https://Stackoverflow.com/questions/18304672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1664088/"
] | You could do:
```
m <- (days - seq_len(k) + 1) / days
probability <- 1 - sapply(seq_along(m), function(x) prod(m[1:x]))
```
but that would be missing on the useful `cumprod` function:
```
probability <- 1 - cumprod(m)
```
which will be a lot faster.
(Also gave you a peak at `seq_along` and `seq_len` which are more robust than `:` when dealing with zero-length vectors.) | For you specific question it's probably best to just use the built-in birthday probability calculator
```
sapply(1:50, pbirthday)
``` |
31,813,588 | I have got SDL2\_image library installed on /usr/include/SDL2 (in this directory I can find SDL\_image.h).
When I compile with CLion all works fine but, in the editor, either include and functions of SDL2\_image librarie appear with error (this library is found by the compiler but It is not found by the editor).
This is my CMake:
```
cmake_minimum_required(VERSION 3.2)
project(sdl)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp)
add_executable(sdl ${SOURCE_FILES} Game.cpp Game.h)
INCLUDE(FindPkgConfig)
PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2IMAGE REQUIRED SDL2_image>=2.0.0)
INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIRS})
TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARIES})
add_custom_command(TARGET sdl POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_SOURCE_DIR}/assets
$<TARGET_FILE_DIR:sdl>/assets)
```
What is the problem? | 2015/08/04 | [
"https://Stackoverflow.com/questions/31813588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4296783/"
] | Use this FindSDL2\_image.cmake file:
```
# Locate SDL2_image library
# This module defines
# SDL2_IMAGE_LIBRARY, the name of the library to link against
# SDL2_IMAGE_FOUND, if false, do not try to link to SDL2_image
# SDL2_IMAGE_INCLUDE_DIR, where to find SDL_image.h
#
# Additional Note: If you see an empty SDL2_IMAGE_LIBRARY_TEMP in your configuration
# and no SDL2_IMAGE_LIBRARY, it means CMake did not find your SDL2_Image library
# (SDL2_image.dll, libsdl2_image.so, SDL2_image.framework, etc).
# Set SDL2_IMAGE_LIBRARY_TEMP to point to your SDL2 library, and configure again.
# Similarly, if you see an empty SDL2MAIN_LIBRARY, you should set this value
# as appropriate. These values are used to generate the final SDL2_IMAGE_LIBRARY
# variable, but when these values are unset, SDL2_IMAGE_LIBRARY does not get created.
#
# $SDL2 is an environment variable that would
# correspond to the ./configure --prefix=$SDL2
# used in building SDL2.
# l.e.galup 9-20-02
#
# Modified by Eric Wing.
# Added code to assist with automated building by using environmental variables
# and providing a more controlled/consistent search behavior.
# Added new modifications to recognize OS X frameworks and
# additional Unix paths (FreeBSD, etc).
# Also corrected the header search path to follow "proper" SDL2 guidelines.
# Added a search for SDL2main which is needed by some platforms.
# Added a search for threads which is needed by some platforms.
# Added needed compile switches for MinGW.
#
# On OSX, this will prefer the Framework version (if found) over others.
# People will have to manually change the cache values of
# SDL2_IMAGE_LIBRARY to override this selection or set the CMake environment
# CMAKE_INCLUDE_PATH to modify the search paths.
#
# Note that the header path has changed from SDL2/SDL.h to just SDL.h
# This needed to change because "proper" SDL2 convention
# is #include "SDL.h", not <SDL2/SDL.h>. This is done for portability
# reasons because not all systems place things in SDL2/ (see FreeBSD).
#
# Ported by Johnny Patterson. This is a literal port for SDL2 of the FindSDL.cmake
# module with the minor edit of changing "SDL" to "SDL2" where necessary. This
# was not created for redistribution, and exists temporarily pending official
# SDL2 CMake modules.
#
# Note that on windows this will only search for the 32bit libraries, to search
# for 64bit change x86/i686-w64 to x64/x86_64-w64
#=============================================================================
# Copyright 2003-2009 Kitware, Inc.
#
# CMake - Cross Platform Makefile Generator
# Copyright 2000-2014 Kitware, Inc.
# Copyright 2000-2011 Insight Software Consortium
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the names of Kitware, Inc., the Insight Software Consortium,
# nor the names of their contributors may be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
FIND_PATH(SDL2_IMAGE_INCLUDE_DIR SDL_image.h
HINTS
${SDL2}
$ENV{SDL2}
$ENV{SDL2_IMAGE}
PATH_SUFFIXES include/SDL2 include SDL2
i686-w64-mingw32/include/SDL2
x86_64-w64-mingw32/include/SDL2
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local/include/SDL2
/usr/include/SDL2
/sw # Fink
/opt/local # DarwinPorts
/opt/csw # Blastwave
/opt
)
# Lookup the 64 bit libs on x64
IF(CMAKE_SIZEOF_VOID_P EQUAL 8)
FIND_LIBRARY(SDL2_IMAGE_LIBRARY_TEMP
NAMES SDL2_image
HINTS
${SDL2}
$ENV{SDL2}
$ENV{SDL2_IMAGE}
PATH_SUFFIXES lib64 lib
lib/x64
x86_64-w64-mingw32/lib
PATHS
/sw
/opt/local
/opt/csw
/opt
)
# On 32bit build find the 32bit libs
ELSE(CMAKE_SIZEOF_VOID_P EQUAL 8)
FIND_LIBRARY(SDL2_IMAGE_LIBRARY_TEMP
NAMES SDL2_image
HINTS
${SDL2}
$ENV{SDL2}
$ENV{SDL2_IMAGE}
PATH_SUFFIXES lib
lib/x86
i686-w64-mingw32/lib
PATHS
/sw
/opt/local
/opt/csw
/opt
)
ENDIF(CMAKE_SIZEOF_VOID_P EQUAL 8)
SET(SDL2_IMAGE_FOUND "NO")
IF(SDL2_IMAGE_LIBRARY_TEMP)
# Set the final string here so the GUI reflects the final state.
SET(SDL2_IMAGE_LIBRARY ${SDL2_IMAGE_LIBRARY_TEMP} CACHE STRING "Where the SDL2_image Library can be found")
# Set the temp variable to INTERNAL so it is not seen in the CMake GUI
SET(SDL2_IMAGE_LIBRARY_TEMP "${SDL2_IMAGE_LIBRARY_TEMP}" CACHE INTERNAL "")
SET(SDL2_IMAGE_FOUND "YES")
ENDIF(SDL2_IMAGE_LIBRARY_TEMP)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_IMAGE REQUIRED_VARS SDL2_IMAGE_LIBRARY SDL2_IMAGE_INCLUDE_DIR)
```
in my source tree I have a folder called cmake\_modules with the above find FindSDL2\_image.cmake file in there.
you can read the bottom of that .cmake file to see the library and include names to use: `FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_IMAGE REQUIRED_VARS SDL2_IMAGE_LIBRARY SDL2_IMAGE_INCLUDE_DIR)`
Then in my cmake file looks something like this:
```
PROJECT(project_name)
SET(SRC_FILES xxx.c xxx.c xxx.c xxx.c)
FIND_PACKAGE(SDL2 REQUIRED)
INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIR})
FIND_PACKAGE(OPENGL REQUIRED)
INCLUDE_DIRECTORIES( ${OPENGL_INCLUDE_DIR})
FIND_PACKAGE(SDL_IMAGE REQUIRED)
INCLUDE_DIRECTORIES( ${SDL2_IMAGE_INCLUDE_DIR})
ADD_LIBRARY(project_name SHARED ${SRC_FILES})
TARGET_LINK_LIBRARIES(project_name ${SDL2_LIBRARY} ${OPENGL_LIBRARIES} ${SDL2_IMAGE_LIBRARY})
``` | `FindPkgConfig` module invoke `pkg-config` command to get the link/compiler flags. In your case it's possible that the `pkg-config` does not find the settings, so CMake failed to get that information.
Please try opening the console/terminal (or msys, msys2, whatever you're using). Then calls `pkg-config SDL2_image --libs`. If it works properly you should see something like (I use MSYS2 on Windows, in other platform it would be a bit different) :-
```
$ pkg-config SDL2_image --libs
-LC:/msys64/mingw64/lib -lSDL2_image -lmingw32 -lSDL2main -lSDL2
```
Note: the command is case-sensitive.
If it does not work then you might have to update the pkgconfig file manually. This is different from systems to systems (the default on Linux is /usr/lib/pkgconfig , but again this could vary between distros). In worst case, you would have to write the pkgconfig file manually.
Anyway it would be better if you can specify what the operating system and platform you are currently working on. |
31,813,588 | I have got SDL2\_image library installed on /usr/include/SDL2 (in this directory I can find SDL\_image.h).
When I compile with CLion all works fine but, in the editor, either include and functions of SDL2\_image librarie appear with error (this library is found by the compiler but It is not found by the editor).
This is my CMake:
```
cmake_minimum_required(VERSION 3.2)
project(sdl)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp)
add_executable(sdl ${SOURCE_FILES} Game.cpp Game.h)
INCLUDE(FindPkgConfig)
PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2IMAGE REQUIRED SDL2_image>=2.0.0)
INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIRS})
TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARIES})
add_custom_command(TARGET sdl POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_SOURCE_DIR}/assets
$<TARGET_FILE_DIR:sdl>/assets)
```
What is the problem? | 2015/08/04 | [
"https://Stackoverflow.com/questions/31813588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4296783/"
] | Use this FindSDL2\_image.cmake file:
```
# Locate SDL2_image library
# This module defines
# SDL2_IMAGE_LIBRARY, the name of the library to link against
# SDL2_IMAGE_FOUND, if false, do not try to link to SDL2_image
# SDL2_IMAGE_INCLUDE_DIR, where to find SDL_image.h
#
# Additional Note: If you see an empty SDL2_IMAGE_LIBRARY_TEMP in your configuration
# and no SDL2_IMAGE_LIBRARY, it means CMake did not find your SDL2_Image library
# (SDL2_image.dll, libsdl2_image.so, SDL2_image.framework, etc).
# Set SDL2_IMAGE_LIBRARY_TEMP to point to your SDL2 library, and configure again.
# Similarly, if you see an empty SDL2MAIN_LIBRARY, you should set this value
# as appropriate. These values are used to generate the final SDL2_IMAGE_LIBRARY
# variable, but when these values are unset, SDL2_IMAGE_LIBRARY does not get created.
#
# $SDL2 is an environment variable that would
# correspond to the ./configure --prefix=$SDL2
# used in building SDL2.
# l.e.galup 9-20-02
#
# Modified by Eric Wing.
# Added code to assist with automated building by using environmental variables
# and providing a more controlled/consistent search behavior.
# Added new modifications to recognize OS X frameworks and
# additional Unix paths (FreeBSD, etc).
# Also corrected the header search path to follow "proper" SDL2 guidelines.
# Added a search for SDL2main which is needed by some platforms.
# Added a search for threads which is needed by some platforms.
# Added needed compile switches for MinGW.
#
# On OSX, this will prefer the Framework version (if found) over others.
# People will have to manually change the cache values of
# SDL2_IMAGE_LIBRARY to override this selection or set the CMake environment
# CMAKE_INCLUDE_PATH to modify the search paths.
#
# Note that the header path has changed from SDL2/SDL.h to just SDL.h
# This needed to change because "proper" SDL2 convention
# is #include "SDL.h", not <SDL2/SDL.h>. This is done for portability
# reasons because not all systems place things in SDL2/ (see FreeBSD).
#
# Ported by Johnny Patterson. This is a literal port for SDL2 of the FindSDL.cmake
# module with the minor edit of changing "SDL" to "SDL2" where necessary. This
# was not created for redistribution, and exists temporarily pending official
# SDL2 CMake modules.
#
# Note that on windows this will only search for the 32bit libraries, to search
# for 64bit change x86/i686-w64 to x64/x86_64-w64
#=============================================================================
# Copyright 2003-2009 Kitware, Inc.
#
# CMake - Cross Platform Makefile Generator
# Copyright 2000-2014 Kitware, Inc.
# Copyright 2000-2011 Insight Software Consortium
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the names of Kitware, Inc., the Insight Software Consortium,
# nor the names of their contributors may be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
FIND_PATH(SDL2_IMAGE_INCLUDE_DIR SDL_image.h
HINTS
${SDL2}
$ENV{SDL2}
$ENV{SDL2_IMAGE}
PATH_SUFFIXES include/SDL2 include SDL2
i686-w64-mingw32/include/SDL2
x86_64-w64-mingw32/include/SDL2
PATHS
~/Library/Frameworks
/Library/Frameworks
/usr/local/include/SDL2
/usr/include/SDL2
/sw # Fink
/opt/local # DarwinPorts
/opt/csw # Blastwave
/opt
)
# Lookup the 64 bit libs on x64
IF(CMAKE_SIZEOF_VOID_P EQUAL 8)
FIND_LIBRARY(SDL2_IMAGE_LIBRARY_TEMP
NAMES SDL2_image
HINTS
${SDL2}
$ENV{SDL2}
$ENV{SDL2_IMAGE}
PATH_SUFFIXES lib64 lib
lib/x64
x86_64-w64-mingw32/lib
PATHS
/sw
/opt/local
/opt/csw
/opt
)
# On 32bit build find the 32bit libs
ELSE(CMAKE_SIZEOF_VOID_P EQUAL 8)
FIND_LIBRARY(SDL2_IMAGE_LIBRARY_TEMP
NAMES SDL2_image
HINTS
${SDL2}
$ENV{SDL2}
$ENV{SDL2_IMAGE}
PATH_SUFFIXES lib
lib/x86
i686-w64-mingw32/lib
PATHS
/sw
/opt/local
/opt/csw
/opt
)
ENDIF(CMAKE_SIZEOF_VOID_P EQUAL 8)
SET(SDL2_IMAGE_FOUND "NO")
IF(SDL2_IMAGE_LIBRARY_TEMP)
# Set the final string here so the GUI reflects the final state.
SET(SDL2_IMAGE_LIBRARY ${SDL2_IMAGE_LIBRARY_TEMP} CACHE STRING "Where the SDL2_image Library can be found")
# Set the temp variable to INTERNAL so it is not seen in the CMake GUI
SET(SDL2_IMAGE_LIBRARY_TEMP "${SDL2_IMAGE_LIBRARY_TEMP}" CACHE INTERNAL "")
SET(SDL2_IMAGE_FOUND "YES")
ENDIF(SDL2_IMAGE_LIBRARY_TEMP)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_IMAGE REQUIRED_VARS SDL2_IMAGE_LIBRARY SDL2_IMAGE_INCLUDE_DIR)
```
in my source tree I have a folder called cmake\_modules with the above find FindSDL2\_image.cmake file in there.
you can read the bottom of that .cmake file to see the library and include names to use: `FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_IMAGE REQUIRED_VARS SDL2_IMAGE_LIBRARY SDL2_IMAGE_INCLUDE_DIR)`
Then in my cmake file looks something like this:
```
PROJECT(project_name)
SET(SRC_FILES xxx.c xxx.c xxx.c xxx.c)
FIND_PACKAGE(SDL2 REQUIRED)
INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIR})
FIND_PACKAGE(OPENGL REQUIRED)
INCLUDE_DIRECTORIES( ${OPENGL_INCLUDE_DIR})
FIND_PACKAGE(SDL_IMAGE REQUIRED)
INCLUDE_DIRECTORIES( ${SDL2_IMAGE_INCLUDE_DIR})
ADD_LIBRARY(project_name SHARED ${SRC_FILES})
TARGET_LINK_LIBRARIES(project_name ${SDL2_LIBRARY} ${OPENGL_LIBRARIES} ${SDL2_IMAGE_LIBRARY})
``` | depends what compiler you are using, and maybe other factors, depending on what error you are getting exactly.
on your
`TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARIES})`
you might need more linkers or they might not be picking up correctly for some reason.
mine looks about like this for a similar project
`target_link_libraries(${PROJECT_NAME} -lmingw32 -lSDL2main -lSDL2 -lSDL2_image)`
using the mingw compiler, and it seems to work okay. |
28,023,726 | showing error when trying to get date from Sql server which is in the format like 1986-02-02 00:00:00.0000000. need to display in dd/MM/yyyy format. working fine with format like 2015-01-14.tried different ways but didn't work. pls help.
```
//c#
string dt = reader[6].ToString();
dob_lbl.Text = DateTime.ParseExact(dt, "M/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
```
error:string was not recognised as a valid DateTime | 2015/01/19 | [
"https://Stackoverflow.com/questions/28023726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4442557/"
] | change this becuase your input string does not match the pattern that you are passing in to the parser
```
"M/dd/yyyy hh:mm:ss tt"
```
to
```
"yyyy/mm/dd hh:mm:ss tt"
```
So like this
```
dob_lbl.Text = DateTime.ParseExact(dt, "yyyy/mm/dd hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
``` | At first you should get the data as recogniced sqlDateTime by using
```
DateTime dt = reader.GetDateTime(6);
```
Now `dt.ToString("dd/MM/yyyy");` should work. |
28,023,726 | showing error when trying to get date from Sql server which is in the format like 1986-02-02 00:00:00.0000000. need to display in dd/MM/yyyy format. working fine with format like 2015-01-14.tried different ways but didn't work. pls help.
```
//c#
string dt = reader[6].ToString();
dob_lbl.Text = DateTime.ParseExact(dt, "M/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
```
error:string was not recognised as a valid DateTime | 2015/01/19 | [
"https://Stackoverflow.com/questions/28023726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4442557/"
] | change this becuase your input string does not match the pattern that you are passing in to the parser
```
"M/dd/yyyy hh:mm:ss tt"
```
to
```
"yyyy/mm/dd hh:mm:ss tt"
```
So like this
```
dob_lbl.Text = DateTime.ParseExact(dt, "yyyy/mm/dd hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");
``` | *Clearly*, your string and format doesn't match.
Use `yyyy-MM-dd HH:mm:ss.fffffff` format instead when you parse `1986-02-02 00:00:00.0000000` string.
```
string s = "1986-02-02 00:00:00.0000000";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss.fffffff", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture).Dump(); // 02/02/1986
}
```
##But more important
I suspect you keep your `DateTime` values as characters. **Don't do that!** Use proper type always.
Read: [Bad habits to kick : choosing the wrong data type](https://sqlblog.org/2009/10/12/bad-habits-to-kick-choosing-the-wrong-data-type)
If you keep your value a `datetime`, just use [`GetDateTime` metho](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getdatetime%28v=vs.110%29.aspx)d to get it as a `DateTime` and use `.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)` to get it's string representation. |
22,527,173 | I have a script that sends an email, but instead of the sender name being "admin@foo.bar", I want it to say "Foobar Admin". How can I do this?
Thanks! | 2014/03/20 | [
"https://Stackoverflow.com/questions/22527173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2228694/"
] | ```
/^[a-zA-Z\s\-\'\"]*$/
```
use this.
This will contain any alphabet([upper/lower]case)
,space,
hiphen,
",
'
**update**
If you are using it inside NSPredicate
then make sure that you put the `-` in the end, as it throws error.
Move it to the end of the sequence to be the last character before the closing square bracket `]`.
like this `[a-zA-Z '"-]` | Maybe try this:
```
\b[a-zA-Z \-\']+\b
```
<http://regex101.com/r/oQ5nU9> |
22,527,173 | I have a script that sends an email, but instead of the sender name being "admin@foo.bar", I want it to say "Foobar Admin". How can I do this?
Thanks! | 2014/03/20 | [
"https://Stackoverflow.com/questions/22527173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2228694/"
] | ```
/^[a-zA-Z\s\-\'\"]*$/
```
use this.
This will contain any alphabet([upper/lower]case)
,space,
hiphen,
",
'
**update**
If you are using it inside NSPredicate
then make sure that you put the `-` in the end, as it throws error.
Move it to the end of the sequence to be the last character before the closing square bracket `]`.
like this `[a-zA-Z '"-]` | If you want only the alphabets and space, `'` and `-` then:
```
/^[-a-zA-Z\s\']+$/
```
Notice the `+` from above instead of `*`. If you use `*` then it will match with empty string, where the `+` sign means to have at least one character in your input.
Now, if you want to match any alphabets with any special characters(not only those three which are mentioned), then I'll just you to use this one:
```
/^\D+$/
```
It means any characters other than digits! |
22,527,173 | I have a script that sends an email, but instead of the sender name being "admin@foo.bar", I want it to say "Foobar Admin". How can I do this?
Thanks! | 2014/03/20 | [
"https://Stackoverflow.com/questions/22527173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2228694/"
] | ```
/^[a-zA-Z\s\-\'\"]*$/
```
use this.
This will contain any alphabet([upper/lower]case)
,space,
hiphen,
",
'
**update**
If you are using it inside NSPredicate
then make sure that you put the `-` in the end, as it throws error.
Move it to the end of the sequence to be the last character before the closing square bracket `]`.
like this `[a-zA-Z '"-]` | You can use it defiantly work it
```
[a-zA-Z._^%$#!~@,-]+
```
this code work fine you can try it.... |
22,527,173 | I have a script that sends an email, but instead of the sender name being "admin@foo.bar", I want it to say "Foobar Admin". How can I do this?
Thanks! | 2014/03/20 | [
"https://Stackoverflow.com/questions/22527173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2228694/"
] | ```
/^[a-zA-Z\s\-\'\"]*$/
```
use this.
This will contain any alphabet([upper/lower]case)
,space,
hiphen,
",
'
**update**
If you are using it inside NSPredicate
then make sure that you put the `-` in the end, as it throws error.
Move it to the end of the sequence to be the last character before the closing square bracket `]`.
like this `[a-zA-Z '"-]` | //Use this for allowing space as we all as other special character.
@"[a-zA-Z\\s\\-\\'\\"]"
//Following link will be help for further.
<http://www.raywenderlich.com/30288/nsregularexpression-tutorial-and-cheat-sheet> |
22,527,173 | I have a script that sends an email, but instead of the sender name being "admin@foo.bar", I want it to say "Foobar Admin". How can I do this?
Thanks! | 2014/03/20 | [
"https://Stackoverflow.com/questions/22527173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2228694/"
] | ```
/^[a-zA-Z\s\-\'\"]*$/
```
use this.
This will contain any alphabet([upper/lower]case)
,space,
hiphen,
",
'
**update**
If you are using it inside NSPredicate
then make sure that you put the `-` in the end, as it throws error.
Move it to the end of the sequence to be the last character before the closing square bracket `]`.
like this `[a-zA-Z '"-]` | Thanks for your response.. I finally resolved it with this
NSString *characterRegex = @"^(\s*[a-zA-Z]+(([\'\-\+\s]\s\*[a-zA-Z])?[a-zA-Z]*)\s*)+$";
NSPredicate \*characterTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",characterRegex];
return [characterTest evaluateWithObject:inputString]; |
191,580 | This is a follow-up question to the one posted here:
[Random walking and the expected value](https://math.stackexchange.com/questions/191518/random-walking-and-the-expected-value)
I want to generalize the probability.... lets say walking to the neighbour in the clockwise direction is p ,and the counter clockwise is 1-p.
Any help would be greatly appreciated
Thanks | 2012/09/05 | [
"https://math.stackexchange.com/questions/191580",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/39563/"
] | The answer is still 4, because (by the symmetry) the invariant distribution of the Markov chain is still uniform, and the mean time to return to the node is the reciprocal of the corresponding component of the invariant distribution vector, $\mathbb{E}(T\_1) = \frac{1}{\pi\_1} = 4$.
Alternatively, let $m\_k$ denote the mean number of transitions until visiting node 1. Conditioning on the next step:
$$
m\_2 = 1 + p m\_3, \quad m\_3 = 1 + (1-p) m\_2 + p m\_4, \quad m\_4 = 1 + (1-p) m\_3
$$
Which gives:
$$
m\_2 = 1 + \frac{2p}{1-2p(1-p)}, \quad m\_3 = \frac{2}{1-2p(1-p)}, \quad m\_4 = 1 + \frac{2(1-p)}{1-2p(1-p)}
$$
The mean time to return to node 1 is:
$$
1 + (1-p) m\_4 + p m\_2 = 1 + 1 + \frac{2}{1-2p(1-p)}\left((1-p)^2 + p^2\right) = 4
$$ | Let $e$ be the desired expectation. Let $a\_2$, $a\_3$, $a\_4$ be the expected time until one returns to vertex $1$, given that we are at $2$, $3$, $4$ respectively.
We have the following equations:
$e=1+ pa\_2+(1-p)a\_4$; This is because we take $1$ step, and enter State $2$ with probability $p$, and State $4$ with probability $1-p$.
$a\_2=1+pa\_3$; one step backwards and it's over, else we are in State $3$. This happens with probability $p$.
$a\_3=1+pa\_4+(1-p)a\_2$;
$a\_4=1+(1-p)a\_3$.
Four linear equations in four unknowns: solve. |
39,306,131 | I am sending a link like below
```
users/reset?token=0272dcff7439023e082204ac9fe9b96b
```
Where `token = user_email`
In controller after get token, I am trying to match this string with database email field.
I have tried by below code , but here query not working
```
public function search(){
if($this->request->is(['post','get'])){
$email = $this->request->query('token');
$query = $this->Users->find('all', [
'conditions' => [md5('Users.email') =>$email],
'fields' => ['email','username']
]);
}
```
How can I match this md5 or base\_64 string with email field in cake query ? | 2016/09/03 | [
"https://Stackoverflow.com/questions/39306131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3081630/"
] | If you **have** to use `switch` you should bring the `if else` statements outside of your `switch` in order to switch over a proper integer value. Something like this:
```
int state = 0;
if ( grade < 101 && grade >= 95 )
state = 1;
else if ( grade < 101 && grade >= 85 )
state = 2;
switch state {
case 1:
printf("A+");
break;
case 2:
printf("A");
break;
default:
printf("invalid");
break;
}
``` | You can express this with switch statements in the following way (though you probably do not want to):
```
switch(grade)
{
case 100:
case 99:
case 98:
case 97:
case 96:
case 95:
printf("A+");
break;
case 94:
case 93:
case 92:
case 91:
case 90:
case 89:
case 88:
case 87:
case 86:
case 85:
printf("A");
break;
default:
printf("Invalid");
//or an if statement if more options are required.
break;
}
``` |
52,016,746 | I'm trying to change cache driver from **file** to **redis** or **apc**, but everytime when I said `dd(\Cache::getDefaultDriver());` it gives me that "file" as default cache driver.
I cleared config and stored cache, but it still continue..
```
php artisan config:cache
php artisan cache:clear
```
in my config/cache.php
```
'default' => env('CACHE_DRIVER', 'redis'),
```
What should I do ? I'm working on local and my laravel version is 5.6 | 2018/08/25 | [
"https://Stackoverflow.com/questions/52016746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9714376/"
] | please change
>
> CACHE\_DRIVER = redis
>
>
>
in `.env`
to redis and again run `php artisan serve` | 1) `composer require predis/predis`
2) in `config/database.php` paste these codes below..
```
'redis' => [
'client' => 'predis',
'default' => [
'host' => env('REDIS_HOST', 'localhost'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
],
```
3) CACHE\_DRIVER=redis in .env file |
22,582,312 | Confirming that every time you call Akka.system.actorOf or Akka.system.scheduler it'll create a new ActorSystem in the application? Looking at some code where it calls Akka.system.actorOf every time it has to create a new actor, which I think should have been context.actorOf to use the existing ActorSystem (which should have been created at the app startup). Is my understanding correct that calling Akka.system.actorOf every single time, to create a new actor, is very wrong? | 2014/03/22 | [
"https://Stackoverflow.com/questions/22582312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2066049/"
] | According to the docs:
>
> Using the ActorSystem will create top-level actors, supervised by the
> actor system’s provided guardian actor, while using an actor’s context
> will create a child actor.
>
>
>
So basically, it depends on what you want to achieve.
More details [here](http://doc.akka.io/docs/akka/snapshot/scala/actors.html).
EDIT:
Concerning your concrete question (I am sorry, I misunderstood you), you should see an `ActorSystem` as a heavyweight structure that will allocate up to N threads, and each Actor will run within one of these threads (the key point here is that there is no mutable state). ActorSystems share common configuration, e.g. dispatchers, deployments, remote capabilities and addresses. They are also the entry point for creating or looking up actors.
Creating an `ActorSystem` is very expensive, so you want to avoid creating a new one each time you need it. Also your actors should run in the same `ActorSystem`, unless there is a good reason for them not to. The name of the `ActorSystem` is also part the the path to the actors that run in it.
There is no `Akka.system.actorOf` method in the current API. Normally you hold a reference to the application `ActorSystem` as others already showed you, and create child actors from that context:
```
val system = akka.actor.ActorSystem("YourApplication");
val actor1 = system.actorOf(Props[Actor1], "Actor1")
val actor2 = system.actorOf(Props[Actor2], "Actor2")
```
So, in short, I have never tried it but I assume every call to `akka.actor.ActorSystem` will try to create a new ActorSystem and it would probably fail if no different ActorSystem names/configurations are provided. | You can only have one ActorSystem in a Cluster. thats why you cant use new.
Something very similar to main..
trying to learn by answering to it. |
22,582,312 | Confirming that every time you call Akka.system.actorOf or Akka.system.scheduler it'll create a new ActorSystem in the application? Looking at some code where it calls Akka.system.actorOf every time it has to create a new actor, which I think should have been context.actorOf to use the existing ActorSystem (which should have been created at the app startup). Is my understanding correct that calling Akka.system.actorOf every single time, to create a new actor, is very wrong? | 2014/03/22 | [
"https://Stackoverflow.com/questions/22582312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2066049/"
] | You create new `ActorSystem` *only* when you call `ActorSystem.apply` method:
```
val system = ActorSystem("YourApplication")
```
Of course, when you call methods on the system you *do not* create new systems, that is, the following:
```
val actor = system.actorOf(Props[SomeActor], "someActor")
```
won't create new system, it will just create new *top-level* actor in the `system`. You usually call `system.actorOf` method when you are outside of an actor, for example, in initialization code when there are no actors created yet.
`context`, on the other hand, is a way to interact with the system *from inside* an actor. `context` is a member of `Actor` trait, which is inherited into your actors. You use `context` to access actor system's scheduler, to watch actors, to create child actors, to change actor's behavior etc. `context.actorOf` will create *child* actor.
So no, calling `system.actorOf` for creating actors is absolutely *not wrong*. You just have to keep in mind that when you use `system.actorOf` you're creating top-level actors, and that's not something you need *always*. Usually you create one or several top-level actors, which then in turn create child actors and so on. | You can only have one ActorSystem in a Cluster. thats why you cant use new.
Something very similar to main..
trying to learn by answering to it. |
37,320,817 | I have an ASP.NET web application which is connected to SQL Server.
I have used three connections for each SQL operation. It works very well, however I think this is not an efficient way to do things - can this be written better than it is?
```
public partial class Home : System.Web.UI.Page
{
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
co.Close();
using (con)
{
con.Open();
SqlCommand cmv = con.CreateCommand();
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
con.Close();
using (con2)
{
con2.Open();
SqlCommand cmf = con2.CreateCommand();
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
con2.Close();
}
}
``` | 2016/05/19 | [
"https://Stackoverflow.com/questions/37320817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6278437/"
] | ```
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.CommandText += " insert...";
cm.CommandText += " delete from...";
cm.ExecuteNonQuery();
}
co.Close();
}
```
you can use like this. | You're using the same connection string for each connection? Why do you need three connections? Why not just open and close the same one?
As long as the connection string is the same, you only need one connection. |
37,320,817 | I have an ASP.NET web application which is connected to SQL Server.
I have used three connections for each SQL operation. It works very well, however I think this is not an efficient way to do things - can this be written better than it is?
```
public partial class Home : System.Web.UI.Page
{
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
co.Close();
using (con)
{
con.Open();
SqlCommand cmv = con.CreateCommand();
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
con.Close();
using (con2)
{
con2.Open();
SqlCommand cmf = con2.CreateCommand();
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
con2.Close();
}
}
``` | 2016/05/19 | [
"https://Stackoverflow.com/questions/37320817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6278437/"
] | You're using the same connection string for each connection? Why do you need three connections? Why not just open and close the same one?
As long as the connection string is the same, you only need one connection. | You can also try this.
```
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(" Select statement.. ");
sb.AppendLine(" Insert statement ");
sb.AppendLine(" delete statement ");
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = sb.Tostring();
cm.ExecuteNonQuery();
}
co.Close();
}
``` |
37,320,817 | I have an ASP.NET web application which is connected to SQL Server.
I have used three connections for each SQL operation. It works very well, however I think this is not an efficient way to do things - can this be written better than it is?
```
public partial class Home : System.Web.UI.Page
{
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
co.Close();
using (con)
{
con.Open();
SqlCommand cmv = con.CreateCommand();
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
con.Close();
using (con2)
{
con2.Open();
SqlCommand cmf = con2.CreateCommand();
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
con2.Close();
}
}
``` | 2016/05/19 | [
"https://Stackoverflow.com/questions/37320817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6278437/"
] | ```
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.CommandText += " insert...";
cm.CommandText += " delete from...";
cm.ExecuteNonQuery();
}
co.Close();
}
```
you can use like this. | *In general* you should prefer to create and open a connection object as close to where you make use of it as possible, and dispose of it as soon as possible afterwards (preferably by making use of a `using` statement). Connection pooling will take care of ensuring you only actually create a limited number of *real* connections to the server, despite the large number of `SqlConnection` objects your code may seem to create.
Within a *single* method, however, it is reasonable to use a single connection object:
```
public partial class Home : System.Web.UI.Page
{
string connString = ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString;
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection co = new SqlConnection(connString))
{
co.Open();
using(SqlCommand cm = co.CreateCommand())
{
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
using(SqlCommand cmv = co.CreateCommand())
{
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
using(SqlCommand cmf = co.CreateCommand())
{
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
}
}
}
```
(You don't need to explicitly close the connection object, the `Dispose` (within the `using` is equivalent) |
37,320,817 | I have an ASP.NET web application which is connected to SQL Server.
I have used three connections for each SQL operation. It works very well, however I think this is not an efficient way to do things - can this be written better than it is?
```
public partial class Home : System.Web.UI.Page
{
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
co.Close();
using (con)
{
con.Open();
SqlCommand cmv = con.CreateCommand();
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
con.Close();
using (con2)
{
con2.Open();
SqlCommand cmf = con2.CreateCommand();
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
con2.Close();
}
}
``` | 2016/05/19 | [
"https://Stackoverflow.com/questions/37320817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6278437/"
] | ```
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.CommandText += " insert...";
cm.CommandText += " delete from...";
cm.ExecuteNonQuery();
}
co.Close();
}
```
you can use like this. | 1. No use declaring/creating multiple connections when you would be using only one at a time. You can do with just one.
2. Declare variable as close as possible to its first use, and with minimum scope manageable.
3. Make things modular and reusable as far as possible.
4. No need to explicitly close the connection, since the IDisposable interface implementation (and `using` block) does it anyways. But there is no harm in explicitly closing it.
---
```
protected void Button1_Click(object sender, EventArgs e)
{
ExecuteNonQuery("select...", null); // why??
ExecuteNonQuery("insert...", null);
ExecuteNonQuery("delete from...", null);
}
protected void ExecuteNonQuery(string query, SqlParameter[] parameters)
{
using (SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString))
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = query;
if (parameters != null) cm.Parameters.AddRange(parameters);
cm.ExecuteNonQuery();
}
}
``` |
37,320,817 | I have an ASP.NET web application which is connected to SQL Server.
I have used three connections for each SQL operation. It works very well, however I think this is not an efficient way to do things - can this be written better than it is?
```
public partial class Home : System.Web.UI.Page
{
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
co.Close();
using (con)
{
con.Open();
SqlCommand cmv = con.CreateCommand();
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
con.Close();
using (con2)
{
con2.Open();
SqlCommand cmf = con2.CreateCommand();
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
con2.Close();
}
}
``` | 2016/05/19 | [
"https://Stackoverflow.com/questions/37320817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6278437/"
] | ```
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.CommandText += " insert...";
cm.CommandText += " delete from...";
cm.ExecuteNonQuery();
}
co.Close();
}
```
you can use like this. | You can also try this.
```
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(" Select statement.. ");
sb.AppendLine(" Insert statement ");
sb.AppendLine(" delete statement ");
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = sb.Tostring();
cm.ExecuteNonQuery();
}
co.Close();
}
``` |
37,320,817 | I have an ASP.NET web application which is connected to SQL Server.
I have used three connections for each SQL operation. It works very well, however I think this is not an efficient way to do things - can this be written better than it is?
```
public partial class Home : System.Web.UI.Page
{
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
co.Close();
using (con)
{
con.Open();
SqlCommand cmv = con.CreateCommand();
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
con.Close();
using (con2)
{
con2.Open();
SqlCommand cmf = con2.CreateCommand();
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
con2.Close();
}
}
``` | 2016/05/19 | [
"https://Stackoverflow.com/questions/37320817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6278437/"
] | *In general* you should prefer to create and open a connection object as close to where you make use of it as possible, and dispose of it as soon as possible afterwards (preferably by making use of a `using` statement). Connection pooling will take care of ensuring you only actually create a limited number of *real* connections to the server, despite the large number of `SqlConnection` objects your code may seem to create.
Within a *single* method, however, it is reasonable to use a single connection object:
```
public partial class Home : System.Web.UI.Page
{
string connString = ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString;
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection co = new SqlConnection(connString))
{
co.Open();
using(SqlCommand cm = co.CreateCommand())
{
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
using(SqlCommand cmv = co.CreateCommand())
{
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
using(SqlCommand cmf = co.CreateCommand())
{
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
}
}
}
```
(You don't need to explicitly close the connection object, the `Dispose` (within the `using` is equivalent) | You can also try this.
```
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(" Select statement.. ");
sb.AppendLine(" Insert statement ");
sb.AppendLine(" delete statement ");
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = sb.Tostring();
cm.ExecuteNonQuery();
}
co.Close();
}
``` |
37,320,817 | I have an ASP.NET web application which is connected to SQL Server.
I have used three connections for each SQL operation. It works very well, however I think this is not an efficient way to do things - can this be written better than it is?
```
public partial class Home : System.Web.UI.Page
{
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
co.Close();
using (con)
{
con.Open();
SqlCommand cmv = con.CreateCommand();
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
con.Close();
using (con2)
{
con2.Open();
SqlCommand cmf = con2.CreateCommand();
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
con2.Close();
}
}
``` | 2016/05/19 | [
"https://Stackoverflow.com/questions/37320817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6278437/"
] | 1. No use declaring/creating multiple connections when you would be using only one at a time. You can do with just one.
2. Declare variable as close as possible to its first use, and with minimum scope manageable.
3. Make things modular and reusable as far as possible.
4. No need to explicitly close the connection, since the IDisposable interface implementation (and `using` block) does it anyways. But there is no harm in explicitly closing it.
---
```
protected void Button1_Click(object sender, EventArgs e)
{
ExecuteNonQuery("select...", null); // why??
ExecuteNonQuery("insert...", null);
ExecuteNonQuery("delete from...", null);
}
protected void ExecuteNonQuery(string query, SqlParameter[] parameters)
{
using (SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString))
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = query;
if (parameters != null) cm.Parameters.AddRange(parameters);
cm.ExecuteNonQuery();
}
}
``` | You can also try this.
```
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(" Select statement.. ");
sb.AppendLine(" Insert statement ");
sb.AppendLine(" delete statement ");
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = sb.Tostring();
cm.ExecuteNonQuery();
}
co.Close();
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.