date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/17
| 867 | 3,245 |
<issue_start>username_0: I am facing the problem that once I `import` vue, the wrapper element for vue (in my case `#app`) will be replaced with the following comment
```
```
There is no error in the console and webpack compiles fine, I do however get the console log from vue's `mounted` method.
My index.html
```
Document
some content
============
{{test}}
```
webpack.config.js
```
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
}
```
src/app.js
```
import Vue from 'vue'
const app = new Vue({
el: "#app",
data: {
test: "asdf"
},
mounted() {
console.log('mounted')
}
})
```<issue_comment>username_1: You are running a runtime-only build without the template compiler.
Check out <https://v2.vuejs.org/v2/guide/installation.html#Webpack>
You need to create an alias for 'vue', so webpack includes the correct vue/dist/\*.js from your node\_modules/:
```
module.exports = {
// ...
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
}
}
```
See also <https://forum.vuejs.org/t/what-is-the-compiler-included-build/13239>
Upvotes: 5 [selected_answer]<issue_comment>username_2: While username_1's answer is functional, including the template compiler isn't generally required for production builds. I would say it is likely undesired, as there will likely be performance impacts from building templates dynamically, which I assume is the case in this answer. Furthermore, it looks like username_1's answer includes the full development version of Vue in the production build, which should be discouraged because of all of the [extra content included in this version](https://v2.vuejs.org/v2/guide/deployment.html#Turn-on-Production-Mode). Instead, it is possible to [pre-compile templates](https://v2.vuejs.org/v2/guide/deployment.html#Pre-Compiling-Templates) during the build step.
The easiest method of doing this is to use single-file components (SFCs), as described in the previous link:
>
> [The] associated build setups automatically performs pre-compilation for
> you, so the built code contains the already compiled render functions
> instead of raw template strings.
>
>
>
Another method, which I needed to use for my own situation, is to define an explicit `render` function instead of a `template` for the component definition, so a compilation isn't required. I needed this because the Vue project I had generated at the time used SFCs for all of its components, except for the root "mounting" component, which was defined explicitly using the following object:
```
new Vue({
el: '#app',
store,
router,
components: { App },
template: ''
})
```
This worked fine in development mode, but failed in production with the "function comment" issue you were experiencing. Taking the insight from username_1's answer, I replaced the above snippet with the following:
```
new Vue({
el: '#app',
store,
router,
components: { App },
render: (h) => {
return h(App)
}
})
```
This resolved the issue on my production version without requiring me to include the full development version of Vue.
Upvotes: 3
|
2018/03/17
| 480 | 1,708 |
<issue_start>username_0: I have code:
```js
var box = document.querySelectorAll("div");
box.forEach(function(element) {
element.onclick = function() {
alert(this.innerText);
}
});
```
```html
A
B
```
When I click Box B, I just want to show "B" not "AB". Any ideas?<issue_comment>username_1: **1.solution:** You could cancel all other events using `event.stopPropagation();` Have a look at the [jQuery docs](https://api.jquery.com/event.stoppropagation/).
*event.stopPropagation-Description*: `Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.`
```js
var box = document.querySelectorAll("div");
box.forEach(function(element) {
element.onclick = function(event) {
event.stopPropagation();
alert(this.innerText);
}
});
```
```html
A
B
```
**2. solution:** You could of course also use the method to separate the two div elements like this:
```js
var box = document.querySelectorAll("div");
box.forEach(function(element) {
element.onclick = function() {
alert(this.innerText);
}
});
```
```html
A
B
```
Upvotes: 0 <issue_comment>username_2: Use `event.stopPropagation()` which stops the click event from bubbling to parent element like the following:
```js
var box = document.querySelectorAll("div");
box.forEach(function(element) {
element.onclick = function(event) {
event.stopPropagation();
alert(this.innerText);
}
});
```
```html
A
B
```
Upvotes: 1 <issue_comment>username_1: I think this is your need.
```js
function a(div) {
alert(div.innerHTML);
}
```
```html
A
B
```
Upvotes: 0
|
2018/03/17
| 2,959 | 8,792 |
<issue_start>username_0: Given a markup:
```
dl
dt
dd
dd
..
dt
dd
dd
...
```
I'm trying to achieve the following layout with CSS grid:
```
dt dt
dd dd dd dd
dd dd dd dd
dd dd dd dd
dd dd dd dd
```
My current approach is:
```css
.time-table {
display: grid;
grid-gap: 1em;
grid-template-columns: repeat(4, 1fr);
grid-template-areas:
"destination1 destination1 destination2 destination2"
"time time time time";
list-style: none;
padding: 0;
}
.time-table__time {
background-color: #34ace0;
display: block;
color: #fff;
margin: 0;
grid-area: time;
}
.time-table__destination::before {
content: '\021D2';
display: inline-block;
transform: translateX(-5px);
}
.time-table__destination1 {
grid-area: destination1;
}
.time-table__destination2 {
grid-area: destination2;
}
@media (max-width: 35em) {
.time-table {
grid-template-columns: repeat(2, 1fr);
grid-template-areas:
"destination1 destination2"
"time time";
}
.time-table__destination::before {
transform: translateX(-5px);
}
}
```
```html
Metsakooli
23:22
23:32
23:42
23:52
00:02
Männiku
23:27
23:37
23:47
23:57
00:07
```
Or without using grid's template areas:
```css
.time-table {
display: grid;
grid-gap: 1em;
grid-template-columns: repeat(4, 1fr);
list-style: none;
padding: 0;
}
.time-table__time {
background-color: #34ace0;
display: block;
color: #fff;
margin: 0;
}
.time-table__destination::before {
content: '\021D2';
display: inline-block;
transform: translateX(-5px);
}
@media (max-width: 35em) {
.time-table {
grid-template-columns: repeat(2, 1fr);
grid-template-areas:
"destination1 destination2"
"time time";
}
.time-table__destination::before {
transform: translateX(-5px);
}
}
```
```html
Metsakooli
23:22
23:32
23:42
23:52
00:02
Männiku
23:27
23:37
23:47
23:57
00:07
```
But as you can see, the first approach fails to render the different times under the appropriate route title. The second approach creates the rows, but doesn't list them in the correct order and fails to hoist the second title (). My questions are:
- How can I make the times () appear under their respective destination/route?
- Is there a more elegant way to have the first row's cells span 2 columns and have the rest of the elements take the place of grid area `time`, like using `grid-auto-rows`? (I bet there is...)<issue_comment>username_1: The problem with the HTML that you've provided is that there's no way of associating the elements with a unique element, under which the `.time-table__time` elements should be aligned.
It is possible, with JavaScript, to take advantage of the `order` property to provide that visual identity, but it's an overwrought solution to a problem that can be better solved by changing the HTML.
The problem with using the `grid-template-areas` is, as you've found, that you create a named area that spans four columns; and all the elements are placed in that one named area.
The revised HTML, below, uses two elements, each with its own and descendants to uniquely associate the two together; those elements are themselves wrapped in `-` elements, themselves the children of an element. This is because the HTML you're showing – without context – *seems* to be an ordered list of destinations.
I was tempted to change the elements themselves into elements, given that they seem to be ordered lists of times, albeit with a title. However, semantics aside, the following is my suggestion of how you can produce your apparent requirements:
```css
/* Setting the margin and padding of all
elements to zero: */
*,
::before,
::after {
margin: 0;
padding: 0;
}
/* Adjust to taste: */
html,
body {
background-color: #fff;
}
/* Defining a custom CSS Property for
later use: */
:root {
--numParentColumns: 2;
}
/* Removing default list-styling: */
ol,
li,
dl,
dt,
dd {
list-style-type: none;
}
ol {
/* Setting the display type of the element
to that of 'grid': \*/
display: grid;
/\* Defining the grid columns, using the previously-
defined --numParentColumns variable to supply the
integer to the repeat() function, and setting each
column to the width of 1fr: \*/
grid-template-columns: repeat(var(--numParentColumns), 1fr);
/\* Adjust to taste: \*/
width: 90vw;
grid-column-gap: 0.5em;
margin: 0 auto;
}
ol>li dl {
/\* Setting the elements' display to 'grid': \*/
display: grid;
/\* Defining the number of grid columns to that value
held in the --numParentColumns variable, retaining
the 1fr width: \*/
grid-template-columns: repeat(var(--numParentColumns), 1fr);
grid-column-gap: 0.25em;
}
dt.time-table\_\_destination {
/\* Rather than using specific named grid-areas
here we place the elements in column 1
and span 2 columns: \*/
grid-column: 1 / span 2;
background-color: limegreen;
}
dt.time-table\_\_destination::before {
content: '\021D2';
margin: 0 1em 0 0;
}
dd.time-table\_\_time {
background-color: #34ace0;
}
/\* in displays where the width is at, or below,
35em we update some properties: \*/
@media (max-width: 35em) {
dd.time-table\_\_time {
/\* Here we place the elements in the
first column and have them span 2
columns: \*/
grid-column: 1 / span 2;
}
}
/\* At page-widths less than 15em (not mentioned in
the question): \*/
@media (max-width: 15em) {
/\* We update the --numParentColumns variable to
1, as a tangential demonstration of how useful
CSS custom properties can be: \*/
:root {
--numParentColumns: 1;
}
}
```
```html
1. Metsakooli
23:22
23:32
23:42
23:52
00:02
2. Männiku
23:27
23:37
23:47
23:57
00:07
```
References:
* [`:root`](https://developer.mozilla.org/en-US/docs/Web/CSS/:root).
* [CSS Custom Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/--*).
* [`grid-column`](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column).
* [`grid-column-gap`](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column-gap).
* [`repeat()`](https://developer.mozilla.org/en-US/docs/Web/CSS/repeat).
* [`var()`](https://developer.mozilla.org/en-US/docs/Web/CSS/var).
Upvotes: 2 [selected_answer]<issue_comment>username_2: @DavidThomas' [answer](https://stackoverflow.com/a/49336248/2803743) helped me a ton, but I ended up going in a bit of a different direction. I found out that pseudo elements are considered as grid cells! That opened up a nice opportunity to use aria labels as titles, and my desired result looks like this:
```css
.time-table {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 3em;
text-align: center;
color: #fff;
}
.time-table__listing {
display: grid;
grid-gap: 1em;
grid-template-columns: repeat(2, 1fr);
list-style: none;
--listing-background: #34ace0;
}
.time-table__listing:last-child {
--listing-background: #B33771;
}
.time-table__listing::before {
content: '\021D2 ' attr(aria-label);
font-size: 1.2em;
grid-column: 1 / span 2;
}
.time-table__listing:first-child::before {
background-color: #34ace0;
}
.time-table__listing:last-child::before {
background-color: #B33771;
}
.time-table__time {
background-color: var(--listing-background);
}
```
```html
1. 23:22
2. 23:32
3. 23:42
4. 23:52
5. 00:02
1. 23:27
2. 23:37
3. 23:47
4. 23:57
5. 00:07
```
Upvotes: 0 <issue_comment>username_3: There is no need for extra markup using modern CSS grid, **however** since this is tabular data, and not terms/definitions, you should be using `table` instead of `dl`.
In my example, if you want to expand horizontally, you *will* need to add more CSS for each subsequent term. Not bad to code using a preprocessor, but a fair bit of code for something a table would handle more easily.
```css
dl {
display: grid;
width: 10em;
column-gap: 1em;
row-gap: .5em;
grid-auto-flow: row dense;
}
dt {
grid-column: auto / span 2;
grid-row: 1;
}
dt, dd {
text-align: center;
}
dd:nth-child(even) {
grid-column: 1;
}
dd:nth-child(odd) {
grid-column: 2;
}
dt:nth-of-type(2) ~ dd:nth-child(even) {
grid-column: 3;
}
dt:nth-of-type(2) ~ dd:nth-child(odd) {
grid-column: 4;
}
```
```html
Metsakooli
23:22
23:32
23:42
23:52
00:02
Männiku
23:27
23:37
23:47
23:57
00:07
```
Upvotes: 0
|
2018/03/17
| 746 | 2,381 |
<issue_start>username_0: i am trying to redirect when i am getting data from firebase.
if it is null or empty then no need to redirect.
I am trying by using `this.navCtrl.push(ProspectPage);` but don't know why it is not working
it returns an error
`TypeError: this is null`
Here is my code, please check it and let me know what i am doing wrong here.
```
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ProspectPage } from '../prospect/prospect';
import * as firebase from 'firebase';
@Component({
selector: 'page-credentials',
templateUrl: 'credentials.html'
})
export class CredentialsPage {
constructor(public navCtrl: NavController) {
}
register(params){
// this.navCtrl.push(ProspectPage); // if i wrote here then it works
ref.orderByChild("ssn").equalTo(1234).on("value", function(snapshot) {
if(snapshot.val())
{
this.navCtrl.push(ProspectPage);
}
});
}
}
```
see register() there is one comment. If i add `this.navCtrl.push(ProspectPage);` at the starting of the function
then it works. but it should work when i gat the data from firbase.
Here, is my html code.
```
Lets go!
```<issue_comment>username_1: The answer to your question is [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions):
>
> An arrow function expression has a shorter syntax than a function
> expression and does not bind its own this, arguments, super, or
> new.target.
>
>
>
```
register(params) {
ref.orderByChild("ssn").equalTo(1234).on("value", (snapshot) => {
if(snapshot.val()) {
this.navCtrl.push(ProspectPage);
}
});
}
```
Notice the `(snapshot) => {...}` instead of the `function(snapshot) {...}`
Upvotes: 4 [selected_answer]<issue_comment>username_2: Example:
```
this.a = 100;
let arrowFunc = () => {this.a = 150};
function regularFunc() {
this.a = 200;
}
console.log(this.a)
arrowFunc()
console.log(this.a);
regularFunc()
console.log(this.a);
/*
Output
100
150
150
*/
```
Your corrected Code is:
```
register(params){
// this.navCtrl.push(ProspectPage); // if i wrote here then it works
//convert to arrow function
ref.orderByChild("ssn").equalTo(1234).on("value", (snapshot)=> {
if(snapshot.val())
{
this.navCtrl.push(ProspectPage);
}
});
}
```
Upvotes: 0
|
2018/03/17
| 1,327 | 4,695 |
<issue_start>username_0: I have an image like this:

and I'd like to resize this image to a specific width: **let's say 200px** where the height should also get calculated. (So the image should keep its width-to-height scale)
This was all I get so far:
```
extension UIImage {
func resize(newSize1: CGSize) -> UIImage {
let size = self.size
let widthRatio = newSize1.width / size.width
let heightRatio = newSize1.height / size.height
var newSize2: CGSize
if(widthRatio > heightRatio) {
newSize2 = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize2 = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
let rect = CGRect(x: 0, y: 0, width: newSize2.width, height: newSize2.height)
UIGraphicsBeginImageContextWithOptions(newSize2, false, 1.0)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage2!
}
}
```
But the function takes a `CGSize` size parameter (width AND height) but I just want to get a function that takes the width parameter.
How to edit my code to solve my problem?
Any help would be very appreciated `:)`
**Note**: The UIImage should get a smaller resolution (less pixels), not the Image View itself!<issue_comment>username_1: You can calculate the desired height based on your width and aspect ratio of the image. The same can be applied to the height parameters. Here is a sample of the extension of the `UIImage`.
```
extension UIImage {
func resize(width: CGFloat) -> UIImage {
let height = (width/self.size.width)*self.size.height
return self.resize(size: CGSize(width: width, height: height))
}
func resize(height: CGFloat) -> UIImage {
let width = (height/self.size.height)*self.size.width
return self.resize(size: CGSize(width: width, height: height))
}
func resize(size: CGSize) -> UIImage {
let widthRatio = size.width/self.size.width
let heightRatio = size.height/self.size.height
var updateSize = size
if(widthRatio > heightRatio) {
updateSize = CGSize(width:self.size.width*heightRatio, height:self.size.height*heightRatio)
} else if heightRatio > widthRatio {
updateSize = CGSize(width:self.size.width*widthRatio, height:self.size.height*widthRatio)
}
UIGraphicsBeginImageContextWithOptions(updateSize, false, UIScreen.main.scale)
self.draw(in: CGRect(origin: .zero, size: updateSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
```
}
Upvotes: 3 <issue_comment>username_2: For Swift 4 And Swift 3 use below `UIImage` extension for resizing image. It's calculated height according to given width.
```
extension UIImage {
func resized(toWidth width: CGFloat) -> UIImage? {
let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: canvasSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: Based on the solution from @username_1 I developed the following approach to scale an image so that the bigger size (width or height) don't exceeds a defined maximum size, defined by the parameter 'base'.
Example: if the original size is width = 4000 and height = 3000 and the parameter 'base' is set to 200 the returned image has the size 200 x 150 (or vice versa if height is bigger than width):
```
extension UIImage {
func resize(toBase base: CGFloat) -> UIImage {
guard base > 0 else {
return self
}
let widthRatio = base / max(self.size.width, 1)
let heightRatio = base / max(self.size.height, 1)
var updateSize = CGSize()
if (widthRatio > heightRatio) {
updateSize = CGSize(width:self.size.width * heightRatio, height:self.size.height * heightRatio)
} else {
updateSize = CGSize(width:self.size.width * widthRatio, height:self.size.height * widthRatio)
}
UIGraphicsBeginImageContextWithOptions(updateSize, false, UIScreen.main.scale)
self.draw(in: CGRect(origin: .zero, size: updateSize))
if let newImage = UIGraphicsGetImageFromCurrentImageContext() {
UIGraphicsEndImageContext()
return newImage
} else {
UIGraphicsEndImageContext()
return self
}
}
```
}
Upvotes: 0
|
2018/03/17
| 1,203 | 4,436 |
<issue_start>username_0: I am writing Automation scripts using protractor. I have created a java script file in which I have created a function.
PlatformviewCnOPage is my JS file and searchCapabilityOfferingsName is function. I want to call this function in another function (in same file).
```
var PlatformviewCnOPage = function() {
this.searchCapabilityOfferingsName = function(){
coreutil.clickElement(objectrepo.platformView_Searchbox_EnterBtn,'xpath');
browser.sleep(2000);
var searchResult= coreutil.getTextofElement(objectrepo.platformView_SearchResult,'xpath');
return searchResult;
}
```
I want to use the above function i.e searchCapabilityOfferingsName in another function in same java script file. I have tried some combinations but its not working.Basically I am new to java script.
```
this.verifySearchinCnO = function(){
this.searchCapabilityOfferingsName();// Failed-method not defined
searchCapabilityOfferingsName(); //Failed method not defined
Create object of same file and call the function. // Failed.
}
};
module.exports = PlatformviewCnOPage;
```
Could anyone suggest how can I call the function in another function in same JS file?<issue_comment>username_1: You can calculate the desired height based on your width and aspect ratio of the image. The same can be applied to the height parameters. Here is a sample of the extension of the `UIImage`.
```
extension UIImage {
func resize(width: CGFloat) -> UIImage {
let height = (width/self.size.width)*self.size.height
return self.resize(size: CGSize(width: width, height: height))
}
func resize(height: CGFloat) -> UIImage {
let width = (height/self.size.height)*self.size.width
return self.resize(size: CGSize(width: width, height: height))
}
func resize(size: CGSize) -> UIImage {
let widthRatio = size.width/self.size.width
let heightRatio = size.height/self.size.height
var updateSize = size
if(widthRatio > heightRatio) {
updateSize = CGSize(width:self.size.width*heightRatio, height:self.size.height*heightRatio)
} else if heightRatio > widthRatio {
updateSize = CGSize(width:self.size.width*widthRatio, height:self.size.height*widthRatio)
}
UIGraphicsBeginImageContextWithOptions(updateSize, false, UIScreen.main.scale)
self.draw(in: CGRect(origin: .zero, size: updateSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
```
}
Upvotes: 3 <issue_comment>username_2: For Swift 4 And Swift 3 use below `UIImage` extension for resizing image. It's calculated height according to given width.
```
extension UIImage {
func resized(toWidth width: CGFloat) -> UIImage? {
let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: canvasSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: Based on the solution from @username_1 I developed the following approach to scale an image so that the bigger size (width or height) don't exceeds a defined maximum size, defined by the parameter 'base'.
Example: if the original size is width = 4000 and height = 3000 and the parameter 'base' is set to 200 the returned image has the size 200 x 150 (or vice versa if height is bigger than width):
```
extension UIImage {
func resize(toBase base: CGFloat) -> UIImage {
guard base > 0 else {
return self
}
let widthRatio = base / max(self.size.width, 1)
let heightRatio = base / max(self.size.height, 1)
var updateSize = CGSize()
if (widthRatio > heightRatio) {
updateSize = CGSize(width:self.size.width * heightRatio, height:self.size.height * heightRatio)
} else {
updateSize = CGSize(width:self.size.width * widthRatio, height:self.size.height * widthRatio)
}
UIGraphicsBeginImageContextWithOptions(updateSize, false, UIScreen.main.scale)
self.draw(in: CGRect(origin: .zero, size: updateSize))
if let newImage = UIGraphicsGetImageFromCurrentImageContext() {
UIGraphicsEndImageContext()
return newImage
} else {
UIGraphicsEndImageContext()
return self
}
}
```
}
Upvotes: 0
|
2018/03/17
| 3,450 | 9,189 |
<issue_start>username_0: I am currently using D3 v4. My x scale is a scaleBand where I am taking a country name for the display and my y scale is scaleTime. When I am trying to get a new xScale in the zoom function it's throwing an error at rescaleX. I looked at many examples online but all of them either have a linearScale or scaleTime.
```
var countryArr = ["USA", "UK", "Poland", "Sweden"];
var firstDay = moment(day).subtract(1, 'days').toDate();
var lastDay = moment(day).add(1, 'days').toDate();
// define scale
var yScale = d3.scaleTime().range([0, width]);
yScale.domain([firstDay, lastDay]);
var xScale = d3.scaleBand().range([0, height]);
xScale.domain(countryArr);
// define zoom
var zoom = d3.zoom()
.scaleExtent([1, 1])
.translateExtent([[margin.left, margin.top], [width, height]])
.on("zoom", zoomed);
d3.select("#main-canvas").call(zoom);
function zoomed() {
//console.log(d3.event.transform.y);
var new_x = d3.event.transform.rescaleX(xScale); // ERROR at this line
var new_y = d3.event.transform.rescaleY(yScale);
}
```
[](https://i.stack.imgur.com/e57Bu.png)<issue_comment>username_1: It makes little sense using `rescaleX` in an **ordinal** (qualitative) scale. The [API](https://github.com/d3/d3-zoom#transform_rescaleX) is clear:
>
> Returns a copy of the **continuous scale** x whose domain is transformed. This is implemented by first applying the inverse x-transform on the scale’s range, and then applying the inverse scale to compute the corresponding domain. (emphasis mine)
>
>
>
Also, Bostock (D3 creator) [already explained](https://github.com/d3/d3/issues/2442) that...
>
> ... the zoom behavior affects the attached scales’ domains, but it wouldn’t make sense to modify the ordinal scale’s domain when panning and zooming because the domain is discrete.
>
>
>
What you can do is creating a *geometric zooming* instead of a *semantic zooming*.
Here is a demo, I'm using [this example](https://bl.ocks.org/mbostock/3885304) of a bar chart to add the geometric zooming:
```js
var svg = d3.select("svg"),
margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
y = d3.scaleLinear().rangeRound([height, 0]);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var data = [{
"letter": "A",
"frequency": 0.08167
}, {
"letter": "B",
"frequency": 0.01492
}, {
"letter": "C",
"frequency": 0.02782
}, {
"letter": "D",
"frequency": 0.04253
}, {
"letter": "E",
"frequency": 0.12702
}, {
"letter": "F",
"frequency": 0.02288
}, {
"letter": "G",
"frequency": 0.02015
}, {
"letter": "H",
"frequency": 0.06094
}, {
"letter": "I",
"frequency": 0.06966
}, {
"letter": "J",
"frequency": 0.00153
}, {
"letter": "K",
"frequency": 0.00772
}, {
"letter": "L",
"frequency": 0.04025
}, {
"letter": "M",
"frequency": 0.02406
}, {
"letter": "N",
"frequency": 0.06749
}, {
"letter": "O",
"frequency": 0.07507
}, {
"letter": "P",
"frequency": 0.01929
}, {
"letter": "Q",
"frequency": 0.00095
}, {
"letter": "R",
"frequency": 0.05987
}, {
"letter": "S",
"frequency": 0.06327
}, {
"letter": "T",
"frequency": 0.09056
}, {
"letter": "U",
"frequency": 0.02758
}, {
"letter": "V",
"frequency": 0.00978
}, {
"letter": "W",
"frequency": 0.0236
}, {
"letter": "X",
"frequency": 0.0015
}, {
"letter": "Y",
"frequency": 0.01974
}, {
"letter": "Z",
"frequency": 0.00074
}];
x.domain(data.map(function(d) {
return d.letter;
}));
y.domain([0, d3.max(data, function(d) {
return d.frequency;
})]);
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y).ticks(10, "%"))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Frequency");
g.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) {
return x(d.letter);
})
.attr("y", function(d) {
return y(d.frequency);
})
.attr("width", x.bandwidth())
.attr("height", function(d) {
return height - y(d.frequency);
});
var rect = g.append("rect")
.attr("width", width)
.attr("height", height)
.attr("opacity", 0)
.call(d3.zoom()
.scaleExtent([.1, 10])
.on("zoom", zoom));
function zoom() {
g.attr("transform", d3.event.transform);
}
```
```css
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
.axis--x path {
display: none;
}
```
```html
```
Upvotes: 3 <issue_comment>username_2: As @gerardofurtado explains the rescale function makes little sense for a ordinal scale. But here's a little trick I like to use for a nice zoom on the graph with rescaling ordinal axis. Essentially, it zoom the axis independently and then inverse scales the components of the axis (lines and text) so that they don't distort:
```html
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
.axis--x path {
display: none;
}
var svg = d3.select("svg"),
margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var zoom = d3.zoom()
.scaleExtent([1, Infinity])
.translateExtent([
[0, 0],
[width, height]
])
.extent([
[0, 0],
[width, height]
])
.on("zoom", zoom);
svg.call(zoom);
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
y = d3.scaleBand().rangeRound([height, 0]).padding(0.1);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var defs = g.append('defs');
defs
.append('clipPath')
.attr('id', 'clip')
.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', width)
.attr('height', height);
defs
.append('clipPath')
.attr('id', 'clipx')
.append('rect')
.attr('x', 0)
.attr('y', height)
.attr('width', width)
.attr('height', margin.bottom);
defs
.append('clipPath')
.attr('id', 'clipy')
.append('rect')
.attr('x', -margin.left)
.attr('y', -10)
.attr('width', margin.left+1)
.attr('height', height+15);
var data = [{
"letter": "A",
"frequency": 'Z'
}, {
"letter": "B",
"frequency": 'Y'
}, {
"letter": "C",
"frequency": 'X'
}, {
"letter": "D",
"frequency": 'W'
}, {
"letter": "E",
"frequency": 'V'
}, {
"letter": "F",
"frequency": 'U'
}, {
"letter": "G",
"frequency": 'T'
}, {
"letter": "H",
"frequency": 'S'
}, {
"letter": "I",
"frequency": 'R'
}, {
"letter": "J",
"frequency": 'Q'
}, {
"letter": "K",
"frequency": 'P'
}, {
"letter": "L",
"frequency": 'O'
}, {
"letter": "M",
"frequency": 'N'
}, {
"letter": "N",
"frequency": 'M'
}, {
"letter": "O",
"frequency": 'L'
}, {
"letter": "P",
"frequency": 'K'
}, {
"letter": "Q",
"frequency": 'J'
}, {
"letter": "R",
"frequency": 'I'
}, {
"letter": "S",
"frequency": 'H'
}, {
"letter": "T",
"frequency": 'G'
}, {
"letter": "U",
"frequency": 'F'
}, {
"letter": "V",
"frequency": 'E'
}, {
"letter": "W",
"frequency": 'D'
}, {
"letter": "X",
"frequency": 'C'
}, {
"letter": "Y",
"frequency": 'B'
}, {
"letter": "Z",
"frequency": 'A'
}];
x.domain(data.map(function(d) {
return d.letter;
}));
y.domain(data.map(function(d) {
return d.frequency;
}));
var xAxis = g.append("g")
.attr('clip-path', 'url(#clipx)')
.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
var yAxis = g.append("g")
.attr('clip-path', 'url(#clipy)')
.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y));
yAxis
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Letters Too");
var bars = g.append("g")
.attr('clip-path', 'url(#clip)')
.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) {
return x(d.letter);
})
.attr("y", function(d) {
return y(d.frequency) + y.bandwidth()/2;
})
.attr("width", x.bandwidth())
.attr("height", function(d) {
return height - y(d.frequency);
});
function zoom() {
var t = d3.event.transform;
bars.attr("transform", t);
xAxis.attr("transform", d3.zoomIdentity.translate(t.x, height).scale(t.k));
xAxis.selectAll("text")
.attr("transform",d3.zoomIdentity.scale(1/t.k));
xAxis.selectAll("line")
.attr("transform",d3.zoomIdentity.scale(1/t.k));
yAxis.attr("transform", d3.zoomIdentity.translate(0, t.y).scale(t.k));
yAxis.selectAll("text")
.attr("transform",d3.zoomIdentity.scale(1/t.k));
yAxis.selectAll("line")
.attr("transform",d3.zoomIdentity.scale(1/t.k));
}
```
Upvotes: 4 [selected_answer]
|
2018/03/17
| 765 | 2,596 |
<issue_start>username_0: I created a `file.h` and a `file.c` how can I compile them on Ubuntu?<issue_comment>username_1: Use following command to compile your program(For GCC Compiler):
```
gcc file.c -o file
```
No need to compile file.h file.
Upvotes: 1 <issue_comment>username_2: **You only need to compile your `.c` file(s), not your `.h` file(s).**
To compile `file.c` on Ubuntu, you can use [GCC](https://gcc.gnu.org/):
```
gcc file.c -o my_program
```
...or [Clang](https://clang.llvm.org/):
```
clang file.c -o my_program
```
It is possible to precompile your header files, but you only need precompiled headers in particular cases. [More information here.](https://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html)
---
**If `file.h` is not in the same folder as `file.c`, you can use GCC or Clang's `-I` option.**
Example if `file.h` is in the `include/` folder:
```
gcc -I include/ file.c -o my_program
```
In `file.c` you still have this instruction, with only the filename:
```
#include "file.h"
```
Upvotes: 2 <issue_comment>username_3: You can also use a more generic approach by the usage of a makefile.
Here is a short example of such a file:
```
# Declaration of variables
CC = gcc
CC_FLAGS = -w -Werror -Wall
# File names
# "prgoram" will be the name of the output produced from the make process
EXEC = program
#Incorporates all the files with .c extension
SOURCES = $(wildcard *.c)
OBJECTS = $(SOURCES:.c=.o)
# Main target
$(EXEC): $(OBJECTS)
$(CC) $(OBJECTS) -o $(EXEC)
# To obtain object files
%.o: %.c
$(CC) -c $(CC_FLAGS) $< -o $@
# To remove generated files
clean:
rm -f $(EXEC) $(OBJECTS)
```
To use this utility just make sure that the file itself is within the directory containing your source files and its name is either "makefile" or "Makefile".
To compile the code simply run the following command from your working directory:
```
make program
```
This command will automatically link all the source files within your working directory into one executable file with the name of "program". To run the program itself just use the command:
```
./program
```
To clean your project and the created executable you can run the command:
```
make clean
```
The makefile is very powerful when dealing with larger projects that contain a larger number of source files. [Here](http://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/) you can check for more guidance on how to use makefiles. [This is](http://makepp.sourceforge.net/1.19/makepp_tutorial.html) also a very detailed tutorial on the topic.
Upvotes: 2
|
2018/03/17
| 789 | 2,477 |
<issue_start>username_0: I am trying to build a docker image whenever there is push to my source code and move the docker image to the ECR( EC2 Container Registry).
I have tried with the following build-spec file
```
version: 0.2
env:
variables:
IMG: "app"
REPO: "<>.dkr.ecr.us-east-1.amazonaws.com/app"
phases:
pre\_build:
commands:
- echo Logging in to Amazon ECR...
- aws ecr get-login --region us-east-1
- TAG=echo $CODEBUILD\_RESOLVED\_SOURCE\_VERSION | head -c 8
build:
commands:
- echo $TAG
- docker build -t $IMG:$TAG .
- docker tag $IMG:$TAG $REPO:$TAG
post\_build:
commands:
- docker push $REPO:$TAG
- printf Image":"%s:%s" $REPO $TAG > build.json
artifacts:
files: build.json
discard-paths: yes
```
when I build this I am receiving the error `invalid reference format` at docker build -t
I looked into the document and found no help.<issue_comment>username_1: ```
TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | head -c 8)
```
you can use $()
```
version: 0.2
phases:
install:
commands:
- echo Entered the install phase...
- TAG=$(echo "This is test")
pre_build:
commands:
- echo $TAG
build:
commands:
- echo Entered the build phase...
- echo Build started on $TAG
```
Logs:
```
[Container] 2018/03/17 16:15:31 Running command TAG=$(echo "This is test")
[Container] 2018/03/17 16:15:31 Entering phase PRE_BUILD
[Container] 2018/03/17 16:15:31 Running command echo $TAG
This is test
```
Upvotes: 2 <issue_comment>username_2: So after of lots of retries, i finally found my mistake.
Env **CODEBUILD\_RESOLVED\_SOURCE\_VERSION** should be replaced with **CODEBUILD\_SOURCE\_VERSION** environment variable because I am using codebuild to build directly from source repo in GitHub.
To log in to ecr, need to add `--no-include-email` option and wrap the command with $(). This will allow you to run docker login. My updated buildspec file would be similar below
```
version: 0.2
env:
variables:
REPO: "184665364105.dkr.ecr.us-east-1.amazonaws.com/app"
phases:
pre_build:
commands:
- echo $CODEBUILD_SOURCE_VERSION
- TAG=$(echo $CODEBUILD_SOURCE_VERSION | head -c 8)
- echo Logging in to Amazon ECR...
- $(aws ecr get-login --no-include-email --region us-east-1)
build:
commands:
- echo $TAG
- echo $REPO
- docker build --tag $REPO:$TAG .
post_build:
commands:
- docker push $REPO:$TAG
```
Upvotes: 1
|
2018/03/17
| 618 | 2,001 |
<issue_start>username_0: New to python and I cannot import modules that I have installed via pip.
For instance, I have installed numpy though cannot import it.
I have a feeling from trying to work this out that it is installing to the wrong directory, or I am calling the wrong version.
```
$ which python
```
returns
/usr/bin/python
I am just not sure how to change it so I can access the modules.<issue_comment>username_1: ```
TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | head -c 8)
```
you can use $()
```
version: 0.2
phases:
install:
commands:
- echo Entered the install phase...
- TAG=$(echo "This is test")
pre_build:
commands:
- echo $TAG
build:
commands:
- echo Entered the build phase...
- echo Build started on $TAG
```
Logs:
```
[Container] 2018/03/17 16:15:31 Running command TAG=$(echo "This is test")
[Container] 2018/03/17 16:15:31 Entering phase PRE_BUILD
[Container] 2018/03/17 16:15:31 Running command echo $TAG
This is test
```
Upvotes: 2 <issue_comment>username_2: So after of lots of retries, i finally found my mistake.
Env **CODEBUILD\_RESOLVED\_SOURCE\_VERSION** should be replaced with **CODEBUILD\_SOURCE\_VERSION** environment variable because I am using codebuild to build directly from source repo in GitHub.
To log in to ecr, need to add `--no-include-email` option and wrap the command with $(). This will allow you to run docker login. My updated buildspec file would be similar below
```
version: 0.2
env:
variables:
REPO: "184665364105.dkr.ecr.us-east-1.amazonaws.com/app"
phases:
pre_build:
commands:
- echo $CODEBUILD_SOURCE_VERSION
- TAG=$(echo $CODEBUILD_SOURCE_VERSION | head -c 8)
- echo Logging in to Amazon ECR...
- $(aws ecr get-login --no-include-email --region us-east-1)
build:
commands:
- echo $TAG
- echo $REPO
- docker build --tag $REPO:$TAG .
post_build:
commands:
- docker push $REPO:$TAG
```
Upvotes: 1
|
2018/03/17
| 979 | 2,149 |
<issue_start>username_0: I have an batch of output hidden vector from GRU. It's shape is [1,4,256]
```
( 0 ,.,.) =
-0.9944 1.0000 0.0000 ... -1.0000 0.0000 -1.0000
-1.0000 1.0000 0.0000 ... -1.0000 0.0000 -1.0000
-1.0000 1.0000 0.0000 ... -1.0000 0.0000 -1.0000
-1.0000 1.0000 0.0000 ... -1.0000 0.0000 -1.0000
[torch.cuda.FloatTensor of size (1,4,256) (GPU 0)]
```
I need a shape of [1,1,256] to pass to another model. How can I take it? Through this line I can only have a shape of [1,256]
```
decoder_hidden = encoder_hidden[:, index]
```
resize and wrap a new FloatTensor didn't work.<issue_comment>username_1: You can use the [`view()`](http://pytorch.org/docs/master/tensors.html#torch.Tensor.view) method of tensors.
```
decoder_hidden_new = decoder_hidden.view((1, 1, 256))
```
Upvotes: 2 <issue_comment>username_2: You can [**unsqueeze()**](http://pytorch.org/docs/0.3.1/torch.html#torch.unsqueeze) in dimension `1` to achieve this.
```
encoder_hidden = torch.randn(1, 4, 256)
print(encoder_hidden.size())
for idx in range(encoder_hidden.size(1)):
decoder_hidden = encoder_hidden[:, idx, :].unsqueeze(1)
print(decoder_hidden.size())
```
It prints:
```
torch.Size([1, 4, 256])
torch.Size([1, 1, 256])
torch.Size([1, 1, 256])
torch.Size([1, 1, 256])
torch.Size([1, 1, 256])
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: Here're more ways to do this. Details in the comments below:
```
# random tensor
In [53]: t.shape
Out[53]: torch.Size([1, 4, 256])
# the four slices
In [54]: slice_1 = t[:, 0, :]
In [55]: slice_2 = t[:, 1, :]
In [56]: slice_3 = t[:, 2, :]
In [57]: slice_4 = t[:, 3, :]
In [58]: slice_1.shape
Out[58]: torch.Size([1, 256])
# using `torch.np.newaxis`
In [59]: slice_1 = slice_1[torch.np.newaxis, ...]
In [60]: slice_1.shape
Out[60]: torch.Size([1, 1, 256])
# simply using `np.newaxis`
In [61]: slice_2 = slice_2[np.newaxis, ...]
In [62]: slice_2.shape
Out[62]: torch.Size([1, 1, 256])
# or even simply, use `None` which is an alias to `np.newaxis`
In [63]: slice_3 = slice_3[None, ...]
In [64]: slice_3.shape
Out[64]: torch.Size([1, 1, 256])
```
Upvotes: 0
|
2018/03/17
| 434 | 1,488 |
<issue_start>username_0: I tried to execute commands read it from txt file. But only 1st command is executing, after that script is terminated. My script file name is shellEx.sh is follows:
```
echo "pwd" > temp.txt
echo "ls" >> temp.txt
exec < temp.txt
while read line
do
exec $line
done
echo "printed"
```
if I keep echo in the place of exec, just it prints both pwd and ls. But i want to execute pwd and ls one by one.
o/p am getting is:
```
$ bash shellEx.sh
/c/Users/<NAME>/Desktop
```
But after pwd, ls also need to execute for me.
Anyone can please give better solution for this?<issue_comment>username_1: `exec` in bash is meant in the [Unix sense](https://en.m.wikipedia.org/wiki/Exec_(system_call)) where it means "stop running this program and start running another instead". This is why your script exits.
If you want to execute line as a shell command, you can use:
```
line="find . | wc -l"
eval "$line"
```
(`$line` by itself will not allow using pipes, quotes, expansions or other shell syntax)
To execute the entire file including multiline commands, use one of:
```
source ./myfile # keep variables, allow exiting script
bash myfile # discard variables, limit exit to myfile
```
Upvotes: 2 <issue_comment>username_2: A file with one valid command per line is itself a shell script. Just use the `.` command to execute it in the current shell.
```
$ echo "pwd" > temp.txt
$ echo "ls" >> temp.txt
$ . temp.txt
```
Upvotes: -1 [selected_answer]
|
2018/03/17
| 678 | 3,211 |
<issue_start>username_0: So I was wondering that if a table is in editing mode(say in SQL), it cannot be accessed or changed by some other user. But then how is that we see real time visualization in Tableau ?, how come we are seeing charts but they are being updated at the back end in real time. Technically it can't be changed or accessed.
I would like to understand how data is updated real time and at the same time we use those tables to see dynamic charts.
I tried searching internet over this, closest I came to HSQL, but I am not able to understand.<issue_comment>username_1: I was wondering if you are asking the opposite of what you are asking :)
Databases think of data as the unique truce and they will execute your commands on those data. **The data is not locked when you are seeing it on your screen**.
When you present the data, say in an application or even in Management studio (for SQL server) they query the DB on that specific time and show it to you and when you change something, they send an update command to the server. The data is not locked.
DBs have a locking process on tables that usually works when you have a time consuming command and you don't want any proccess reading the data while some of them are in invalid state. Lets say you are doing an update increasing col1 by 1. Now in the middle of the update if someone query on data and SQL returns the data some of them will be the updated value and some others will not which usually is not what you want.
However, there is a mode in SQL called "Single user mode" which disables all connections from all other users and doesn't let them connect letting the DBA to take care of the DB (usually when you have a big DB change).
Upvotes: 1 <issue_comment>username_2: SQL Server provides transaction isolation levels to provide read consistency. These may use either locking or row versioning depending on the session transaction isolation level and database configuration.
The default transaction isolation level is `READ_COMMITTED` implemented with locking. In this case, read-only queries like those used for your Tableau visualization will happily select data unless the requested rows are currently being updated. The query will then wait until the transaction is committed and then proceed returning the latest data. Depending on the workload, the duration of blocking like this may be so small as to be transparent to the application. But in the case of large batch updates, the blocking duration can be significant. Note that SQL Server will use granular locks when possible rather than locking the entire table.
A DBA can change this behavior by turning on the database `READ_COMMITTED_SNAPSHOT` database option. This causes the `READ_COMMITTED` isolation level to use row versioning instead of locking to provide read consistency. With this option turned on, the Tableau queries will receive the before image of updated data instead of being blocked by an in-progress transaction. There is some additional overhead with row versioning so DBAs don't turn on the `READ_COMMITTED_SNAPSHOT` database option on indiscriminately. Turning on the option improve concurrency but at the cost of resource usage.
Upvotes: 2
|
2018/03/17
| 478 | 1,609 |
<issue_start>username_0: I'm trying to write my own implementation of show for my Tree type. But the following code:
```
data Tree a = Leaf a | Branch (Tree a) (Tree a)
instance Show (Tree a) where
show (Branch a b) = show $ "<" ++ show a ++ "," ++ show b ++ ">"
show (Leaf a) = show a
```
is yielding:
```
main.hs:11:21: error:
• No instance for (Show a) arising from a use of ‘show’
Possible fix:
add (Show a) to the context of the instance declaration
• In the expression: show a
In an equation for ‘show’: show (Leaf a) = show a
In the instance declaration for ‘Show (Tree a)’
|
11 | show (Leaf a) = show a
| ^^^^^^
```
I don't really understand what the compiler is telling me.
What would be the correct implementation and why?<issue_comment>username_1: You need to explicitly state that there exists a `Show` instance for the type variable `a`:
```
instance (Show a) => Show (Tree a) where
show (Branch a b) = show $ "<" ++ show a ++ "," ++ show b ++ ">"
show (Leaf a) = show a
```
Upvotes: 2 <issue_comment>username_2: In your implementation, you write:
```
instance Show (Tree a) where
show (Branch a b) = show $ "<" ++ show a ++ "," ++ show b ++ ">"
show (Leaf a) = **show a**
```
That thus means that you call `show` on an `a` object. But Haskell has no guarantees that it can call `show` on `a`. So you need to add a type constraint `Show a`:
```
instance **Show a =>** Show (Tree a) where
show (Branch a b) = show $ "<" ++ show a ++ "," ++ show b ++ ">"
show (Leaf a) = show a
```
Upvotes: 1
|
2018/03/17
| 1,712 | 6,460 |
<issue_start>username_0: Consider my code below. My understanding of unique pointers was that only one unique pointer can be used to reference one variable or object. In my code I have more than one unique\_ptr accessing the same variable.
It's obviously not the correct way to use smart pointers i know, in that the pointer should have complete ownership from creation. But still, why is this valid and not having a compilation error? Thanks.
```
#include
#include
using namespace std;
int main()
{
int val = 0;
int\* valPtr = &val
unique\_ptr uniquePtr1(valPtr);
unique\_ptr uniquePtr2(valPtr);
\*uniquePtr1 = 10;
\*uniquePtr2 = 20;
return 0;
}
```<issue_comment>username_1: This example of code is a bit artificial. `unique_ptr` is not usually initialized this way in real world code. Use [`std::make_unique`](http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique) or initialize `unique_ptr` without storing raw pointer in a variable:
```
unique_ptr uniquePtr2(new int);
```
Upvotes: 0 <issue_comment>username_2: >
> But still, why is this valid
>
>
>
It is **not** valid! It's undefined behaviour, because the destructor of `std::unique_ptr` will free an object with automatic storage duration.
Practically, your program tries to destroy the `int` object three times. First through `uniquePtr2`, then through `uniquePtr1`, and then through `val` itself.
>
> and not having a compilation error?
>
>
>
Because such errors are not generally detectable at compile time:
```
unique_ptr uniquePtr1(valPtr);
unique\_ptr uniquePtr2(function\_with\_runtime\_input());
```
In this example, `function_with_runtime_input()` may perform a lot of complicated runtime operations which eventually return a pointer to the same object `valPtr` points to.
---
If you use `std::unique_ptr` correctly, then you will almost always use `std::make_unique`, which prevents such errors.
Upvotes: 3 <issue_comment>username_3: Just an addition to username_2's excellent answer:
`std::unique_ptr` was introduced to ensure [RAII](https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) for pointers; this means, in opposite to raw pointers you don't have to take care about destruction yourself anymore. The whole management of the raw pointer is done by the smart pointer. Leaks caused by a forgotten `delete` can not happen anymore.
If a `std::unique_ptr` would only allow to be created by `std::make_unique`, it would be absolutely safe regarding allocation and deallocation, and of course that would be also detectable during compile time.
But that's not the case: `std::unique_ptr` is also constructible with a raw pointer. The reason is, that being able to be constructed with a hard pointer makes a `std::unique_ptr` much more useful. If this would not be possible, e.g. the pointer returned by username_2's `function_with_runtime_input()` would not be possible to integrate into a modern RAII environment, you would have to take care of destruction yourself.
Of course the downside with this is that errors like yours can happen: To forget destruction is not possible with `std::unique_ptr`, but erroneous multiple destructions are always possible (and impossible to track by the compiler, as C.H. already said), if you created it with a raw pointer constructor argument. Always be aware that `std::unique_ptr` logically takes "ownership" of the raw pointer - what means, that no one else may delete the pointer except the one `std::unique_ptr` itself.
As rules of thumb it can be said:
* Always create a `std::unique_ptr` with `std::make_unique` if possible.
* If it needs to be constructed with a raw pointer, never touch the raw pointer after creating the `std::unique_ptr` with it.
* Always be aware, that the `std::unique_ptr` takes ownership of the supplied raw pointer
* Only supply raw pointers to the heap. NEVER use raw pointers which point to local
stack variables (because they will be unavoidably destroyed automatically,
like `val`in your example).
* Create a `std::unique_ptr` only with raw pointers, which were created by `new`, if possible.
* If the `std::unique_ptr` needs to be constructed with a raw pointer, which was created by something else than `new`, add a custom deleter to the `std::unique_ptr`, which matches the hard pointer creator. An example are image pointers in the (C based) [FreeImage](http://freeimage.sourceforge.net/) library, which always have to be destroyed by `FreeImage_Unload()`
Some examples to these rules:
```
// Safe
std::unique_ptr p = std::make\_unique();
// Safe, but not advisable. No accessible raw pointer exists, but should use make\_unique.
std::unique\_ptr p(new int());
// Handle with care. No accessible raw pointer exists, but it has to be sure
// that function\_with\_runtime\_input() allocates the raw pointer with 'new'
std::unique\_ptr p( function\_with\_runtime\_input() );
// Safe. No accessible raw pointer exists,
// the raw pointer is created by a library, and has a custom
// deleter to match the library's requirements
struct FreeImageDeleter {
void operator() (FIBITMAP\* \_moribund) { FreeImage\_Unload(\_moribund); }
};
std::unique\_ptr p( FreeImage\_Load(...) );
// Dangerous. Your class method gets a raw pointer
// as a parameter. It can not control what happens
// with this raw pointer after the call to MyClass::setMySomething()
// - if the caller deletes it, your'e lost.
void MyClass::setMySomething( MySomething\* something ) {
// m\_mySomethingP is a member std::unique\_ptr
m\_mySomethingP = std::move( std::unique\_ptr( something ));
}
// Dangerous. A raw pointer variable exists, which might be erroneously
// deleted multiple times or assigned to a std::unique\_ptr multiple times.
// Don't touch iPtr after these lines!
int\* iPtr = new int();
std::unique\_ptr p(iPtr);
// Wrong (Undefined behaviour) and a direct consequence of the dangerous declaration above.
// A raw pointer is assigned to a std::unique\_ptr twice, which means
// that it will be attempted to delete it twice.
// This couldn't have happened if iPtr wouldn't have existed in the first
// place, like shown in the 'safe' examples.
int\* iPtr = new int();
std::unique\_ptr p(iPtr);
std::unique\_ptr p2(iPtr);
// Wrong. (Undefined behaviour)
// An unique pointer gets assigned a raw pointer to a stack variable.
// Erroneous double destruction is the consequence
int val;
int\* valPtr = &val
std::unique\_ptr p(valPtr);
```
Upvotes: 2
|
2018/03/17
| 700 | 2,372 |
<issue_start>username_0: Slack themes are available in the web app using Stylish see <https://userstyles.org/styles/browse?search_terms=slack>
However there must be a way to use them on the Desktop application. What is the hack?<issue_comment>username_1: UPDATED LATEST! Slack desktop app now supports dark mode natively!
Just got to preferences `cmd+,` and select Themes > Dark
UPDATED, previous hacks stopped working with release of 4.0.0.
This solution works as of July 18, 2019
see <https://github.com/LanikSJ/slack-dark-mode>
You may need to see instructions on <https://github.com/LanikSJ/slack-dark-mode/issues/80>
I will likely update this answer again when I have time to fork the repo I've posted above and improve upon it.
Upvotes: 3 [selected_answer]<issue_comment>username_2: I've written a sort of small "plugin framework", where you just run a shell script to patch your slack install, and then you get the ability to enable any number of "plugins" I've written for the desktop app, one of which is a dark theme. There are instructions in the README if you'd like to load your own CSS files you've found elsewhere as well.
<https://github.com/glajchs/slack-customizations>
Upvotes: 2 <issue_comment>username_3: [Here](https://gist.github.com/username_3/0679f72bd990fc72cc91046455f736e6)'s my script to toggle between light and dark mode automatically at sunrise/sunset. Append the script at the end of `/Applications/Slack.app/Contents/Resources/app.asar.unpacked/src/static/ssb-interop.js` and don't forget to update the `LOCATION` based on your actual location.
```js
document.addEventListener('DOMContentLoaded', async function() {
// supply your location here, use e.g. https://www.latlong.net/ to find it
const LOCATION = [50.075539, 14.437800]
const MS_IN_DAY = 24 * 60 * 60 * 1000
const initTheme = themeCssUrl => new Promise(resolve => $.ajax({
url: themeCssUrl,
success: css => {
const styleJqueryEl = $('
```
Upvotes: 1 <issue_comment>username_4: This answer does not solve the desktop app question but can be used as a browser only based solution.
1. Use Chrome instead of downloadable Slack app
2. Install [Dark Reader chrome add-on](https://chrome.google.com/webstore/detail/dark-reader/eimadpbcbfnmbkopoojfekhnkhdbieeh)
3. Open Slack url (eg. <https://team_name.slack.com/>) in Chrome instead of app
Upvotes: 0
|
2018/03/17
| 1,218 | 3,892 |
<issue_start>username_0: I've been trying to set up clear information on iterating through and i and then j, but i get stuck when trying to make sense of the while loop?
Can someone please give me some information on how to solve something like this please?<issue_comment>username_1: In order to calculate all time-complexity of code, replace each loop with a summation. Moreover, consider that the second loop run `(n - i)/3` since `j` decreases with step size of `3`. So we have:
[](https://i.stack.imgur.com/q1i05.png)
Upvotes: 1 <issue_comment>username_2: *Disclaimer: this answer is long and overly verbose because I wanted to provide the OP with a "baby-steps" method rather than a result. I hope she can find some help from it - would it be needed.*
If you get stuck when trying to derive the complexity in one go, you can try to breakdown the problem into smaller pieces easier to reason about.
Introducing notations can help in this context to structure your thought process.
1. Let's introduce a notation for the inner `while` loop. We can see the starting index `j` depends on `n - i`, so the number of operations performed by this loop will be a function of `n` and `i`. Let's represent this number of operations by `G(i, n)`.
2. The outer loop depends only on `n`. Let's represent the number of operations by `T(n)`.
3. Now, let's write down the dependency between `T(n)` and `G(n, i)`, reasoning about the outer loop only - we do not care about the inner `while` loop for this step because we have already abstracted its complexity in the function `G`. So we go with:
`T(n) = G(n, n - 1) + G(n, n - 2) + G(n, n - 3) + ... + G(n, 0)
= sum(k = 0, k < n, G(n, k))`
4. Now, let's focus on the function `G`.
* Let's introduce an additional notation and write `j(t)` the value of the index `j` at the `t`-th iteration performed by the `while` loop.
* Let's call `k` the value of `t` for which the invariant of the while loop is breached, i.e. the last time the condition is evaluated.
* Let's consider an arbitrary `i`. You could try with a couple of specific values of `i` (e.g. 1, 2, `n`) if this helps.
We can write:
```
j(0) = n - i
j(1) = n - i - 3
j(2) = n - i - 6
...
j(k - 1) = n - i - 3(k - 1) such that j(k-1) >= 0
j(k) = n - i - 3k such that j(k) < 0
```
Finding `k` involves solving the inequality `n - 1 - 3k < 0`. To make it easier, let's "ignore" the fact that `k` is an integer and that we need to take the integer part of the result below.
```
n - i - 3k < 0 <=> k = (n - i) / 3
```
So there are `(n - i) / 3` "steps" to consider. By steps we refer here to the number of evaluation of the loop condition. The number of times the operation `j <- j - 3` is performed would be the latter minus one.
So we found an expression for `G(n, i)`:
```
G(n, i) = (n - i) / 3
```
Now let's get back to the expression of `T(n)` we found in (3):
```
T(n) = sum(k = 0, k < n, (n - k) / 3)
```
Since when `k` varies from 0 to `n`, `n - k` varies from `n` to 0, we can equivalently write `T(n)` as:
```
T(n) = sum(k = 0, k <= n, k / 3)
= (1/3).sum(k = 0, j <= n, k)
= (1/6).n.(n+1)
```
And you can therefore conclude with
```
T(n) = Theta(n^2)
```
This resolution exhibited some patterns from which you can create your own recipe to solve similar exercises:
* Consider the number of operations at individual levels (one loop at a time) and introduce notations for the functions representing them;
* Find relationships between these functions;
* Find an algebraic expression of the most inner functions, which doesn't depend on other functions you introduced and for which the number of steps can be calculated from a loop invariant;
* Using the relationships between these functions, find expressions for the functions higher in the stack.
Upvotes: 3 [selected_answer]
|
2018/03/17
| 1,194 | 4,050 |
<issue_start>username_0: I have an Array class written with RAII in mind (super simplified for the purpose of this example):
```
struct Array
{
Array(int size) {
m_size = size;
m_data = new int[m_size];
}
~Array() {
delete[] m_data;
}
int* m_data = nullptr;
int m_size = 0;
};
```
Then I have a function that takes a reference to an Array and does some operations on it. I use a temporary Array `temp` to perform the processing, because for several reasons I can't work directly with the reference. Once done, I would like to transfer the data from the temporary Array to the real one:
```
void function(Array& array)
{
Array temp(array.m_size * 2);
// do heavy processing on `temp`...
array.m_size = temp.m_size;
array.m_data = temp.m_data;
}
```
The obvious problem is that `temp` goes out of scope at the end of the function: its destructor is triggered, which in turn deletes the memory. This way `array` would contain non-existent data.
So what is the best way to "move" the ownership of data from an object to another?<issue_comment>username_1: if you insist on your example format, then you are missing a couple of things. you need to make sure that the temp array does not destroy memory reused by the non-temp array.
```
~Array() {
if (md_data != nullptr)
delete [] m_data;
}
```
and the function needs to do clean move
```
void function(Array& array)
{
Array temp(array.m_size * 2);
// do heavy processing on `temp`...
array.m_size = temp.m_size;
array.m_data = temp.m_data;
temp.m_data = nullptr;
temp.m_size = 0;
}
```
To make it more c++ like, you can do multiple things. i.e. in the array you can create member function to move the data from other array (or a constructor, or assign operator, ...)
```
void Array::move(Array &temp) {
m_size = temp.m_size;
temp.m_size = 0;
m_data = temp.m_data;
temp.m_data = 0;
}
```
in c++11 and higher you can create a move constructor and return your value from the function:
```
Array(Array &&temp) {
do your move here
}
Array function() {
Array temp(...);
return temp;
}
```
there are other ways as well.
Upvotes: 2 <issue_comment>username_2: What you want is move construction or move assignment for your array class, which saves you redundant copies. Also, it will help you to use `std::unique_ptr` which will take care of move semantics for allocated memory for you, so that you don't need to do any memory allocation directly, yourself. You will still need to pull up your sleeves and follow the ["rule of zero/three/five"](http://en.cppreference.com/w/cpp/language/rule_of_three), which in our case is the rule of five (copy & move constructor, copy & move assignment operator, destructor).
So, try:
```
class Array {
public:
Array(size_t size) : m_size(size) {
m_data = std::make_unique(size);
}
Array(const Array& other) : Array(other.size) {
std::copy\_n(other.m\_data.get(), other.m\_size, m\_data.get());
}
Array(Array&& other) : m\_data(nullptr) {
\*this = other;
}
Array& operator=(Array&& other) {
std::swap(m\_data, other.m\_data);
std::swap(m\_size,other.m\_size);
return \*this;
}
Array& operator=(const Array& other) {
m\_data = std::make\_unique(other.m\_size);
std::copy\_n(other.m\_data.get(), other.m\_size, m\_data.get());
return \*this;
}
~Array() = default;
std::unique\_ptr m\_data;
size\_t m\_size;
};
```
(Actually, it's a bad idea to have `m_size` and `m_data` public, since they're tied together and you don't want people messing with them. I would also template that class on the element type, i.e. `T` instead of `int` and use `Array`)
Now you can implement your function in a very straightforward manner:
```
void function(Array& array)
{
Array temp { array }; // this uses the copy constructor
// do heavy processing on `temp`...
std::swap(array, temp); // a regular assignment would copy
}
```
Upvotes: 4 [selected_answer]
|
2018/03/17
| 3,004 | 10,434 |
<issue_start>username_0: I have a code to get local ip address. This is the code I use.
```
typedef std::map settings\_t;
void loadLocalIp (settings\_t &ipConfig)
{
struct ifaddrs \* ifAddrStruct=NULL;
struct ifaddrs \* ifa=NULL;
void \* tmpAddrPtr=NULL;
getifaddrs(&ifAddrStruct);
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa\_next) {
if (ifa ->ifa\_addr->sa\_family==AF\_INET) { // check it is IP4
// is a valid IP4 Address
tmpAddrPtr=&((struct sockaddr\_in \*)ifa->ifa\_addr)->sin\_addr;
char addressBuffer[INET\_ADDRSTRLEN];
inet\_ntop(AF\_INET, tmpAddrPtr, addressBuffer, INET\_ADDRSTRLEN);
string key(ifa->ifa\_name);
string value(addressBuffer);
cout<(key, value));
// printf("'%s': %s\n", ifa->ifa\_name, addressBuffer);
}
}
if (ifAddrStruct!=NULL)
freeifaddrs(ifAddrStruct);//remember to free ifAddrStruct
}
int main()
{
settings\_t ipConfig;
loadLocalIp(ipConfig);
cout<
```
So My result, is
```
lo =1 127.0.0.1
enp2s0 =1 172.20.55.6
172.20.55.6
```
But In another computer, the interface name is different. They get result like bellow,
```
lo =1 127.0.0.1
ens32 =1 172.20.55.9
terminate called after throwing an instance of 'std::out_of_range'
what(): map::at
Aborted (core dumped)
```
I want to get my Ip address whatever the interface name is. How can I get my local ip address if the interface name varies from different computer. It should give the ip address whatever the interface name is. How can I do this?
My question is, Now I am getting my local IP from this method. But I should get IP whatever the Interface name is. One thing, I need to find that interface name and apply it in my above code (or) Is there any other option to find that IP without that interface?<issue_comment>username_1: >
> I want to get my IP address whatever the interface name is.
>
>
>
It is difficult to reliably get the local ip address by looking at the network interface. As you have already discovered, the network interface name can be unique for each host you run on. To further complicate things, a computer may have multiple network interfaces and each of those may or may not be connected to the Internet.
You don't need to use the default interface. A more simplistic approach is to just let the OS routing table figure it out for you. You can do this by setting up a socket connection to some external server and then calling [`getsockname`](http://man7.org/linux/man-pages/man2/getsockname.2.html) to get the local address. This example uses Google's DNS server at `8.8.8.8` to establish a socket connection but you can use whatever external server you'd like.
```
#include ///< cout
#include ///< memset
#include ///< errno
#include ///< socket
#include ///< sockaddr\_in
#include ///< getsockname
#include ///< close
int main()
{
const char\* google\_dns\_server = "8.8.8.8";
int dns\_port = 53;
struct sockaddr\_in serv;
int sock = socket(AF\_INET, SOCK\_DGRAM, 0);
//Socket could not be created
if(sock < 0)
{
std::cout << "Socket error" << std::endl;
}
memset(&serv, 0, sizeof(serv));
serv.sin\_family = AF\_INET;
serv.sin\_addr.s\_addr = inet\_addr(google\_dns\_server);
serv.sin\_port = htons(dns\_port);
int err = connect(sock, (const struct sockaddr\*)&serv, sizeof(serv));
if (err < 0)
{
std::cout << "Error number: " << errno
<< ". Error message: " << strerror(errno) << std::endl;
}
struct sockaddr\_in name;
socklen\_t namelen = sizeof(name);
err = getsockname(sock, (struct sockaddr\*)&name, &namelen);
char buffer[80];
const char\* p = inet\_ntop(AF\_INET, &name.sin\_addr, buffer, 80);
if(p != NULL)
{
std::cout << "Local IP address is: " << buffer << std::endl;
}
else
{
std::cout << "Error number: " << errno
<< ". Error message: " << strerror(errno) << std::endl;
}
close(sock);
return 0;
}
```
Upvotes: 4 <issue_comment>username_2: Thank you for your solution. It works fine. But When I search for solution, I came up with the following answer also. Please have a look at it. What is pros and cons of this answer.
```
FILE *f;
char line[100] , *p , *c;
f = fopen("/proc/net/route" , "r");
while(fgets(line , 100 , f))
{
p = strtok(line , " \t");
c = strtok(NULL , " \t");
if(p!=NULL && c!=NULL)
{
if(strcmp(c , "00000000") == 0)
{
printf("Default interface is : %s \n" , p);
break;
}
}
}
//which family do we require , AF_INET or AF_INET6
int fm = AF_INET;
struct ifaddrs *ifaddr, *ifa;
int family , s;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1)
{
perror("getifaddrs");
exit(EXIT_FAILURE);
}
//Walk through linked list, maintaining head pointer so we can free list later
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL)
{
continue;
}
family = ifa->ifa_addr->sa_family;
if(strcmp( ifa->ifa_name , p) == 0)
{
if (family == fm)
{
s = getnameinfo( ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6) , host , NI_MAXHOST , NULL , 0 , NI_NUMERICHOST);
if (s != 0)
{
printf("getnameinfo() failed: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
printf("address: %s", host);
}
printf("\n");
}
}
freeifaddrs(ifaddr);
return 0;
```
Upvotes: 0 <issue_comment>username_3: None of these answers seemed good enough: either too much trouble walking through the interfaces or required connection to internet.
Here is a method based upon username_1's [answer](https://stackoverflow.com/a/49336660/11269176). It's basically the same but it connects a UDP socket rather than a TCP. As per [udp(7)](https://linux.die.net/man/7/udp), using `connect(3)` on a unbound UDP socket:
>
> will automatically assign a free local port [...] and bind the socket to INADDR\_ANY
>
>
>
Moreover, conversely to a TCP socket, connect(3) on a UDP socket does not present any network overhead or communication, as it only changes the rules regarding which packet to drop and which to keep on the socket buffers.
Therefore, connecting to any IP address that is not `INADDR_LOOPBACK` is sufficient to retrieve a local address which has been chosen to bind the socket.
```
#include
#include
#include
#include
#include
#include
int main(void) {
int sock = socket(PF\_INET, SOCK\_DGRAM, 0);
sockaddr\_in loopback;
if (sock == -1) {
std::cerr << "Could not socket\n";
return 1;
}
std::memset(&loopback, 0, sizeof(loopback));
loopback.sin\_family = AF\_INET;
loopback.sin\_addr.s\_addr = 1337; // can be any IP address
loopback.sin\_port = htons(9); // using debug port
if (connect(sock, reinterpret\_cast(&loopback), sizeof(loopback)) == -1) {
close(sock);
std::cerr << "Could not connect\n";
return 1;
}
socklen\_t addrlen = sizeof(loopback);
if (getsockname(sock, reinterpret\_cast(&loopback), &addrlen) == -1) {
close(sock);
std::cerr << "Could not getsockname\n";
return 1;
}
close(sock);
char buf[INET\_ADDRSTRLEN];
if (inet\_ntop(AF\_INET, &loopback.sin\_addr, buf, INET\_ADDRSTRLEN) == 0x0) {
std::cerr << "Could not inet\_ntop\n";
return 1;
} else {
std::cout << "Local ip address: " << buf << "\n";
}
}
```
Upvotes: 4 <issue_comment>username_4: Cool method of getting local ip is to execute the ipconfig command, save the output to a file read it, and parse the data so the output only shows your ipv4 address for example.
Can be done with something like this:
```
std::string GetParsedIPConfigData(std::string Columb)
{
//Set up command file path and command line command
std::string APPDATA = getenv("APPDATA");
std::string path = APPDATA + "\\localipdata.txt";
std::string cmd = "ipconfig > " + path;
//execute ipconfig command and save file to path
system(cmd.c_str());
//current line
std::string line;
//Line array : Here is all lines saved
std::string lineArray[500];
int arrayCount = 0;
std::ifstream file(path);
if (file.is_open())
{
//Get all lines
while (std::getline(file, line))
{
//Save each line into a element in an array
lineArray[arrayCount] = line;
arrayCount++;
}
for (int arrayindex = 0; arrayindex <= arrayCount; arrayindex++)
{
std::string s = Columb;
std::string s2 = ":";
//Search all lines and get pos
std::size_t i = lineArray[arrayindex].find(s);
std::size_t i2 = lineArray[arrayindex].find(s2);
//Found a match for Columb
if (lineArray[arrayindex].find(s) != std::string::npos)
{
//Validate
if (i != std::string::npos)
{
//Earse Columb name
lineArray[arrayindex].erase(i, s.length());
//Erase all blanks
lineArray[arrayindex].erase(remove_if(lineArray[arrayindex].begin(), lineArray[arrayindex].end(), isspace), lineArray[arrayindex].end());
//Found match for ':'
if (lineArray[arrayindex].find(s2) != std::string::npos)
{
//Validate
if (i2 != std::string::npos)
{
//Delete all characters prior to ':'
lineArray[arrayindex].erase(0, lineArray[arrayindex].find(":"));
lineArray[arrayindex].erase(std::remove(lineArray[arrayindex].begin(), lineArray[arrayindex].end(), ':'), lineArray[arrayindex].end());
}
}
//Return our data
return lineArray[arrayindex];
}
}
//Only go through all lines once
if (arrayindex == arrayCount)
break;
}
//Close file
file.close();
}
//Something went wrong
return "Invalid";
}
```
And the just call it like so:
```
cout << parser.GetParsedIPConfigData("IPv4 Address") << "\n\n";
```
Upvotes: 0
|
2018/03/17
| 2,728 | 9,679 |
<issue_start>username_0: Can somebody tell me what the equivalent of this answer <https://stackoverflow.com/a/27312494/9507009> without lambda expression, please ?
>
> Extra: One-shot AsyncTask Example
>
>
>
> ```
> class InternetCheck extends AsyncTask {
>
> private Consumer mConsumer;
> public interface Consumer { void accept(Boolean internet); }
>
> public InternetCheck(Consumer consumer) { mConsumer = consumer; execute(); }
>
> @Override protected Boolean doInBackground(Void... voids) { try {
> Socket sock = new Socket();
> sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
> sock.close();
> return true;
> } catch (IOException e) { return false; } }
>
> @Override protected void onPostExecute(Boolean internet) { mConsumer.accept(internet); }
> }
>
> ///////////////////////////////////////////////////////////////////////////////////
> // Usage
>
> new InternetCheck(internet -> { /\* do something with boolean response \*/ });
>
> ```
>
><issue_comment>username_1: >
> I want to get my IP address whatever the interface name is.
>
>
>
It is difficult to reliably get the local ip address by looking at the network interface. As you have already discovered, the network interface name can be unique for each host you run on. To further complicate things, a computer may have multiple network interfaces and each of those may or may not be connected to the Internet.
You don't need to use the default interface. A more simplistic approach is to just let the OS routing table figure it out for you. You can do this by setting up a socket connection to some external server and then calling [`getsockname`](http://man7.org/linux/man-pages/man2/getsockname.2.html) to get the local address. This example uses Google's DNS server at `8.8.8.8` to establish a socket connection but you can use whatever external server you'd like.
```
#include ///< cout
#include ///< memset
#include ///< errno
#include ///< socket
#include ///< sockaddr\_in
#include ///< getsockname
#include ///< close
int main()
{
const char\* google\_dns\_server = "8.8.8.8";
int dns\_port = 53;
struct sockaddr\_in serv;
int sock = socket(AF\_INET, SOCK\_DGRAM, 0);
//Socket could not be created
if(sock < 0)
{
std::cout << "Socket error" << std::endl;
}
memset(&serv, 0, sizeof(serv));
serv.sin\_family = AF\_INET;
serv.sin\_addr.s\_addr = inet\_addr(google\_dns\_server);
serv.sin\_port = htons(dns\_port);
int err = connect(sock, (const struct sockaddr\*)&serv, sizeof(serv));
if (err < 0)
{
std::cout << "Error number: " << errno
<< ". Error message: " << strerror(errno) << std::endl;
}
struct sockaddr\_in name;
socklen\_t namelen = sizeof(name);
err = getsockname(sock, (struct sockaddr\*)&name, &namelen);
char buffer[80];
const char\* p = inet\_ntop(AF\_INET, &name.sin\_addr, buffer, 80);
if(p != NULL)
{
std::cout << "Local IP address is: " << buffer << std::endl;
}
else
{
std::cout << "Error number: " << errno
<< ". Error message: " << strerror(errno) << std::endl;
}
close(sock);
return 0;
}
```
Upvotes: 4 <issue_comment>username_2: Thank you for your solution. It works fine. But When I search for solution, I came up with the following answer also. Please have a look at it. What is pros and cons of this answer.
```
FILE *f;
char line[100] , *p , *c;
f = fopen("/proc/net/route" , "r");
while(fgets(line , 100 , f))
{
p = strtok(line , " \t");
c = strtok(NULL , " \t");
if(p!=NULL && c!=NULL)
{
if(strcmp(c , "00000000") == 0)
{
printf("Default interface is : %s \n" , p);
break;
}
}
}
//which family do we require , AF_INET or AF_INET6
int fm = AF_INET;
struct ifaddrs *ifaddr, *ifa;
int family , s;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1)
{
perror("getifaddrs");
exit(EXIT_FAILURE);
}
//Walk through linked list, maintaining head pointer so we can free list later
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL)
{
continue;
}
family = ifa->ifa_addr->sa_family;
if(strcmp( ifa->ifa_name , p) == 0)
{
if (family == fm)
{
s = getnameinfo( ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6) , host , NI_MAXHOST , NULL , 0 , NI_NUMERICHOST);
if (s != 0)
{
printf("getnameinfo() failed: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
printf("address: %s", host);
}
printf("\n");
}
}
freeifaddrs(ifaddr);
return 0;
```
Upvotes: 0 <issue_comment>username_3: None of these answers seemed good enough: either too much trouble walking through the interfaces or required connection to internet.
Here is a method based upon username_1's [answer](https://stackoverflow.com/a/49336660/11269176). It's basically the same but it connects a UDP socket rather than a TCP. As per [udp(7)](https://linux.die.net/man/7/udp), using `connect(3)` on a unbound UDP socket:
>
> will automatically assign a free local port [...] and bind the socket to INADDR\_ANY
>
>
>
Moreover, conversely to a TCP socket, connect(3) on a UDP socket does not present any network overhead or communication, as it only changes the rules regarding which packet to drop and which to keep on the socket buffers.
Therefore, connecting to any IP address that is not `INADDR_LOOPBACK` is sufficient to retrieve a local address which has been chosen to bind the socket.
```
#include
#include
#include
#include
#include
#include
int main(void) {
int sock = socket(PF\_INET, SOCK\_DGRAM, 0);
sockaddr\_in loopback;
if (sock == -1) {
std::cerr << "Could not socket\n";
return 1;
}
std::memset(&loopback, 0, sizeof(loopback));
loopback.sin\_family = AF\_INET;
loopback.sin\_addr.s\_addr = 1337; // can be any IP address
loopback.sin\_port = htons(9); // using debug port
if (connect(sock, reinterpret\_cast(&loopback), sizeof(loopback)) == -1) {
close(sock);
std::cerr << "Could not connect\n";
return 1;
}
socklen\_t addrlen = sizeof(loopback);
if (getsockname(sock, reinterpret\_cast(&loopback), &addrlen) == -1) {
close(sock);
std::cerr << "Could not getsockname\n";
return 1;
}
close(sock);
char buf[INET\_ADDRSTRLEN];
if (inet\_ntop(AF\_INET, &loopback.sin\_addr, buf, INET\_ADDRSTRLEN) == 0x0) {
std::cerr << "Could not inet\_ntop\n";
return 1;
} else {
std::cout << "Local ip address: " << buf << "\n";
}
}
```
Upvotes: 4 <issue_comment>username_4: Cool method of getting local ip is to execute the ipconfig command, save the output to a file read it, and parse the data so the output only shows your ipv4 address for example.
Can be done with something like this:
```
std::string GetParsedIPConfigData(std::string Columb)
{
//Set up command file path and command line command
std::string APPDATA = getenv("APPDATA");
std::string path = APPDATA + "\\localipdata.txt";
std::string cmd = "ipconfig > " + path;
//execute ipconfig command and save file to path
system(cmd.c_str());
//current line
std::string line;
//Line array : Here is all lines saved
std::string lineArray[500];
int arrayCount = 0;
std::ifstream file(path);
if (file.is_open())
{
//Get all lines
while (std::getline(file, line))
{
//Save each line into a element in an array
lineArray[arrayCount] = line;
arrayCount++;
}
for (int arrayindex = 0; arrayindex <= arrayCount; arrayindex++)
{
std::string s = Columb;
std::string s2 = ":";
//Search all lines and get pos
std::size_t i = lineArray[arrayindex].find(s);
std::size_t i2 = lineArray[arrayindex].find(s2);
//Found a match for Columb
if (lineArray[arrayindex].find(s) != std::string::npos)
{
//Validate
if (i != std::string::npos)
{
//Earse Columb name
lineArray[arrayindex].erase(i, s.length());
//Erase all blanks
lineArray[arrayindex].erase(remove_if(lineArray[arrayindex].begin(), lineArray[arrayindex].end(), isspace), lineArray[arrayindex].end());
//Found match for ':'
if (lineArray[arrayindex].find(s2) != std::string::npos)
{
//Validate
if (i2 != std::string::npos)
{
//Delete all characters prior to ':'
lineArray[arrayindex].erase(0, lineArray[arrayindex].find(":"));
lineArray[arrayindex].erase(std::remove(lineArray[arrayindex].begin(), lineArray[arrayindex].end(), ':'), lineArray[arrayindex].end());
}
}
//Return our data
return lineArray[arrayindex];
}
}
//Only go through all lines once
if (arrayindex == arrayCount)
break;
}
//Close file
file.close();
}
//Something went wrong
return "Invalid";
}
```
And the just call it like so:
```
cout << parser.GetParsedIPConfigData("IPv4 Address") << "\n\n";
```
Upvotes: 0
|
2018/03/17
| 1,425 | 5,960 |
<issue_start>username_0: Let's say we use Java SE (no libraries) and have the following situation. We have a class:
```
public class DriverInfo {
private final int age;
public DriverInfo(int age) {
this.age = age;
}
// getter here
}
```
In some countries there is a requirement that you can drive if you're 18 years old. In other words - we need to have some validation for **age** parameter. Something like:
```
if (age < 18) {
throw new IllegalArgumentException("Age is not valid!");
}
```
So, my question is - where this validation should be? My thoughts are as follows:
* On constructor add the **if()** described above. The validation would work if the constructor is called from multiple places on your code. My concern is that class constructors should (IMHO) not contain any logic. Am I right?
* Validate somewhere outside the constructor - whether it's a factory method, builder class etc. But then we are forcing developers to not instantiate the class by using the constructor, but to use some artificial factory/builder.
* To validate constructors parameters by using [Validate](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/Validate.html). It's not standard Java, but I saw people doing this. As for me it doesn't look right, because we're adding logic to the constructor - which doesn't look right for me.
* Any other good way I missed?
Any thoughts would be highly appreciated. Does anyone could suggest a best practice how to deal with the situation described abode?<issue_comment>username_1: I think there are two more techniques which you can use.
1. Pass variables to **super()** and validate them at parent class.
For example
>
> super(age)
>
>
>
2. You can use **getters**, **setters** and validate the variable there. I tried using setters in java.
```
public class validate_object_variable {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
if(this.age >= 18)
this.age = age;
else {
throw new IllegalArgumentException("Age is not valid!");
}
}
public static void main(String args[]) {
validate_object_variable obj = new validate_object_variable();
obj.setAge(10);
System.out.println(obj.getAge());
}
}
```
This gives me the ability to cleanly exit with a **valid exception** to the caller.
**OUTPUT**
[](https://i.stack.imgur.com/lRECs.png)
I think it would not be a nice idea to throw exceptions in a constructor. But it's a good choice to validate the variables using setters separately without hampering the object creation.
Upvotes: 0 <issue_comment>username_2: Validation in constructor is completely fine. This "no logic in constructor" rule does not apply on it, guess it's worded bit unfortunately. **Task of constructor is** to take dependencies from outside (dependency injection), make sure they are valid and then probably store them in instance attributes - **creating valid instance** in short.
This way the rules of what is valid and what is not valid are kept inside the object, not detached in some factory.
If the instance would be invalid, then throwing an exception, which explains what is wrong with parameters, is absolutely fine. It prevents invalid instances from roaming around system.
Also this way with immutable objects you get guaranteed that all existing instances are valid all the time, which is great.
Having some validation method on the object is possible and can be useful, but I'd prefer constructor validation any day. But if it's not possible, then it's better than nothing and it still keeps the rules for validity within the object. Like when some framework constructs your mutable object for you and requires parameterless constructor...you can forget to call it, but it's better than nothing.
Upvotes: 4 [selected_answer]<issue_comment>username_3: In my opinion, you should have a method inside the class DriverInfo, something like:
```
public boolean isDriverLegalAge(int age){
if (age < 18) {
return false;
} else {
return true;
}
}
```
The constructor should only be used to build the object. Everything related to logic inside that object should be inside methods.
For more information regarding the purpose of a constructor see this link: <https://stackoverflow.com/a/19941847/2497743>
Upvotes: -1 <issue_comment>username_4: I think you can "also" use `Builder` pattern for such use cases. Although Constructor validation is perfectly fine and usually Builder tend to introduce a lot of Boiler Plate code but if you want to avoid validation inside the constructor and also want to have immutable class (no setter validations) then you can give builders a try.
Usually builders should be used when faced with many constructor parameters. You can read more on builders [here](http://www.informit.com/articles/article.aspx?p=1216151&seqNum=2).
```
public class DriverInfo {
private final int age;
//more parameters here
private DriverInfo(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public static DriverInfoBuilder newBuilder() {
return new DriverInfoBuilder();
}
public static final class DriverInfoBuilder {
private int age;
private DriverInfoBuilder() {
}
public DriverInfoBuilder age(int age) {
this.age = age;
return this;
}
public DriverInfo build() {
if (age < 18) {
throw new IllegalArgumentException("Age is not valid!");
}
//other validations.
return new DriverInfo(age);
}
}
}
```
Again there are many ways to do this and there is no right and wrong here. Its more about what one prefers and will it be readable for other programmers or not.
Upvotes: 1
|
2018/03/17
| 1,330 | 5,444 |
<issue_start>username_0: I have the following validation function checking if a user exists:
```
validate.user = async (user, password) => {
const matches = await bcrypt.compare(password, user.password);
if (matches) return user;
if (!matches) {
return validate.logAndThrow('User password does not match');
}
return validate.logAndThrow('Error in bcrypt compare');
};
```
The following test using Chai should test this:
```
chai.use(sinonChai);
const { expect } = chai;
describe('#user', () => {
it('show throw if user is undefined', () => {
expect(() => validate.user(undefined, 'pass')).to.throw('User does not exist');
});
```
The error does get thrown, however mocha shows the following in the console:
>
> 2) show throw if user is undefined
> (node:18587) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: User does not exist
>
>
>
So my question is, how I can rewrite the test such that it does catch promise rejections?<issue_comment>username_1: I think there are two more techniques which you can use.
1. Pass variables to **super()** and validate them at parent class.
For example
>
> super(age)
>
>
>
2. You can use **getters**, **setters** and validate the variable there. I tried using setters in java.
```
public class validate_object_variable {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
if(this.age >= 18)
this.age = age;
else {
throw new IllegalArgumentException("Age is not valid!");
}
}
public static void main(String args[]) {
validate_object_variable obj = new validate_object_variable();
obj.setAge(10);
System.out.println(obj.getAge());
}
}
```
This gives me the ability to cleanly exit with a **valid exception** to the caller.
**OUTPUT**
[](https://i.stack.imgur.com/lRECs.png)
I think it would not be a nice idea to throw exceptions in a constructor. But it's a good choice to validate the variables using setters separately without hampering the object creation.
Upvotes: 0 <issue_comment>username_2: Validation in constructor is completely fine. This "no logic in constructor" rule does not apply on it, guess it's worded bit unfortunately. **Task of constructor is** to take dependencies from outside (dependency injection), make sure they are valid and then probably store them in instance attributes - **creating valid instance** in short.
This way the rules of what is valid and what is not valid are kept inside the object, not detached in some factory.
If the instance would be invalid, then throwing an exception, which explains what is wrong with parameters, is absolutely fine. It prevents invalid instances from roaming around system.
Also this way with immutable objects you get guaranteed that all existing instances are valid all the time, which is great.
Having some validation method on the object is possible and can be useful, but I'd prefer constructor validation any day. But if it's not possible, then it's better than nothing and it still keeps the rules for validity within the object. Like when some framework constructs your mutable object for you and requires parameterless constructor...you can forget to call it, but it's better than nothing.
Upvotes: 4 [selected_answer]<issue_comment>username_3: In my opinion, you should have a method inside the class DriverInfo, something like:
```
public boolean isDriverLegalAge(int age){
if (age < 18) {
return false;
} else {
return true;
}
}
```
The constructor should only be used to build the object. Everything related to logic inside that object should be inside methods.
For more information regarding the purpose of a constructor see this link: <https://stackoverflow.com/a/19941847/2497743>
Upvotes: -1 <issue_comment>username_4: I think you can "also" use `Builder` pattern for such use cases. Although Constructor validation is perfectly fine and usually Builder tend to introduce a lot of Boiler Plate code but if you want to avoid validation inside the constructor and also want to have immutable class (no setter validations) then you can give builders a try.
Usually builders should be used when faced with many constructor parameters. You can read more on builders [here](http://www.informit.com/articles/article.aspx?p=1216151&seqNum=2).
```
public class DriverInfo {
private final int age;
//more parameters here
private DriverInfo(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public static DriverInfoBuilder newBuilder() {
return new DriverInfoBuilder();
}
public static final class DriverInfoBuilder {
private int age;
private DriverInfoBuilder() {
}
public DriverInfoBuilder age(int age) {
this.age = age;
return this;
}
public DriverInfo build() {
if (age < 18) {
throw new IllegalArgumentException("Age is not valid!");
}
//other validations.
return new DriverInfo(age);
}
}
}
```
Again there are many ways to do this and there is no right and wrong here. Its more about what one prefers and will it be readable for other programmers or not.
Upvotes: 1
|
2018/03/17
| 539 | 1,912 |
<issue_start>username_0: Here's a strip of my code:
```
$("#body").val("Dear Supplier,\n\nWe would like to cancel our order of
[product specifications] made on [date of order submission].
Please send us a reply to provide confirmation at earliest convenience.
\nThank you.\n\nYours sincerely,\n...");
```
Is there any way of making the "[product specifications]" part bold? I tried surrounding it inside the tags [but that didn't work.](https://i.stack.imgur.com/gQ0yt.jpg)
EDIT: My #body field is a text area.<issue_comment>username_1: The `.val()` allows you to change the **value** of your cibling element. Olr, what you need is to insert code / or replace the existing one with **HTML** tags. SO if you just use the `.html()` function in jQuery it should fit your needs. Here how to do :
```
$("#body").html("**D**ear Supplier,\n\nWe would like to cancel our order of
[product specifications] made on [date of order submission].
Please send us a reply to provide confirmation at earliest convenience.
\nThank you.\n\nYours sincerely,\n...");
```
Upvotes: -1 <issue_comment>username_2: Maybe you could use a `div` with `contenteditable="true"` instead: $('div#body').html(yourText).
This is if you still want bold phrases in an element but want to maintain the input feature.
Upvotes: 0 <issue_comment>username_3: $("#body").html("Dear Supplier,\n\nWe would like to cancel our order of \
**[product specifications]** made on [date of order submission]. \
Please send us a reply to provide confirmation at earliest convenience. \
\nThank you.\n\nYours sincerely,\n...");
Upvotes: -1 <issue_comment>username_4: >
> Is there any way of making the "[product specifications]" part bold? I tried surrounding it inside the tags but that didn't work.
>
>
>
No, it's not possible with .
You have to resort to a [WYSIWYG](https://en.wikipedia.org/wiki/WYSIWYG) editor.
Upvotes: 3 [selected_answer]
|
2018/03/17
| 907 | 3,703 |
<issue_start>username_0: With the code below:
```
function create_table() {
$.ajax({
method: "GET",
url: "/api/data/",
success: function(data){
$('#table').load('http://127.0.0.1:8000/results');
$('#go_back').remove();
},
error: function(error_data){
console.log("errorrr")
console.log(error_data)
}
})
}
document.getElementById("create_table").onclick = function() {
create_table();
return false;
}
```
I want to remove `#go_back` element after `#table` element is loaded. The problem is it doesn't get removed because the code doesn't wait for `#go_back` to appear.
How do I make the script wait before those `.load` and `.remove` methods?<issue_comment>username_1: There is a callback function in JQuery `load()` function that is triggered when the load completes. Thus, put that code inside the callback which will only execute after the `load()` operation is completed.
```
function create_table() {
$.ajax({
method: "GET",
url: "/api/data/",
success: function(data){
$('#table').load('http://127.0.0.1:8000/results', function(){
$('#go_back').remove();
});
},
error: function(error_data){
console.log("errorrr")
console.log(error_data)
}
})
}
document.getElementById("create_table").onclick = function() {
create_table();
return false;
}
```
Upvotes: 1 <issue_comment>username_2: The issue you are having is that the `load` function is asynchronous, while the `remove` function you are calling is synchronous. The rough sequence of events is below.
* an AJAX request is performed
* the AJAX request returns success
* the success callback is called
* the `load` function makes a second asynchronous call to localhost to load the results into an element identified with ID `table`
* the 'load' function takes some time to complete
* in the meantime, the `remove` function is called
* the `remove` function inspects the DOM (Document Object Model) for an element matching ID `go_back`
* no matching element is found, because the `load` function has not yet returned
* the `load` function returns, and populates the inner HTML of the table element
The solution to your problem is to understand that any changes to be made to the contents of the table element must be made *after* the load function returns. This is accomplished by consulting the jQuery documentation [jQuery Load](http://api.jquery.com/load/) to find out how to place a hook to the completion of the `load` function. This modification should accomplish what you want:
```js
$('#table').load('http://127.0.0.1:8000/results', function(){
$('#go_back').remove();
});
```
In essence, pass a second parameter to the `load` function, which is another callback function. Inside this callback function, any code will be executed after the inner contents of the table element have been modified. Therefore the `go_back` element should be found and removed.
Upvotes: 3 [selected_answer]<issue_comment>username_3: The .load function actually creates an Ajax call. You are using Ajax to get 'data', doing nothing with it and then using another Ajax call to get the result which I assume is some html.
You could get your Ajax function to populate the html based on the data rather than doing a second call.
I'm not sure if there is a .done func available from .load. But if there is you can remove the element in there.
Or, you can keep as is and change the .load function to a proper Ajax call and populate the table html in the success func, along with removing the element.
Upvotes: 1
|
2018/03/17
| 990 | 3,790 |
<issue_start>username_0: I am trying to fill-up page numbers of a Book in [its Index Wikisource page](https://ta.wikisource.org/s/5be). The following code writes well in the specific pageNumber parameter.
If the page is empty, it looks fine. But if i run the code another time, due to the concatenation the 67 becomes 6767. How can i know that the pageNumber parameter (`'|Number of pages='`) is empty? or If the parameter already filled how can i set the skip option in the code.
The writing code;-
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pywikibot
indexTitle = 'அட்டவணை:தமிழ் நாடகத் தலைமை ஆசிரியர்-2.pdf'
indexPages = '67'
site1 = pywikibot.Site('ta', 'wikisource')
page = pywikibot.Page(site1, indexTitle)
indexTitlePage = page.text.replace('|Number of pages=','|Number of pages='+indexPages)
page.save(summary='67')
```<issue_comment>username_1: There is a callback function in JQuery `load()` function that is triggered when the load completes. Thus, put that code inside the callback which will only execute after the `load()` operation is completed.
```
function create_table() {
$.ajax({
method: "GET",
url: "/api/data/",
success: function(data){
$('#table').load('http://127.0.0.1:8000/results', function(){
$('#go_back').remove();
});
},
error: function(error_data){
console.log("errorrr")
console.log(error_data)
}
})
}
document.getElementById("create_table").onclick = function() {
create_table();
return false;
}
```
Upvotes: 1 <issue_comment>username_2: The issue you are having is that the `load` function is asynchronous, while the `remove` function you are calling is synchronous. The rough sequence of events is below.
* an AJAX request is performed
* the AJAX request returns success
* the success callback is called
* the `load` function makes a second asynchronous call to localhost to load the results into an element identified with ID `table`
* the 'load' function takes some time to complete
* in the meantime, the `remove` function is called
* the `remove` function inspects the DOM (Document Object Model) for an element matching ID `go_back`
* no matching element is found, because the `load` function has not yet returned
* the `load` function returns, and populates the inner HTML of the table element
The solution to your problem is to understand that any changes to be made to the contents of the table element must be made *after* the load function returns. This is accomplished by consulting the jQuery documentation [jQuery Load](http://api.jquery.com/load/) to find out how to place a hook to the completion of the `load` function. This modification should accomplish what you want:
```js
$('#table').load('http://127.0.0.1:8000/results', function(){
$('#go_back').remove();
});
```
In essence, pass a second parameter to the `load` function, which is another callback function. Inside this callback function, any code will be executed after the inner contents of the table element have been modified. Therefore the `go_back` element should be found and removed.
Upvotes: 3 [selected_answer]<issue_comment>username_3: The .load function actually creates an Ajax call. You are using Ajax to get 'data', doing nothing with it and then using another Ajax call to get the result which I assume is some html.
You could get your Ajax function to populate the html based on the data rather than doing a second call.
I'm not sure if there is a .done func available from .load. But if there is you can remove the element in there.
Or, you can keep as is and change the .load function to a proper Ajax call and populate the table html in the success func, along with removing the element.
Upvotes: 1
|
2018/03/17
| 1,200 | 4,400 |
<issue_start>username_0: I am following couple of tutorials for random hex generation for a map. I am currently trying to randomly generate continents based on single hex on the map by getting other hexes surrounding that particular hex.
This is my code for putting all the neighboring hexes into an array:
```
public HexCell[] GetHexWithinRange (HexCell centerHex, int range)
{
List hexWithinRange = new List();
int x = centerHex.coordinates.X;
int y = centerHex.coordinates.Y;
int z = centerHex.coordinates.Z;
int sequence = 0;
for (int dy = -range; dy < range + 1; dy++)
{
for (int dz = -range; dz < range + 1; dz++)
{
for (int dx = -range; dx < range + 1; dx++)
{
HexCell neighborHex = GetCellFromCoord(x + (float)dx,
y + (float)dy, z + (float)dz);
if (neighborHex == null)
{ continue; }
else
{
neighborHex.sequenceCheck = sequence++;
hexWithinRange.Add(neighborHex);
}
}
}
}
return hexWithinRange.ToArray();
}
```
[Perfectly hexagonal shaped continent](https://i.stack.imgur.com/hoeXW.png)
Although the code return a perfectly shaped continent, it is putting the other hexes diagonally from the outside ring into the center hex:
[Sequence when the code is putting the neighboring hex into array](https://i.stack.imgur.com/kqtPa.png)
What I would really want it to do is to get the neighboring hex from within the continent and move outside from there until it reaches the intended radius such as this:
[Sequence how I want the code to put the neighboring hex into array](https://i.stack.imgur.com/Te0jP.png)
I tried coming out with a formula to put the neighboring hexes in the array ring-by-ring. But I'd like to keep my radius from center hex to be a variable. How do I do that?<issue_comment>username_1: Notice that you want to walk each "axis" by the radius.
For example, if you start at [36,-57,21] with Radius == 1, you move 1 Hex along X, then 1 along Y, then 1 along z, then backward along X, Y and Z, and arrive back at [36, -57, 21].
When Radius == 2, its the same, only you march each axis 2 times. And so on.
So, I think something like this would work (if your Vector3 hex representation is correct and has addition defined)
```
var center = centerHex.coordinates;
var offset = new Vector3(0, 0, 0);
int radius = 0;
for(radius = 0; radius < 4 radius ++){
for(i = 0; i < radius; i++){
AddCell(center + offset);
offset.X++;
}
for(i = 0; i < radius; i++){
AddCell(center + offset);
offset.Y--;
}
for(i = 0; i < radius; i++){
AddCell(center + offset);
offset.Z--;
}
for(i = 0; i < radius; i++){
AddCell(center + offset);
offset.X--;
}
for(i = 0; i < radius; i++){
AddCell(center + offset);
offset.Y++;
}
for(i = 0; i < radius; i++){
AddCell(center + offset);
offset.Z++;
}
offset.Z++;
}
```
}
Upvotes: 1 <issue_comment>username_2: I figured it out. Instead of using the range as the limit for the loop, I created an incremental range within the original range. To avoid the initial problem crops up again, I make it that the loop check for a duplicates cell in the list/array before adding the cell it is currently on.
```
for (int curRange = 1; curRange < range + 1; curRange++)
{
for (int dy = -curRange; dy < curRange + 1; dy++)
{
for (int dz = -curRange; dz < curRange + 1; dz++)
{
for (int dx = -curRange; dx < curRange + 1; dx++)
{
HexCell neighborHex = GetCellFromCoord(x + (float)dx, y + (float)dy, z + (float)dz);
if (neighborHex == null)
{
continue;
}
else if (x == neighborHex.coordinates.X &&
y == neighborHex.coordinates.Y &&
z == neighborHex.coordinates.Z)
{
continue;
}
else
{
if (hexWithinRange.Contains(neighborHex))
{
continue;
}
else
{
hexWithinRange.Add(neighborHex);
}
}
}
}
}
}
```
Upvotes: 1 [selected_answer]
|
2018/03/17
| 785 | 2,971 |
<issue_start>username_0: I'm newbie to JS. I've a code sample below, in which I've written a JS function through which I'm trying to change value of <**p**> tag after a button click. My question is why only setting **innerHTML** work with 'getElementById()'; but not with the other approaches?
```
function myFunction() {
document.getElementById("myid").innerHTML = 'hey';
document.getElementByName("myname").innerHTML = 'Whats';
document.getElementByTagName("p").innerHTML = 'up! ';
document.querySelector("p#myid").innerHTML = 'Dude.';
}
This text will be changed after button click.
Try it
```
**Result:** I was Expecting "Dude." displayed after the click.
[](https://i.stack.imgur.com/YpMa5.png)<issue_comment>username_1: I'm sure `document.querySelectorAll`, `document.getElementsByClassName` and `document.getElementsByTagName` will return a NodeList object. However, `document.querySelector` should return the first match of that element within the given context (document).
Upvotes: 1 <issue_comment>username_2: The script fails on the `document.getElementByName("myname").innerHTML = 'Whats';` line, because `getElementByName` is not a function, and it errors when the script tries to call it. The correct name is [`getElementsByName`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName); element**s**. Same for [`getElementsByTagName`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName).
Also, both functions return lists of elements and not single elements. Because of that, here, you want to use `[0]` to get the first element in that list, then work with it that way:
```
document.getElementsByName("myname")[0].innerHTML = 'Whats';
```
Use `F12` or `Ctrl`+`Shift`+`I` (depending on the browser) to open up your browser console to see errors, and consult the documentation (from the site I linked for example) to make sure you're using the right function.
Upvotes: 2 <issue_comment>username_3: ```html
function myFunction() {
debugger;
document.getElementById("myid").innerHTML = 'hey';
document.getElementsByName("myname").innerHTML = 'Whats';
document.getElementsByTagName("p").innerHTML = 'up! ';
document.querySelector("p#myid").innerHTML = 'Dude.';
}
This text will be changed after button click.
Try it
```
Here you have wrote document.getElementByName("myname").innerHTML = 'Whats';
which is not correct it must be document.getElementsByName("myname").innerHTML = 'Whats'; Try this It works.
FYI document.getElementsByName return array of elements with same name .
Upvotes: 2 <issue_comment>username_4: Change as follows, it works
```
document.getElementById("myid").innerHTML = 'hey';
document.getElementsByName("myname")[0].innerHTML = 'Whats';
document.getElementsByTagName("p")[0].innerHTML = 'up! ';
document.querySelector("p#myid").innerHTML = 'Dude.';
```
Upvotes: 3 [selected_answer]
|
2018/03/17
| 1,502 | 4,416 |
<issue_start>username_0: I am trying to find all the items between two given indexes.
for eg: i have list that looks like this:
```
mylist = ['ABC', 'COMMENT', 'YES', 'YES', 'NO', '123', 'COMMENT','GONOW','MAKE','COMMENT', 'YES','COMMENT']
```
i want the output to be show as below:
**Note: Below outputs are the index value between two 'COMMENT'.**
```
First output : 'YES', 'YES', 'NO', '123'
second output : 'GONOW','MAKE'
third output : 'YES'
```
I have two thoughts to handle this situation:
1) if i know the search\_string as 'COMMENT' then i should be able find everything between two known strings, something like this :
```
string = 'COMMENT'
find_values = mylist[findfirst(comment)-findsecond(comment)]
find_values = mylist[findsecond(comment)-findthird(comment)]
```
2) if i know the index of all 'COMMENT' then i should be able find\_all between two known indexs, something like this :
```
idx1_comment = 1
idx2_comment = 6
idx3_comment = 9
print mylist(range(2-5))
print mylist(range(6-8))
```
Any ideas?
Thanks...
Also, i have another request.
For #1 option, if i have list wherein i have a lot of items between strings 'comment' and 'border' then what be the way for that as well?
Btw, i tried following this article, but with no benefit.
[Python: get items from list between 2 known items](https://stackoverflow.com/questions/33018528/python-get-items-from-list-between-2-known-items)<issue_comment>username_1: Why not simply iterate the list once:
```
result = []
sublist = []
separators = ('COMMENT', 'BORDER')
mylist = ['ABC', 'COMMENT', 'YES', 'YES', 'NO', '123', 'COMMENT','GONOW','MAKE','COMMENT', 'YES','COMMENT', 'BORDER', 'FOO', '123']
for x in mylist:
if x in separators:
if sublist:
result.append(sublist)
sublist = []
else:
sublist.append(x)
result.append(sublist)
print (result)
```
Returns:
```
[['ABC'], ['YES', 'YES', 'NO', '123'], ['GONOW', 'MAKE'], ['YES'], ['FOO', '123']]
```
Upvotes: 2 <issue_comment>username_2: If all you want is to filter out the strings between two predefined strings, this code will do:
```
def filter_output_between_strings(input: [str], separator: str):
separator_indexes = [index for index, word in enumerate(input) if word == separator]
for example_index, (start, end) in enumerate(zip(separator_indexes[:-1], separator_indexes[1:]), start=1):
print('Example: {}: {}'.format(example_index, input[start + 1:end]))
if __name__ == '__main__':
input = ['ABC', 'COMMENT', 'YES', 'YES', 'NO', '123', 'COMMENT', 'GONOW', 'MAKE', 'COMMENT', 'YES', 'COMMENT']
filter_output_between_strings(input, 'COMMENT')
```
Output:
```
Example: 1: ['YES', 'YES', 'NO', '123']
Example: 2: ['GONOW', 'MAKE']
Example: 3: ['YES']
```
Upvotes: 1 <issue_comment>username_3: You could leverage [islice](https://docs.python.org/2/library/itertools.html#itertools.islice) on itertools:
```
from itertools import islice
mylist = ['ABC', 'COMMENT', 'YES', 'YES', 'NO', '123', 'COMMENT','GONOW','MAKE','COMMENT', 'YES','COMMENT']
# get indexes of all 'COMMENT'
idx = [i for i,v in enumerate(mylist) if v in [ 'COMMENT']]
print(idx)
# calculate tuples of data we are interested in:
# ( commentIdx+1 , next commentIdx ) for all found ones
idx2 = [ (idx[i]+1,idx[i+1]) for i in range(len(idx)-1)]
print(idx2)
# slice the data out of our list and create lists of the slices
result = [ list(islice(mylist,a,b)) for a,b in idx2]
print(result)
```
Output:
```
[1, 6, 9, 11] # indexes of 'COMMENT'
[(2, 6), (7, 9), (10, 11)] # Commentindex +1 + the next one as tuple
[['YES', 'YES', 'NO', '123'], ['GONOW', 'MAKE'], ['YES']]
```
You could also skip `idx2`:
```
result = [ list(islice(mylist,a,b)) for a,b in ((idx[i]+1,idx[i+1]) for i in range(len(idx)-1))]
```
---
As for your 2nd question - which should probably be solved by yourself or posted as seperate question:
It depends on the data - do they intermix (`C = COMMENT, B = BORDER`) ?
```
[ C, 1, 2 , C , 3 , B , 4 , B, 5, C ]
```
Best probably to try it yourself or post a new question with sample data and wanted output. The above one could be
`[ [1,2],[3],[4] ]` or `[ [1,2],[3],[3,4,5],[4,5],[5]` or something in between - the first uses strict C-C and B-B and no C-B or B-C matches. The latter allowes C-B and B-C as well as C-......-C ignoring/removing B's in between
Upvotes: 1 [selected_answer]
|
2018/03/17
| 1,181 | 4,191 |
<issue_start>username_0: I have a `User` model that has a child association of `items`. The `:name` of items should be unique for the user, but it should allow different users to have an item with the same name.
The Item model is currently set up as:
```
class Item < ApplicationRecord
belongs_to :user
validates :name, case_sensitive: false, uniqueness: { scope: :user }
end
```
And this works to validate intra-user, but still allows other users to save an Item with the same name.
How do I test this with RSpec/Shoulda?
My current test is written as:
```
describe 'validations' do
it { should validate_uniqueness_of(:name).case_insensitive.scoped_to(:user) }
end
```
But this test fails because:
```
Failure/Error: it { should validate_uniqueness_of(:name).scoped_to(:user).case_insensitive }
Item did not properly validate that :name is case-insensitively
unique within the scope of :user.
After taking the given Item, setting its :name to ‹"an
arbitrary value"›, and saving it as the existing record, then making a
new Item and setting its :name to a different value, ‹"AN
ARBITRARY VALUE"› and its :user to a different value, ‹nil›, the
matcher expected the new Item to be invalid, but it was valid
instead.
```
This however, is the behavior that I want (other than the weird part that Shoulda picks `nil` for user). When the user is different, the same name should be valid.
It's possible that I'm not using the scope test correctly or that this is impossible with Shoulda, here is [the description of scoped tests](https://github.com/thoughtbot/shoulda-matchers/blob/cd96089a56b97cd11f7502826636895253eca27d/lib/shoulda/matchers/active_record/validate_uniqueness_of_matcher.rb#L140). In this case, how would you write a model test to test this behavior?<issue_comment>username_1: The solution to doing this is three-fold:
1. Scope to `:user_id` instead of `:user` in the model
2. Re-write the validations on the model to include all uniqueness requirements as part of a hash
3. Scope the test to `:user_id`
The code in the question will work in that it correctly checks for uniqueness case-insensitively, but it is probably best to include all uniqueness requirements as hash anyway since the example in [the docs](http://guides.rubyonrails.org/active_record_validations.html#uniqueness) takes this form even for single declarations (also, it's the only way I can find to make Shoulda tests pass with the correct behavior).
This is what the working code looks like:
model
```
class Item < ApplicationRecord
belongs_to :user
validates :name, uniqueness: { scope: :user_id, case_sensitive: false }
end
```
test
```
RSpec.describe Item, type: :model do
describe 'validations' do
it { should validate_uniqueness_of(:name).scoped_to(:user_id).case_insensitive }
end
end
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: I tried this with an `enum`
model
```
validates(:plan_type,
uniqueness: { scope: :benefit_class_id, case_sensitive: false })
enum plan_type: {
rrsp: 0,
dpsp: 1,
tfsa: 2,
nrsp: 3,
rpp: 4,
}
```
test
```
it { should validate_uniqueness_of(:plan_type).scoped_to(:benefit_class_id).case_insensitive }
```
but always got an error of the type (i.e. the `enum` value was uppercased in the test)
```
1) BenefitClass::RetirementPlan validations should validate that :plan_type is case-insensitively unique within the scope of :benefit_class_id
Failure/Error:
is_expected.to validate_uniqueness_of(:plan_type)
.scoped_to(:benefit_class_id).case_insensitive
ArgumentError:
'RPP' is not a valid plan_type
```
But I was able to write an explicit test that passed.
```
it 'validates uniqueness of plan_type scoped to benefit_class_id' do
rp1 = FactoryBot.create(:retirement_plan)
rp2 = FactoryBot.build(
:retirement_plan,
benefit_class_id: rp1.benefit_class_id,
plan_type: rp1.plan_type,
)
expect(rp2).to_not be_valid
end
```
Upvotes: 0
|
2018/03/17
| 699 | 2,762 |
<issue_start>username_0: So I was exploring PWAs today and followed [Your First Progressive Web App](https://developers.google.com/web/fundamentals/codelabs/your-first-pwapp/). It takes 5 mins and works on my laptop but the problem is, I can't figure out how to browse it through my phone yet. So I searched and found [How can I access my localhost from my Android device?](https://stackoverflow.com/questions/4779963/how-can-i-access-my-localhost-from-my-android-device) But unfortunately, the answers provided there don't work for me.
Why would that be? Does PWA require some different kind of setup? Am I going all wrong about this? Adiitionally I couldn't find any tutorials that take you to actually browsing your PWA in a mobile. Why?<issue_comment>username_1: Accessing PWA in any device browser is same as accessing any other web site. You simply access with the URL.
Problem in your case seem to be because you are accessing it as "localhost" in your mobile device. If you are running your web app in your desktop and if your mobile is also connected to the same network, access it using its IP address. Say
<https://192.168.1.1/myapp/> instead of <https://localhost/myapp/>. When you put localhost in any device, what it refers to is local device (your android phone in your case), which is not actually running the web app and its your laptop, which is not local, but remote for your android phone.
You can also pack your android app as a apk and side load it. [Try this site.](https://www.pwabuilder.com/)
Upvotes: 0 <issue_comment>username_2: While the [Your First Progressive Web App](https://developers.google.com/web/fundamentals/codelabs/your-first-pwapp/) tutorial tells you to start a server in your localhost. So as mentioned by @username_1, you won't be able to simply access the PWA in your phone.
The most **simple** solution is to use [ngrok](https://ngrok.com/product). Using it will expose a public URL for your web app which you can access in any device you want.
Simply install ngrok from [here](https://ngrok.com/download) and follow through.
Cheers ;)
Upvotes: 4 [selected_answer]<issue_comment>username_3: I had a similar problem . I installed ngrok and accessed the URL it provided from the device. It worked completely fine. Later I went through the link
<https://developers.google.com/web/tools/chrome-devtools/remote-debugging/>
In the settings, I enabled "discover USB devices and set up Port forwarding. Then, I was able to browse and debug the PWA ( which was running on my laptop), in the actual device. I understand if you have device next to your development machine, you can use remote devices USB debugging. If you want to show some demo from a remote place, you can use ngrok. Hope this helps!!!
Upvotes: 1
|
2018/03/17
| 1,156 | 4,465 |
<issue_start>username_0: I use ReflectionTestUtils to set int field in my service class to test the class.
My service class like:
```
@Service
public class SampleService {
@Value("${app.count}")
private int count;
@Value("${app.countStr}")
private String countStr;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getCountStr() {
return countStr;
}
public void setCountStr(String countStr) {
this.countStr = countStr;
}
@PostConstruct
public int demoMethod() {
return count + Integer.parseInt(countStr);
}
}
```
and test class is like:
```
@RunWith(SpringRunner.class)
public class SampleServiceTest {
@Autowired
private SampleService sampleService;
@TestConfiguration
static class SampleServiceTestConfig {
@Bean
public SampleService sampleService() {
return new SampleService();
}
}
@Before
public void init() {
ReflectionTestUtils.setField(sampleService, "count", new Integer(100));
ReflectionTestUtils.setField(sampleService, "countStr", 100);
}
@Test
public void testDemoMethod() {
int a = sampleService.demoMethod();
Assert.assertTrue(a == 200);
}
}
```
While I run this test case it gives below error:
```
Caused by: java.lang.NumberFormatException: For input string: "${app.count}"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.valueOf(Integer.java:766)
at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:210)
at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:115)
at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:466)
at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:439)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:192)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:117)
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:70)
... 47 more
```
Why ReflectionTestUtils try set string value in the field?
I put 2 fields, one is an integer and another is a string for testing purpose.
You can find source code [here](https://github.com/nitinvavdiya/junit-test-for-property).
Please have look and suggest a workaround for the same.<issue_comment>username_1: While testing, you have to provide properties source. If you don't add properties, it will inject the value inside `@Value` in the variable. In your case, it tries to add the string in the integer that gives `NumberFormatException`.
Try adding as below:
```
@RunWith(SpringRunner.class)
@TestPropertySource(properties = {"app.count=1", "app.countStr=sampleString"})
public class SampleServiceTest{...}
```
As you are using `@Autowired`, before `ReflectionTestUtils` it tries to add the value inside `@Value`.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Your problem is that the method annotated with `@Before` is invoked **after** that the spring context was initialized and that the service was injected by Spring in your test class.
Which means that these two fields :
```
@Value("${app.count}")
private int count;
@Value("${app.countStr}")
private String countStr;
```
will have as value the value defined in their `@Value` values.
`String countStr` can be valued with the `"${app.countStr}"` `String` (even it it makes no sense).
But `int count` cannot be valued with the `"${app.count}"` `String` as **`"${app.count}"` cannot be converted into an int value**.
Whereas the thrown exception as `Integer.parseInt("${app.count}")` is invoked :
```
Caused by: java.lang.NumberFormatException: For input string: "${app.count}"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
```
To address this issue, use `@TestPropertySource` as suggested by username_1 to provide the value for the properties at the suitable time.
As a general advise, limit the reflection use. It is checked only at runtime and that is often more opaque.
Upvotes: 2
|
2018/03/17
| 308 | 1,031 |
<issue_start>username_0: I am looking for the files having string say "My\_Name" In my backup folder of Linux server. where I have zip of works of every day. like MyWork\_20180306.zip.
Searching in one zip file would be enough. because there are 100 of zips with name pattern MyWork\_yyyymmdd.zip.
I am using below command, which is working fine on folder of documents. but not in zip.
```
cd /path/
grep -Ril "My_Name"
```<issue_comment>username_1: You can use [`zgrep`](https://linux.die.net/man/1/zgrep), which has the same semantics as `grep`, but can search within compressed files:
```
$ zgrep -Ril "My_Name"
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Some have suggested to use [ugrep](https://github.com/Genivia/ugrep) as a replacement of grep to recursively search compressed files and archives with option `-z`:
```
ugrep -z -Ril "My_Name"
```
This command looks recursively for matches in files compressed in zip, gz, tarballs, etc. and lists them as `archive.zip{path.../file.txt}`.
Upvotes: 0
|
2018/03/17
| 444 | 1,431 |
<issue_start>username_0: I am new to Php and Mysql. I have a table called ut\_posts having multiple columns.I want to query latest 5 records from each column based on the column status as 1. Below is my query to fetch records. But it seems to be not working.
```
SELECT * FROM(
SELECT * FROM ut_posts WHERE political_news = 1 ORDER BY id DESC LIMIT 0,5
UNION ALL
SELECT * FROM ut_posts WHERE cinema_news= 1 ORDER BY id DESC LIMIT 0,5
UNION ALL
SELECT * FROM ut_posts WHERE latest_videos = 1 ORDER BY id DESC LIMIT 0,5
) a
```
But I am getting below error
```
Error Code: 1221
Incorrect usage of UNION and ORDER BY
My requirement is I want to display latest 5 records from each column.
```
How can I achieve this, any help would be greatly appreciated.<issue_comment>username_1: You could use:
```
(SELECT * FROM ut_posts WHERE political_news = 1 ORDER BY id DESC LIMIT 0,5)
UNION ALL
(SELECT * FROM ut_posts WHERE cinema_news= 1 ORDER BY id DESC LIMIT 0,5)
UNION ALL
(SELECT * FROM ut_posts WHERE latest_videos = 1 ORDER BY id DESC LIMIT 0,5);
```
Upvotes: 2 <issue_comment>username_2: ```
SELECT * FROM
( SELECT * FROM ut_posts WHERE political_news = 1 ORDER BY id DESC LIMIT 0,5) t1
UNION
SELECT * FROM(SELECT * FROM ut_posts WHERE cinema_news= 1 ORDER BY id DESC LIMIT 0,5) t2
UNION
SELECT * FROM( SELECT * FROM ut_posts WHERE latest_videos = 1 ORDER BY id DESC LIMIT 0,5 ) t3
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 787 | 2,566 |
<issue_start>username_0: I want to move the digits/numeric string from front of line to end of line, example of input:
```
123example
321example
34292example
```
expected output:
```
example123
example321
example34292
```<issue_comment>username_1: GNU awk's `match` function can do the job:
```
gawk 'match($0, /^([0-9]+)(.*)$/, m) {print m[2] m[1]}' yourfile.txt
```
but, honestly, I would use `sed` for this task (as @anubhava suggested).
Upvotes: 4 [selected_answer]<issue_comment>username_2: GNU awk
```
awk -F"[[:digit:]]+" '{split($0,f,FS,s); print $2 s[1]}' file
example123
example321
example34292
```
You can use stream of digits as `FS`. Split the string using `FS` and the characters matching the separators will be stored in array `s`. Use it as you like
Upvotes: 1 <issue_comment>username_3: Following `awk` may help you without using `array` in `match`:
```
awk '{gsub(/\r/,"");match($0,/^[0-9]+/);print substr($0,RSTART+RLENGTH+1) substr($0,RSTART,RLENGTH)}' Input_file
```
Also added now `gsub(/\r/,"")` for removing all carriage returns from your Input\_file too.
Also in case you want to save output into your Input\_file itself then append following to above code `> temp_file && mv temp_file Input_file`
***Explanation:*** Adding explanation too here now.
```
awk '
{
gsub(/\r/,"") ##Removing all carriage returns from current line here by using gsub out of box function of awk.
match($0,/^[0-9]+/); ##Using match function of awk to match starting digits in current line.
print substr($0,RSTART+RLENGTH+1) substr($0,RSTART,RLENGTH)##Printing substrings here 1st substring is to print from the value of RSTART+RLENGTH+1 to till the end of the line and second substring is to print from the RSTART to RLENGTH where RSTART and RLENGTH are the variables of awk which will be SET once match is having a TRUE value in it. RSTART denotes the index value of matched regex in line/variable and RLENGTH is the length of the matched regex by match.
}
' Input_file ##Mentioning the Input_file name here.
```
Upvotes: 1 <issue_comment>username_4: With bash and a regex:
```
s="123example"
[[ $s =~ ([0-9]+)(.*) ]] && echo "${BASH_REMATCH[2]}${BASH_REMATCH[1]}"
```
Output:
```
example123
```
Upvotes: 2 <issue_comment>username_5: First remove example and put it back in front of what is left.
```
awk '{sub(/example$/,"");print "example"$0}' file
example123
example321
example34292
```
Upvotes: 0
|
2018/03/17
| 757 | 2,766 |
<issue_start>username_0: How can I annotate the yield type of a `contextmanager` in PyCharm so that it properly guesses the type of the value used in the `with` clauses - just as it guesses that the `f` created in `with open(...) as f` is a file?
For example, I have a context manager like this:
```py
@contextlib.contextmanager
def temp_borders_file(geometry: GEOSGeometry, name='borders.json'):
with TemporaryDirectory() as temp_dir:
borders_file = Path(dir) / name
with borders_file.open('w+') as f:
f.write(geometry.json)
yield borders_file
with temp_borders_file(my_geom) as borders_f:
do_some_code_with(borders_f...)
```
How do I let PyCharm know that every `borders_f` created like this is a `pathlib.Path` (and thus enable the autocompletion for the `Path` methods on `border_f`)? Of course, I can make a comment like `# type: Path` after every `with` statement, but it seems that this can be done by properly annotating `temp_border_file`.
I tried `Path`, `typing.Iterator[Path]` and `typing.Generator[Path, None, None]` as the return type of `temp_border_file`, as well as adding `# type: Path` on `borders_file` within the context manager's code, but it seems like it doesn't help.<issue_comment>username_1: Dirty workaround below. Will break `mypy`. Better don't use it.
---
I believe you can use `ContextManager` from `typing`, e.g.:
```
import contextlib
from typing import ContextManager
from pathlib import Path
@contextlib.contextmanager
def temp_borders_file() -> ContextManager[Path]:
pass
with temp_borders_file() as borders_f:
borders_f # has type Path here
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: This is a current PyCharm issue: [PY-36444](https://youtrack.jetbrains.com/issue/PY-36444)
A workaround for the issue is to rewrite an example code of:
```py
from contextlib import contextmanager
@contextmanager
def generator_function():
yield "some value"
with generator_function() as value:
print(value.upper()) # no PyCharm autocompletion
```
to
```py
from contextlib import contextmanager
from typing import ContextManager
def wrapper() -> ContextManager[str]:
@contextmanager
def generator_function():
yield "some value"
return generator_function()
with wrapper() as value:
print(value.upper()) # PyCharm autocompletion works
```
There is also an easier workaround of annotating the return type with `ContextManager[str]` but there are multiple reasons against this:
* mypy will correctly emit errors for this annotation, as described in more detail in the PyCharm issue.
* this is not guaranteed to work in the future because PyCharm will hopefully fix the issue and therefore break this workaround
Upvotes: 3
|
2018/03/17
| 868 | 3,188 |
<issue_start>username_0: I am using **MySQL** database table **scholarship\_discount**. where I have three fields that are **maxPercentage, min Percentage and name**. So I want to run a query for getting rows if all fields satisfy my condition. I am using Laravel 5.6 Framework. problem is when i am running this query into **MySql Workbench** then getting correct result but when tries through Laravel then getting wrong result.
**Problem Example ::**
If I gives **user value as 78** then i get **row id 5** , else **96** then **row is 1**.ok no problem. Using **mysql workbench**.
but when i gives **98 ,96,97,99** then i get no result . why? i don't know. No any record deleted. my meant it should be return **row id 1** but gives me **blank Array** [].
My query is:
```
SELECT * FROM confidence.scholarship_discounts where name='ssc' and
(maxPer >= 100 or maxPer = 100 ) and `scholarship_discounts`.`deleted_at` is null
order by id DESC;
```
my search condition is **MaxPercentage** should be greater than to **user Value**.
My database record is:
```
id name maxPercentage minPercentage discountPercentage
1 HSC 100 95 10
2 HSC 95 90 7
3 HSC 90 85 6
4 HSC 85 80 5
5 HSC 80 75 10
6 HSC 75 70 7
7 HSC 60 50 6
```
So, according to this table if I give 95 as value, then the query should return row id 1.
So it's better if a solution available on Laravel eloquent then please describe it.
Can i filter or search row between maxPercentage { value } minPercentage.
like
```
75 myValue 70
```<issue_comment>username_1: `where maxPercentage <= 90` - This means that the maximum percentage has to be equal to or GREATER than 90% *If you changed this value to 95 then yes, only the row with id=1 would be returned*.
`minPercentage >= 90` - Means the minimum persentage must be LESS than 90%
If this isn't what you're asking please elaborate further. The method you've chosen to do this is probably the most efficient way, if not just the simplest way to do this.
Upvotes: 0 <issue_comment>username_2: Try this code
```
return $data = ScholarshipDiscount::where(function($q) use ($request){
return $q->where('maxPercentage' ,'>=', $request->value)
->orWhere('maxPercentage',$request->value);
})->orderBy('id','desc')->get();
```
Upvotes: 0 <issue_comment>username_3: I have solved my problem self. actually i was doing wrong with table fields. i was selected wrong fields for compare value with my input.
```
ScholarshipDiscount::where( 'name' ,'ssc' )
->where( function( $q ) use ( $request ) {
$q-> where('minPer' ,'<=', $request->ssc );
$q-> orWhere('minPer' , $request->ssc );
$q-> orWhere('maxPer' , $request->ssc );
} )->orderBy('id','asc')->first();
```
I checked my condition with is solution and every time i was getting my result.
Upvotes: 3 [selected_answer]
|
2018/03/17
| 779 | 2,866 |
<issue_start>username_0: i'm working on some kind of educational game, in this game i represent nine levels in recyclerview each level is enabled when the previous one, now i'm trying to make one item in the recycler View enable and the others unable, i been searching in youtube , and other websites, my question is how to do it?(note: i'm new in android studio so keep it simple as possible).
```
public class ListAdapter extends RecyclerView.Adapter {
private List items;
private Context context;
public ListAdapter(List items , Context context){
this.items = items;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item\_list , parent , false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
ItemView i = items.get(position);
holder.setHeadText(i.getHead());
holder.setScoreText(i.getScore());
}
@Override
public int getItemCount() {
return items.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView headText , scoreText;
public ViewHolder(View itemView) {
super(itemView);
headText = (TextView)itemView.findViewById(R.id.head);
scoreText = (TextView)itemView.findViewById(R.id.score);
}
public void setHeadText(String headText) {
this.headText.setText(headText);
}
public void setScoreText(String scoreText) {
this.scoreText.setText(scoreText);
}
}
```
}<issue_comment>username_1: `where maxPercentage <= 90` - This means that the maximum percentage has to be equal to or GREATER than 90% *If you changed this value to 95 then yes, only the row with id=1 would be returned*.
`minPercentage >= 90` - Means the minimum persentage must be LESS than 90%
If this isn't what you're asking please elaborate further. The method you've chosen to do this is probably the most efficient way, if not just the simplest way to do this.
Upvotes: 0 <issue_comment>username_2: Try this code
```
return $data = ScholarshipDiscount::where(function($q) use ($request){
return $q->where('maxPercentage' ,'>=', $request->value)
->orWhere('maxPercentage',$request->value);
})->orderBy('id','desc')->get();
```
Upvotes: 0 <issue_comment>username_3: I have solved my problem self. actually i was doing wrong with table fields. i was selected wrong fields for compare value with my input.
```
ScholarshipDiscount::where( 'name' ,'ssc' )
->where( function( $q ) use ( $request ) {
$q-> where('minPer' ,'<=', $request->ssc );
$q-> orWhere('minPer' , $request->ssc );
$q-> orWhere('maxPer' , $request->ssc );
} )->orderBy('id','asc')->first();
```
I checked my condition with is solution and every time i was getting my result.
Upvotes: 3 [selected_answer]
|
2018/03/17
| 1,186 | 3,975 |
<issue_start>username_0: Is there a way to enter a single jar name to maven and get the full path of jars that added it to my project?<issue_comment>username_1: The best thing that you can do is using the [`mvn dependency:tree` command](https://maven.apache.org/plugins/maven-dependency-plugin/tree-mojo.html).
It doesn't display the full path of jars that pulled the dependencies.
Instead, it displays the dependency tree for the current Maven project.
You could so know for each resolved dependency the Maven module/dependency that pulled that.
Make the mapping between a dependency identified by the trio `groupId-artifactId-version` and your local repository should be so very simple.
Here is an example with a project that among other things has `jmh` as dependency :
```
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ map-benchmark ---
[INFO] username_1:map-benchmark:jar:1.0
[INFO] +- junit:junit:jar:4.7:test
[INFO] +- org.openjdk.jmh:jmh-core:jar:1.19:compile
[INFO] | +- net.sf.jopt-simple:jopt-simple:jar:4.6:compile
[INFO] | \- org.apache.commons:commons-math3:jar:3.2:compile
[INFO] \- org.openjdk.jmh:jmh-generator-annprocess:jar:1.19:compile
```
You can see for example that `junit` is not a transitive dependency as it pulled by the current project itself.
But you could also see that `commons-math3` is a transitive dependency pulled by `jopt-simple` itself pulled by `jmh-core`.
The `dependency:tree` goal can also be used to filter only specific dependencies.
```
mvn dependency:tree -Dincludes=org.apache.commons:commons-math3
```
or (note `:` without prefix if we don't need to specify the groupId) :
```
mvn dependency:tree -Dincludes=:commons-math3
```
will output :
```
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ map-benchmark ---
[INFO] username_1:map-benchmark:jar:1.0
[INFO] \- org.openjdk.jmh:jmh-core:jar:1.19:compile
[INFO] \- org.apache.commons:commons-math3:jar:3.2:compile
[INFO] ------------------------------------------------------------------------
```
---
This plugin can [help to solve conflicts](https://maven.apache.org/plugins/maven-dependency-plugin/examples/resolving-conflicts-using-the-dependency-tree.html).
Here is a relevant example from the documentation.
For example, to find out why Commons Collections 2.0 is being used by
the Maven Dependency Plugin, we can execute the following in the
project's directory:
```
mvn dependency:tree -Dverbose -Dincludes=commons-collections
```
The verbose flag instructs the dependency tree to display conflicting
dependencies that were omitted from the resolved dependency tree. In
this case, the goal outputs:
```
[INFO] [dependency:tree]
[INFO] org.apache.maven.plugins:maven-dependency-plugin:maven-plugin:2.0-alpha-5-SNAPSHOT
[INFO] +- org.apache.maven.reporting:maven-reporting-impl:jar:2.0.4:compile
[INFO] | \- commons-validator:commons-validator:jar:1.2.0:compile
[INFO] | \- commons-digester:commons-digester:jar:1.6:compile
[INFO] | \- (commons-collections:commons-collections:jar:2.1:compile - omitted for conflict with 2.0)
[INFO] \- org.apache.maven.doxia:doxia-site-renderer:jar:1.0-alpha-8:compile
[INFO] \- org.codehaus.plexus:plexus-velocity:jar:1.1.3:compile
[INFO] \- commons-collections:commons-collections:jar:2.0:compile
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Check
<https://maven.apache.org/plugins/maven-dependency-plugin/examples/filtering-the-dependency-tree.html>
You can search for an specific artifact using this maven command:
`mvn dependency:tree -Dincludes=DESIRED-groupId:DESIRED-artifactId`
Also, if you use eclipse and the m2eclipse plugin (<http://m2eclipse.sonatype.org>) then there is a graphical version of dependency tree which will help you to filter it by jar name. See: <https://books.sonatype.com/m2eclipse-book/reference/dependencies-sect-analyze-depend.html>
There should be similar features in other IDEs
Upvotes: 2
|
2018/03/17
| 346 | 1,239 |
<issue_start>username_0: Please find the below url.
<https://stackblitz.com/edit/angular-w4lj6q?file=app%2Fapp.component.ts>
I am using http module and trying to get the data from json file but i am getting below error. can you please help somebody to fix the issue.
Error : errors.js:55 ERROR SyntaxError: Unexpected token < in JSON at position 0<issue_comment>username_1: because you should add the `content-type` equal to `json` in the `http` `header`
to make sure that the returned data format is `json` not `HTML` as your code do
Upvotes: 0 <issue_comment>username_2: There are couple of things going wrong in the stackblitz.
1. The folder which contains the JSON is **apiDta** instead of **apiData**
2. Stackblitz is not returning the JSON even with the correct URL, rather responds with a HTML.
You can use [reqres](https://reqres.in/) to get a sample JSON.
Update the URL in `NameListService`
```
private _url: string = "https://reqres.in/api/users";
```
and update `AppComponent`'s `ngOnInit()`
```
this._nameService
.getNames()
.subscribe(res => {
this.nameLists = res;
console.log(JSON.stringify(this.nameLists));
});
```
Upvotes: 1
|
2018/03/17
| 508 | 1,487 |
<issue_start>username_0: I am making a tkinter project for school. In the project, I need to use transparent images. In my school, the tkinter only supports GIFs so I cannot use a PNG. Moreover, only the modules that come with python 3 when installing are supported. We cannot download more. Is there a way to solve my problem?<issue_comment>username_1: You can do this with [GIFsicle](https://www.lcdf.org/gifsicle/), using the following options:
```
gifsicle -U --disposal=previous --transparent="#ffffff" -O2 pic.gif > pic_trans.gif
```
where pic.gif and pic\_trans.gif are the source and destination file names, and #ffffff is the hex code of the color you want to make transparent (here, pure white).
Upvotes: 0 <issue_comment>username_2: tkinter can show the png transparence.
Example with a basic image.
[](https://i.stack.imgur.com/qOF7Q.png)
```
import tkinter as tk
root = tk.Tk()
img = tk.PhotoImage(file='test.png')
can = tk.Canvas(root, width=300, height=300, bg='lightGrey')
can.grid()
can.create_rectangle(0, 0, 200, 200, fill='darkGreen')
can.create_rectangle(100, 100, 300, 300, fill='navy')
can.create_text(150, 150, text='TKINTER', font=('', 32), fill='orange')
can.create_image(150, 150, image=img)
root.mainloop()
```
[](https://i.stack.imgur.com/C1RNW.png)
You just need to save your image with the alpha parametre, with Gimp or a good image editor.
Upvotes: 2
|
2018/03/17
| 676 | 1,967 |
<issue_start>username_0: I need allow links in messages, when user send message. How I can do this?
```
@foreach($mess as $message)
- 
{{ $message->sender->name }}
@if(Helper::getOnlineUser($message->sender->id))
*fiber\_manual\_record*
@else
*fiber\_manual\_record*
@endif
{{ $message->created\_at->formatLocalized('%H:%m') }}
{{ $message->body }}
@endforeach
```
This is view of messages.
How I can allow links?
Example: <http://example.com> in messages =>
```
<http://example.com>
```
I need {!! $message->body !!} ? Or How?
In controller:
```
$mess = Chat::conversations($conversation)->for($user)->getMessages($limit, $request->page);
```
I use this package: <https://github.com/musonza/chat><issue_comment>username_1: You can do this with [GIFsicle](https://www.lcdf.org/gifsicle/), using the following options:
```
gifsicle -U --disposal=previous --transparent="#ffffff" -O2 pic.gif > pic_trans.gif
```
where pic.gif and pic\_trans.gif are the source and destination file names, and #ffffff is the hex code of the color you want to make transparent (here, pure white).
Upvotes: 0 <issue_comment>username_2: tkinter can show the png transparence.
Example with a basic image.
[](https://i.stack.imgur.com/qOF7Q.png)
```
import tkinter as tk
root = tk.Tk()
img = tk.PhotoImage(file='test.png')
can = tk.Canvas(root, width=300, height=300, bg='lightGrey')
can.grid()
can.create_rectangle(0, 0, 200, 200, fill='darkGreen')
can.create_rectangle(100, 100, 300, 300, fill='navy')
can.create_text(150, 150, text='TKINTER', font=('', 32), fill='orange')
can.create_image(150, 150, image=img)
root.mainloop()
```
[](https://i.stack.imgur.com/C1RNW.png)
You just need to save your image with the alpha parametre, with Gimp or a good image editor.
Upvotes: 2
|
2018/03/17
| 1,877 | 5,225 |
<issue_start>username_0: UPDATE #1
I have one php file with multiple queries that create multiple csv files.
I want to combine the queries.
My mysql `table` has 5 columns: ID, currency, rate, date, temptime
Create the table `table` and insert some records
```
CREATE TABLE IF NOT EXISTS `table` ( `id` INT NOT NULL AUTO_INCREMENT , `currency` VARCHAR(254) NOT NULL , `rate` FLOAT NOT NULL , `date` VARCHAR(254) NOT NULL , `temptime` DATE NOT NULL , PRIMARY KEY (`id`), UNIQUE `UNIQUE` (`currency`, `temptime`)) ENGINE = MyISAM;
INSERT INTO `table`
(currency, rate, date, temptime)
VALUES
('USD', '1.232', '1521212400', '2018-03-16'),
('USD', '1.258', '1521126000', '2018-03-15'),
('JPY', '133.82', '1521212400', '2018-03-16'),
('JPY', '131.88', '1521126000', '2018-03-15'),
('EUR', '1.99', '1521212400', '2018-03-16'),
('EUR', '1.85', '1521126000', '2018-03-15'),
('BRL', '1.6654', '1521212400', '2018-03-16'),
('BRL', '1.5498', '1521126000', '2018-03-15'),
('ZAR', '1.99654', '1521212400', '2018-03-16'),
('ZAR', '2.0198', '1521126000', '2018-03-15'),
('RUB', '19.9654', '1521212400', '2018-03-16'),
('RUB', '20.0198', '1521126000', '2018-03-15');
```
These are the 2 queries I want to combine for the column "currency" USD and EUR :
```
$result = mysql_query("SELECT temptime, rate FROM `table` WHERE currency='USD' ORDER BY date asc");
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('csv/USD.csv', 'w');
if ($fp && $result)
{
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
}
$result = mysql_query("SELECT temptime, rate FROM `table` WHERE currency='EUR' ORDER BY date asc");
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('csv/EUR.csv', 'w');
if ($fp && $result)
{
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
}
```
Thank you<issue_comment>username_1: You can use the currency field in each row to decide which file to write to, I've used an array of file handles so rather than having any conditions around which file, you just use the currency as the index to the file handle...
```
// Create an array of files, each associated with currency
$fp = array( 'EUR' => fopen('csv/EUR.csv', 'w'),
'USD' => fopen('csv/USD.csv', 'w'));
$result = mysql_query("SELECT currency, temptime, rate FROM `table` ORDER BY date asc");
if (!$result) die("Couldn't fetch records");
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
// Write out headers to each file.
foreach ( $fp as $output ) {
fputcsv($output, $headers);
}
while ($row = mysql_fetch_row($result)) {
// Use first field to decide which file to write to.
$currency = array_shift($row);
fputcsv($fp[$currency], $row);
}
// Close all of the files.
foreach ( $fp as $output ) {
fclose($output);
}
```
As I don't have your database, I can't test this, but if you have any problems, then let me know.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Consider also using no loops and exporting to CSV directly from MySQL with its [`SELECT ... INTO OUTFILE`](https://dev.mysql.com/doc/refman/5.7/en/select-into.html) (the complement of `LOAD DATA INFILE`).
Specifically, execute both action queries separately below in PHP (be sure to escape quotes). While not combined, this process should be a faster read/write IO process than multiple loops. Plus, you can swap the app layer (i.e., use Python, Java) without changing csv export code!
```sql
SELECT temptime, rate
INTO OUTFILE '/path/to/csv/USD.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM `table`
WHERE currency='USD'
ORDER BY `date` asc;
SELECT temptime, rate
INTO OUTFILE '/path/to/csv/EUR.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM `table`
WHERE currency='EUR'
ORDER BY `date` asc;
```
And for one call, placed both in MySQL stored procedure:
```sql
DELIMITER $$
DROP PROCEDURE IF EXISTS export_csv$$
CREATE PROCEDURE export_csv
BEGIN
-- SELECT ... INTO OUTFILE COMMANDS
END$$
DELIMITER ;
```
Then in PHP run it with a one-liner (using `mysqli` API):
```php
$result = mysqli_query($conn, "CALL export_csv")
```
---
Do note: headers are not passed with above commands. To resolve adjust query with a union requiring type conversion. And CSVs do not store types or unicodes metadata to have issue here.
```sql
SELECT 'temptime' as col1, 'rate' as col2
UNION ALL
SELECT CAST(temptime, CHAR(10) as col1,
CAST(ROUND(rate,4) AS CHAR(3)) as col2
INTO OUTFILE '/path/to/csv/USD.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM `table`
WHERE currency='USD' ;
```
Upvotes: 0
|
2018/03/17
| 337 | 1,140 |
<issue_start>username_0: I am trying to implement routes with classes in my express js application
controller
```
class User {
constructor (){
this.username = 'me';
}
getUsername(req,res){
res.json({
'name':this.name
});
}
}
export default User;
```
In my routes
```
import express from 'express'
import User from './controller'
const router = express.Router();
const user = new User();
router('/',user.getUsername.bind(user));
export default UserRoute
```
But I got this error
>
> req.next = next;
> ^
>
>
> TypeError: Cannot create property 'next' on string '/'
> at Function.handle (/var/accubits-workspace/express-es6/node\_modules/express/lib/router/index.js:160:12)
>
>
><issue_comment>username_1: you are not using any method on the router object, you need something like `get` , `post`, `put` , `delete` or other http/https verbs or `use` for creating middleware.
for example
```
router.VERB("/", ...);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: router.(use HTTP method like(get,post...))('/',user.getUsername.bind(user));
Upvotes: -1
|
2018/03/17
| 348 | 1,409 |
<issue_start>username_0: I'm trying to send all my js code from kendo grid to external file. But I can't do that, because js file cannot include razor syntax. How can I get my authors from controller method?
**My editor that use razor in datasource**
```
function authorsEditor(container, options) {
$('').appendTo(container)
.kendoMultiSelect({
dataValueField: "AuthorId",
dataTextField: "AuthorName",
//this datasource works
dataSource: @Html.Raw(Json.Encode(LibraryApp.BLL.ViewModels.AuthorViewModel.GetAllAuthors))
//this not, but wanna something like this
dataSource: "/Home/GetAllAuthors"
});
}
```
I have the method in my controller that return authors from database.
How can I send them to datasource?
```
public JsonResult GetAllAuthors()
{
var authors = bookService.GetAuthors();
return Json(authors, JsonRequestBehavior.AllowGet);
}
```
If something is not clear enough, ask questions)<issue_comment>username_1: you are not using any method on the router object, you need something like `get` , `post`, `put` , `delete` or other http/https verbs or `use` for creating middleware.
for example
```
router.VERB("/", ...);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: router.(use HTTP method like(get,post...))('/',user.getUsername.bind(user));
Upvotes: -1
|
2018/03/17
| 260 | 982 |
<issue_start>username_0: Suppose I have a list of `Flowable`, and I would like to do something until all `Flowable` are finished, how can I do it?
Sample Code
===========
```
List> flowableList = getFlowableList();
List> results = blockUntilAllFlowablesAreFinished(flowableList); // is there a similar method?
... // do something with results
```<issue_comment>username_1: I'm not sure why you are thinking in a synchronous fashion but I believe you'll achieve your goal with something like:
```
Flowable.combineLatest(flowableList -> {
// do something with results
});
```
Of course, besides `combineLatest`, there are bunch of operators that allow you to "combine" flowables e.g. `zip`. Choose one that suit you here <https://github.com/ReactiveX/RxJava/wiki/Combining-Observables>
Upvotes: 2 <issue_comment>username_2: I think you can use `Flowable.zip()` with `Iterable` as parameter, it will emit when all Flowables in Iterable are done.
Upvotes: 2 [selected_answer]
|
2018/03/17
| 439 | 1,636 |
<issue_start>username_0: So I have a program that I want to autostart in Raspberry Pi. My program is supposed to grab some api-info online and then display it on a little screen. I've added these lines to rc.local:
```
sudo python ./home/pi/Documents/Skanetrafiken_projekt/testStart.py &
sudo python ./home/pi/Documents/Skanetrafiken_projekt/main.py &
```
The testStart.py just tests the display and it works fine, the screen lights up when the Raspberry Pi boots up. So that works. The main.py won't work at all however. In the beginning of the main code I even put the same code as in testStart.py, just to see if the display lights up, but it doesn't. So that is super weird to me.
Could it be something about that the main.py will connect to internet? I tried setting "Waiting of network to boot" in the raspi-config settings, but that didn't help.
The main works fine when I run in manually. I also tried to start with cron, but that didn't work. I don't have that much experience.
And ideas?<issue_comment>username_1: I'm not sure why you are thinking in a synchronous fashion but I believe you'll achieve your goal with something like:
```
Flowable.combineLatest(flowableList -> {
// do something with results
});
```
Of course, besides `combineLatest`, there are bunch of operators that allow you to "combine" flowables e.g. `zip`. Choose one that suit you here <https://github.com/ReactiveX/RxJava/wiki/Combining-Observables>
Upvotes: 2 <issue_comment>username_2: I think you can use `Flowable.zip()` with `Iterable` as parameter, it will emit when all Flowables in Iterable are done.
Upvotes: 2 [selected_answer]
|
2018/03/17
| 1,933 | 7,884 |
<issue_start>username_0: I want to color every same word inside a RichTextBox. I can do it for one line but not on multiple lines.
E.g., Welcome "user" .....
I want the word `user` to be an exact color in every line it's found.
Here's with what i came up so far:
```
RichTextBox1.Text = "Welcome "
RichTextBox1.Select(RichTextBox1.TextLength, 0)
RichTextBox1.SelectionColor = My.Settings.color
RichTextBox1.AppendText(My.Settings.username)
RichTextBox1.SelectionColor = Color.Black
RichTextBox1.AppendText(" ........." + vbCrLf)
```
It's on `form.Load`; I tried to use the `richtextbox.TextChange` event, but it just colors the last `user` word and the others are remain the same.<issue_comment>username_1: With a module,you can do it this way :
```
Imports System.Runtime.CompilerServices
Module Utility
Sub HighlightText(ByVal myRtb As RichTextBox, ByVal word As String, ByVal color As Color)
If word = String.Empty Then Return
Dim index As Integer, s\_start As Integer = myRtb.SelectionStart, startIndex As Integer = 0
While(\_\_InlineAssignHelper(index, myRtb.Text.IndexOf(word, startIndex))) <> -1
myRtb.[Select](index, word.Length)
myRtb.SelectionColor = color
startIndex = index + word.Length
End While
myRtb.SelectionStart = s\_start
myRtb.SelectionLength = 0
myRtb.SelectionColor = Color.Black
End Sub
Private Shared Function \_\_InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
End Module
```
Or , you can also go with this one as it will allow you to highlight multiple words at the same time :
```
Private Sub HighlightWords(ByVal words() As String)
Private Sub HighlightWords(ByVal words() As String)
For Each word As String In words
Dim startIndex As Integer = 0
While (startIndex < rtb1.TextLength)
Dim wordStartIndex As Integer = rtb1.Find(word, startIndex, RichTextBoxFinds.None)
If (wordStartIndex <> -1) Then
rtb1.SelectionStart = wordStartIndex
rtb1.SelectionLength = word.Length
rtb1.SelectionBackColor = System.Drawing.Color.Black
Else
Exit While
End If
startIndex += wordStartIndex + word.Length
End While
Next
End Sub
```
[Source](https://stackoverflow.com/questions/11851908/highlight-all-searched-word-in-richtextbox) Hope this helps :)
Upvotes: 1 <issue_comment>username_2: This is a simple Class that enables multiple Selections and Highlights of text for RichTextBox and TextBox controls.
You can use multiple instances of this Class for different controls.
You can add the Words to Select/HighLight to a List and specify which color to use for selecting and/or highlighting the text.
```
Dim listOfWords As WordList = New WordList(RichTextBox1)
listOfWords.AddRange({"Word1", "Word2"})
listOfWords.SelectionColor = Color.LightBlue
listOfWords.HighLightColor = Color.Yellow
```
These are the visual results of the Class actions:
[](https://i.stack.imgur.com/S5KHp.gif)
In the example, the List of words is filled using:
```
Dim patterns As String() = TextBox1.Text.Split()
listOfWords.AddRange(patterns)
```
In the visual example, the Class is configured this way:
```
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim patterns As String() = TextBox1.Text.Split()
Dim listOfWords As WordList = New WordList(RichTextBox1)
listOfWords.AddRange(patterns)
listOfWords.SelectionColor = Color.LightBlue
listOfWords.HighLightColor = Color.Yellow
If RadioButton1.Checked = True Then
listOfWords.WordsSelect()
ElseIf RadioButton2.Checked Then
listOfWords.WordsHighLight()
Else
listOfWords.DeselectAll()
End If
End Sub
```
This is the Class used to generate the Selections and HighLights:
```
Imports System.Drawing.Text
Imports System.Text.RegularExpressions
Public Class WordList
Private TextRendererFlags As TextFormatFlags =
TextFormatFlags.Top Or TextFormatFlags.Left Or TextFormatFlags.NoPadding Or
TextFormatFlags.WordBreak Or TextFormatFlags.TextBoxControl
Private textControl As RichTextBox = Nothing
Private wordsList As List(Of Word)
Public Sub New(rtb As RichTextBox)
textControl = rtb
wordsList = New List(Of Word)
ProtectSelection = False
End Sub
Public Property ProtectSelection As Boolean
Public Property HighLightColor As Color
Public Property SelectionColor As Color
Public Sub Add(word As String)
wordsList.Add(New Word() With {.Word = word, .Indexes = GetWordIndexes(word)})
End Sub
Public Sub AddRange(words As String())
For Each WordItem As String In words
wordsList.Add(New Word() With {.Word = WordItem, .Indexes = GetWordIndexes(WordItem)})
Next
End Sub
Private Function GetWordIndexes(word As String) As List(Of Integer)
Return Regex.Matches(textControl.Text, word).
OfType(Of Match)().
Select(Function(chr) chr.Index).ToList()
End Function
Public Sub DeselectAll()
If textControl IsNot Nothing Then
textControl.SelectAll()
textControl.SelectionBackColor = textControl.BackColor
textControl.Update()
End If
End Sub
Public Sub WordsHighLight()
If wordsList.Count > 0 Then
For Each WordItem As Word In wordsList
For Each Position As Integer In WordItem.Indexes
Dim p As Point = textControl.GetPositionFromCharIndex(Position)
TextRenderer.DrawText(textControl.CreateGraphics(), WordItem.Word,
textControl.Font, p, textControl.ForeColor,
HighLightColor, TextRendererFlags)
Next
Next
End If
End Sub
Public Sub WordsSelect()
DeselectAll()
If wordsList.Count > 0 Then
For Each WordItem As Word In wordsList
For Each Position As Integer In WordItem.Indexes
textControl.Select(Position, WordItem.Word.Length)
textControl.SelectionColor = textControl.ForeColor
textControl.SelectionBackColor = SelectionColor
textControl.SelectionProtected = ProtectSelection
Next
Next
End If
End Sub
Friend Class Word
Property Word As String
Property Indexes As List(Of Integer)
End Class
End Class
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: This works
```
Public Sub HighlightText(ByVal txt As String, ByVal obj As RichTextBox)
obj.SelectionStart = 0
obj.SelectAll()
obj.SelectionBackColor = Color.White
Dim len = txt.Length
Dim pos = obj.Find(txt, 0, RichTextBoxFinds.NoHighlight)
While (pos >= 0)
obj.Select(pos, len)
obj.SelectionBackColor = Color.Yellow
If pos + len >= obj.Text.Length Then
Exit While
End If
pos = obj.Find(txt, pos + len, RichTextBoxFinds.NoHighlight)
End While
End Sub
```
Upvotes: 1 <issue_comment>username_3: ```
Public Sub HighlightText(ByVal txt As String, ByVal obj As RichTextBox)
obj.SelectionStart = 0
obj.SelectAll()
obj.SelectionBackColor = Color.White
Dim len = txt.Length
Dim pos = obj.Find(txt, 0, RichTextBoxFinds.NoHighlight)
While (pos >= 0)
obj.Select(pos, len)
obj.SelectionBackColor = Color.Yellow
If pos + len >= obj.Text.Length Then
Exit While
End If
pos = obj.Find(txt, pos + len, RichTextBoxFinds.NoHighlight)
End While
End Sub
```
Upvotes: 0
|
2018/03/17
| 289 | 972 |
<issue_start>username_0: "" these quotes are included in python's basic structure.
What if we want output with these quotes like I mentioned in question?<issue_comment>username_1: Quotes are exchangeable in python, meaning that you can use single ones inside double ones and viceversa:
```
print("'Hi!'")
'Hi!'
print('"Hi!"')
"Hi!"
```
or use scape characters:
```
print("\"Hi!\"")
"Hi!"
```
Upvotes: 2 <issue_comment>username_2: So Python prints everything inside the quote marks. So... if you want your string to be "hello [your name]" you need to put that inside the quotation marks to print it.
it would look like this.
```
print(""hello [your name]"")
```
and your string would be "hello [your name]"
Upvotes: 0 <issue_comment>username_3: You can use double qoutes inside the single qoutes .
Try the below code !
**Code :**
```
name="<NAME>"
print('"Hello ' + name + '"')
```
**Output :**
```
"Hello Muhammad username_3"
```
Upvotes: 0
|
2018/03/17
| 1,029 | 4,456 |
<issue_start>username_0: I have a client side React application and a Rails API from which the React app is fetching data.
As you would expect I only want my React application to be able to fetch data from the API and the rest of the world shouldn't be able to receive data from it.
Despite much searching I am yet to find the best way to secure the communication between the two applications.
I have read about JWT tokens and cookie based session authentication but the majority of articles seem to be focused on authentication of users (ie sign in/sign out) rather than communication between just the two applications.
The two apps will share the same domain so is it enough to rely on Cross Origin to secure communication?
Any advice really would be much appreciated.<issue_comment>username_1: The case of cross origin domains is when you might need to implement CORS and a security like a blacklist. JWT is a little different, as you say authenticating users who need access to your api.
I believe as long as you don't enable CORS on your server, you'll be fine.
Note that this will not stop people from doing things like:
`https://example.com/api/blah` to access a part of your api if it is public. This is essentially the same as your front end doing the same because the client is served to the user, and the user then has full control over the client. They could change all instances of api calls in your app to a different endpoint and you couldn't stop them, just as they could just type it in the url bar. Any public endpoints on your api have to not share sensitive info.
Upvotes: 1 <issue_comment>username_2: If I got your question right you want your client(React App) to be the only client who can access your server.
As a solution to that you will have to have a combination of CORS and a JWT authorization, Thus I would suggest having a strict CORS to enable only your react app's domain to make a call to the server. To achieve this, I generally use a [CORS](https://www.npmjs.com/package/cors#configuration-options) npm module and [configure](https://www.npmjs.com/package/cors#configuration-options) the origin on my server or you can do it yourself as well.
```
var express = require('express')
var cors = require('cors')
var app = express()
var corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
```
The above code allows only requests from example.com to be accepted by the server or have a look at [this code](https://www.npmjs.com/package/cors#configuring-cors-w-dynamic-origin) for more dynamic whitelist & blacklist approach.
Now coming back to JWT, It is just a json encryption and decryption token which can share across API request to Authenticate as well as authorize the user.
For instance, you can store information like email, role, and nickname of the user in JWT and sent this encrypted JWT in each API request, the server authorizes this request and if true forwards to the requested API. This process of authorization and forwarding is generally implemented using an 'Interceptor' pattern wherein a middleware([Passport oAuth](http://www.passportjs.org/docs/oauth/)) does the check and auth before each API call.
---
Doing the above 2 things will ensure that only a client which has valid JWT token and domain address which you allowed to talk with the server. And this client will be your react app, as it is the only one with proper JWT and origin address.
So now your react app should just make sure that appropriate JWT token is passed in the API calls (post/get/put), most probably in the header of the API request, you can have an API helper service which does this for you and import that in component where-ever you make an API call. And your node server will implement the passport middleware pattern to authorize this JWT and filter non-authorized requests.
If you react app doesn't have a login, The JWT can be a client ID as well which recognizes your client as being legit. And just like user login, you can have you react app make a call to the server with data like a secret client id. This will return a JWT token. OR you can pre-generate a JWT token and you react app store it when it loads the first time, and by setting TTL and another config you can check if the Client which is making a call to your server is Old or New or some other fake client.
HTH
Upvotes: 5 [selected_answer]
|
2018/03/17
| 456 | 1,875 |
<issue_start>username_0: I am struggling to find a solution to prevent clients from just creating random fields with values in a document where they have write access to in Firestore. Since you cannot restrict access to single fields in Firestore like you could with the realtime database, this seems hard to achieve.
A solution would maybe be to not allow creation of fields and just letting clients update fields, but this would mean you would have to precreate the fields for documents which is not really a good solution in my opinion, especially if you have documents per user, which are dynamically created and having to use cloud functions to precreate fields in a document just seems unjustified.
Does anyone have a better solution?<issue_comment>username_1: As said in the Firebase Firestore documentation, you actually can prevent or allow writes or reads in certain fields. This can be achieved by adding a rule similar to this:
```
match /collection/{doc} {
allow update: if request.resource.data.field == resource.data.field;
}
```
Which would basically check if that specific field will have the exact same value after the update. You can also add rules to check if the requested value is between a range or equals to (your predefined value).
```
allow update: if request.resource.data.field > 0 && request.resource.data.field > 100;
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: You can inspect the keys of the `request.resource` and only have it pass if it doesn't contain a field that you want to keep read-only (meaning that the request isn't trying to update that field). For example:
```
allow update: if !request.resource.data.keys().hasAny(['my_field'])
```
(Thanks to [<NAME>](https://medium.com/@jqualls) for the [inspiration](https://medium.com/@jqualls/firebase-firestore-unique-constraints-d0673b7a4952)!)
Upvotes: 2
|
2018/03/17
| 1,463 | 4,695 |
<issue_start>username_0: I need to (1) generate a markdown file with a (2) series of plots for specific columns of a dataset that (3) match a particular string
At the moment I am stuck a the second point.
I want to plot some ordered characters factors using ggplot for the columns which name start with "pre\_"
Here the code that I've worked on till now
```
#load ggplot
library(ggplot2)
#reproduce a generic dataset
level=c("Strongly Agree", "Agree", "Neither agree or disagree","Disagree", "Strongly disagree",NA)
df <- data.frame(pre_1=as.character(sample(level, 20, replace = T)),
pre_2=as.character(sample(level, 20, replace = T)),
post_1=as.character(sample(level, 20, replace = T)),
post_2=as.character(sample(level, 20, replace = T)),
stringsAsFactors=T)
## function to plot each colum of the dataset that starts with pre_
dfplot_pre <- function(x)
{
df <- x
ln <- length(names(dplyr::select(df, starts_with("pre_"))))
for(i in 1:ln){
out <- lapply(df , function(x) factor(x, c("Strongly Agree", "Agree", "Neither agree or disagree","Disagree", "Strongly disagree"),ordered = T ))
df <- do.call(data.frame , out )
if(is.factor(df[,i])){ggplot(na.omit(data.frame(df[,i],stringsAsFactors = T)), aes(x=na.omit(df[i]))) +
theme_bw() +
geom_bar(aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(labels=percent) +
scale_x_discrete(drop=FALSE)}
else{print (fail)}
}
}
```
Unfortunately, the code does not display any plot. I am able to correctly plot the columns using the command
```
plot(df[,i])
```
so i suspect it's something wrong in ggplot but not sure what.
Running the code outside of the function and storing it in an object gives this error:
```
Don't know how to automatically pick scale for object of type data.frame. Defaulting to continuous.
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, :
arguments imply differing number of rows: 0, 1
```
Many thanks<issue_comment>username_1: Alternative solution
```
library(tidyverse)
library(scales)
dfplot_pre <- function(df) {
select(df, starts_with("pre_")) %>%
na.omit() %>%
gather() %>%
mutate(value = factor(value, levels = c("Strongly Agree", "Agree", "Neither agree or disagree","Disagree", "Strongly disagree"), ordered = TRUE)) %>%
ggplot(aes(x = value)) +
geom_bar(aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(labels=percent) +
scale_x_discrete(drop=FALSE) +
facet_wrap(~ key) +
theme_bw() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
}
```
Upvotes: 0 <issue_comment>username_2: ORIGINAL SOLUTION:
```
plot_pre <- function(df){
select(data, starts_with("pre_")) %>%
length() %>%
seq(1,.,1) %>%
for (i in .){
if (dummy(as.character(select(data, starts_with("pre_"))[[i]])) == TRUE) {
data.frame(select(data, starts_with("pre_"))[[i]]) %>%
na.omit() %>%
ggplot(.,aes(x=.)) +
geom_bar(aes(y = (..count..)/sum(..count..)), stat="count") +
geom_text(aes( label =paste(round((..count..)/sum(..count..)*100),"%"), y= (..count..)/sum(..count..)), stat= "count", vjust = -.5)+
scale_y_continuous(labels=percent,limits = c(-0, 1)) +
scale_x_discrete(drop=FALSE) +
ylab("Relative Frequencies (%)") +
ggtitle(names(select(data, starts_with("pre_")))[i]) +
theme_light(base_size = 18) +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
theme(plot.title = element_text(hjust = 0.5)) -> dummyplot
print(dummyplot)}
else {
factor(select(data, starts_with("pre_"))[[i]], c("Strongly Agree", "Agree", "Neither agree or disagree","Disagree", "Strongly disagree"),ordered = T ) %>%
data.frame() %>%
na.omit() %>%
ggplot(.,aes(x=.)) +
geom_bar(aes(y = (..count..)/sum(..count..)), stat="count") +
geom_text(aes( label =paste(round((..count..)/sum(..count..)*100),"%"), y= (..count..)/sum(..count..)), stat= "count", vjust = -.5)+
scale_y_continuous(labels=percent,limits = c(-0, 1)) +
scale_x_discrete(drop=FALSE) +
ylab("Relative Frequencies (%)")+
ggtitle(names(select(data, starts_with("pre_")))[i]) +
theme_light(base_size = 18) +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
theme(plot.title = element_text(hjust = 0.5))-> contplot
print(contplot)
}}
}
dfplot_pre(df)
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 3,372 | 14,071 |
<issue_start>username_0: I'm using symfony 3.4 with DoctrineMongoDBBundle and LexikJWTAuthenticationBundle . I'm trying to create a user login which return JWT token. If i specify the username and password under in\_memory provider, it returns the token but if i use a entity provider, it returns {"code":401,"message":"bad credentials"}.
Here is my security.yml
```html
# To get started with security, check out the documentation:
# https://symfony.com/doc/current/security.html
security:
# https://symfony.com/doc/current/security.html#b-configuring-how-users-are-loaded
encoders:
AppBundle\Document\User:
algorithm: bcrypt
cost: 12
providers:
webprovider:
entity:
class: AppBundle\Document\User
property: username
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/api/login
stateless: true
anonymous: true
provider: webprovider
form_login:
username_parameter: username
password_parameter: <PASSWORD>
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
require_previous_session: false
api:
pattern: ^/api
stateless: true
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
main:
anonymous: ~
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate
#http_basic: ~
# https://symfony.com/doc/current/security/form_login_setup.html
#form_login: ~
access_control:
- { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
```
Here is my User class
```html
php
// /AppBundle/Document/User.php
namespace AppBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Bundle\MongoDBBundle\Validator\Constraints\Unique as MongoDBUnique;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @MongoDB\Document(collection="users")
* @MongoDBUnique(fields="email")
*/
class User implements UserInterface
{
/**
* @MongoDB\Id
*/
protected $id;
/**
* @MongoDB\Field(type="string")
* @Assert\Email()
*/
protected $email;
/**
* @MongoDB\Field(type="string")
* @Assert\NotBlank()
*/
protected $username;
/**
* @MongoDB\Field(type="string")
* @Assert\NotBlank()
*/
protected $password;
/**
* @MongoDB\Field(type="boolean")
*/
private $isActive;
public function __construct()
{
var_dump("1");
$this-isActive = true;
// may not be needed, see section on salt below
// $this->salt = md5(uniqid('', true));
}
public function getId()
{
return $this->id;
}
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
public function setUsername($username)
{
$this->username = $username;
}
public function getUsername()
{
var_dump($this->username);
return $this->username;
}
public function getSalt()
{
return null;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password)
{
$this->password = $password;
}
public function getRoles()
{
return array('ROLE_USER');
}
public function eraseCredentials()
{
}
}
```
Would really appreciate if someone could help, Thanks.<issue_comment>username_1: You should use FOS bundle components by extending Base model User calss in entity, better than using directly Implementing UserInterface, In your case problem could be your password is not getting encoded correct. It's better to encode using `security.password_encoder`. To more better understanding i am sharing an example to setup login and generating token.
Your security.yml should look like this
```
`# Symfony 3.4 security.yml
security:
encoders:
FOS\UserBundle\Model\UserInterface: bcrypt
Symfony\Component\Security\Core\User\User: plaintext
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
ROLE_API: ROLE_USER, ROLE_MEDIC, ROLE_STUDENT
# https://symfony.com/doc/current/security.html#b-configuring-how-users-are-loaded
providers:
fos_userbundle:
id: fos_user.user_provider.username_email
in_memory:
memory: ~
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
api_login:
pattern: ^/api/login
stateless: true
anonymous: true
form_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
require_previous_session: false
api:
pattern: ^/(api)
stateless: true #false (not assign cookies)
anonymous: ~
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
provider: fos_userbundle
access_control: .................`
```
Your User class should be like this:
```
// /AppBundle/Document/User.php
namespace AppBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Bundle\MongoDBBundle\Validator\Constraints\Unique as MongoDBUnique;
/**
* @MongoDB\Document(collection="users")
* @MongoDBUnique(fields="email")
*/
class User implements BaseUser
{
/**
* @MongoDB\Id
*/
protected $id;
/**
* @MongoDB\Field(type="string")
* @Assert\Email()
*/
protected $email;
/**
* @MongoDB\Field(type="string")
* @Assert\NotBlank()
*/
protected $username;
/**
* @MongoDB\Field(type="string")
* @Assert\NotBlank()
*/
protected $password;
/**
* @MongoDB\Field(type="boolean")
*/
private $isActive;
public function __construct()
{
var_dump("1");
$this->isActive = true;
// may not be needed, see section on salt below
// $this->salt = md5(uniqid('', true));
}
public function getId()
{
return $this->id;
}
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
public function setUsername($username)
{
$this->username = $username;
}
public function getUsername()
{
var_dump($this->username);
return $this->username;
}
public function getSalt()
{
return null;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password)
{
$this->password = $<PASSWORD>;
}
public function getRoles()
{
return array('ROLE_USER');
}
public function eraseCredentials()
{
}
}
```
Now your Api tokenController.php to generate token and validate token
```
namespace \your_namespace\Api;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use AppBundle\Document\User;
# Below most of the components belongs to Nelmio api or Sensio or Symfony
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\ExpiredTokenException;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\InvalidTokenException;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException;
use Lexik\Bundle\JWTAuthenticationBundle\Security\Authentication\Token\PreAuthenticationJWTUserToken;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
class TokenController extends FOSRestController
{
/**
* @Rest\Post("/tokens", name="api_token_new",
* options={"method_prefix" = false},
* defaults={"_format"="json"}
* )
*
* @ApiDoc(
* section = "Security",
* description = "Get user token",
* parameters={
* {"name"="username", "dataType"="string", "required"=true, "description"="username or email"},
* {"name"="pass", "dataType"="string", "required"=true, "description"="password "},
* }
* )
*/
public function newTokenAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$username = $request->get('username');
/** @var User $user */
$user = $em->getRepository('AppBundle:User')->findOneBy(['email' => $username]);
if (!$user) {
throw $this->createNotFoundException();
}
if (!$user->isEnabled()){
throw $this->createNotFoundException($this->get('translator')->trans('security.user_is_disabled'));
}
$pass = $request->get('pass');
$isValid = $this->get('security.password_encoder')->isPasswordValid($user, $pass);
if (!$isValid) {
throw new BadCredentialsException();
}
$token = $this->get('lexik_jwt_authentication.encoder')->encode([
'username' => $user->getUsername(),
'id' => $user->getId(),
'roles' => $user->getRoles(),
'exp' => time() + (30 * 24 * 3600) // 30 days expiration -> move to parameters or config
]);
// Force login
$tokenLogin = new UsernamePasswordToken($user, $pass, "public", $user->getRoles());
$this->get("security.token_storage")->setToken($tokenLogin);
// Fire the login event
// Logging the user in above the way we do it doesn't do this automatically
$event = new InteractiveLoginEvent($request, $tokenLogin);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
$view = $this->view([
'token' => $token,
'user' => $user
]);
$context = new Context();
$context->addGroups(['Public']);
$view->setContext($context);
return $this->handleView($view);
}
/**
* @Rest\Post("/validate", name="api_token_validate",
* options={"method_prefix" = false},
* defaults={"_format"="json"}
* )
*
* @ApiDoc(
* section = "Security",
* description = "Get user by token",
* parameters={
* {"name"="token", "dataType"="textarea", "required"=true, "description"="token"},
* }
* )
*/
public function validateUserToken(Request $request)
{
$token = $request->get('token');
//get UserProviderInterface
$fos = $this->get('fos_user.user_provider.username_email');
//create PreAuthToken
$preAuthToken = new PreAuthenticationJWTUserToken($token);
try {
if (!$payload = $this->get('lexik_jwt_authentication.jwt_manager')->decode($preAuthToken)) {
throw new InvalidTokenException('Invalid JWT Token');
}
$preAuthToken->setPayload($payload);
} catch (JWTDecodeFailureException $e) {
if (JWTDecodeFailureException::EXPIRED_TOKEN === $e->getReason()) {
throw new ExpiredTokenException();
}
throw new InvalidTokenException('Invalid JWT Token', 0, $e);
}
//get user
/** @var User $user */
$user = $this->get('lexik_jwt_authentication.security.guard.jwt_token_authenticator')->getUser($preAuthToken, $fos);
$view = $this->view([
'token' => $token,
'user' => $user
]);
$context = new Context();
$context->addGroups(array_merge(['Public'],$user->getRoles()));
$view->setContext($context);
return $this->handleView($view);
}
```
if you face any problem then , let me know.
Upvotes: 2 <issue_comment>username_2: you need to add the provider before json\_login tag this the case for me
```
provider: fos_userbundle
```
Upvotes: 0
|
2018/03/17
| 868 | 3,081 |
<issue_start>username_0: I need help making a program that functions as a remote control. I'm not sure how to make a list from the different options that the user can choose. And then if it's not right just keep asking until the user powers the TV off. And it keeps giving me indentation errors, I need some advice with what I'm doing wrong, maybe some formatting and help simplifying my code but with nothing too advanced since I'm on my first semester of CS. It's basically def/return, while/for loops, and if/elif/else statements. Below is my code and directions (that I don't understand too well)
[Directions](https://i.stack.imgur.com/XdsP5.jpg)
Code
```
op1 =print ("'P' or 'p' Turns the power on")
op2 =print ("‘1’,’2’,’3’,’4’,’5’ Set a channel to the specified number")
op3 =print ("‘C+’ or ‘c+’ Add one to the current channel number")
op4 =print ("‘C-’ or ‘c-’ Subtract one to the current channel number")
op5 =print ("‘V+’ or ‘v+’ Add one to the current volume level")
op6 =print ("‘V-’ or ‘v-’ Subtract one from the current volume level")
op7 =print ("‘M’ or ‘m’ Mute the current volume level")
op0 =print ("‘X’ or ‘x’ Turn off the tv and exit the program")
print()
powerOff=False
channel =3
volume = 5
while powerOff !=False:
choice = input("Choose one of the above options: ")
while choice is not "x" or "X":
if choice == "x" or "X":
powerOff == True
elif choice == "P" or "p":
powerOff=False
if choice == volume and powerOff == False:
if choice == "M" or "m":
volume = 0
elif choice == "V+" or "v+":
volume+= 1
elif choice == "V-" or "v-":
volume= volume - 1
elif choice == channel and powerOff == False:
if choice == "1" or "2" or "3" or "4" or "5":
channel == choice
elif choice == "C+" or "c+":
channel += 1
elif choice == "C-" or "c-":
channel = channel - 1
else
choice == powerOff
print (choice)
choice = choice
```
Again, I just need advice to learn how to make this work and in a simpler way so I can apply it in the future, thanks<issue_comment>username_1: There are a couple of mistakes here.
1. Your outer `while` loop will never get executed because you start by setting `powerOff` to `False`.
2. The test `if choice == "x" or "X":` doesn't do what you think it does. It needs to be `if choice.upper() == "X":` or `if choice in ("x","X"):`. That needs to be fixed in 9 places, including the inner `while`.
3. Indentation is wrong in the last 2 lines: the `print()` call needs to be inside the `while` loop.
4. Assigning the value of the `print()` function to `op1` etc does nothing useful, beyond printing the instructions. The variables will all have the value `None`.
Upvotes: 2 <issue_comment>username_2: ```
while(True):
X= input("enter the command")
"""do what ever you want here""""
```
this will always ask for a single variable and you can check with if/else. use hold if you want to hold the asking statement.
Upvotes: 0
|
2018/03/17
| 642 | 2,346 |
<issue_start>username_0: I am fetching the details of a user according to Id on button click in a popup in laravel but It is showing some error.
This is viewuser.blade.php
```
#### Modal Heading
×
| | | |
| --- | --- | --- |
| {{$usersview->id}} | {{$usersview->firstname}} | {{$usersview->filename}} |
Close
```
This is viewparticipant.blade.php in which I have a button View. When the user will click on this button a popup will open and show the details according to Id.
```
[View]({{ URL::to('participant/show',$row->id) }}) |
```
My Controller:
```
php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Session;
use App\Imageupload;
class ParticipantController extends Controller
{
public function show($id)
{
$usersview = Imageupload::find($id);
return View::make('viewuser', compact('usersview'));
}
}
</code
```
My Web.php
```
Route::get('/participant/show/{id}','ParticipantController@show');
```
The error is showing that unknown variables in modal.<issue_comment>username_1: Try this:
```
[View]({{ URL::to('participant/show/{id}',$row->id) }}) |
```
Because laravel is figuring out where you want to place your $row->id variable, and to my guessing it's not passing the variable correctly in your route.
Upvotes: 1 <issue_comment>username_2: well you only have $usersview in your blade file and you're calling $row->id in viewparticipant.blade.php , which should be the $usersview->id instead
after Edit -->
so you need to make an ajax call to the function you want to get the results. the ajax must contain the id of the user so you should get the id some how. I usually define an on click function and get the id. then on the same click trigger an ajax call, something like this:
```
$('#user').on('click', function (event) {
$.ajax({
url: '/users?user_id=' + $(this).val(),
success: function (data) {
// parse the data
},
fail: function () {
// do something in case of failure
}
});
});
```
$(this).val(); is the id here, I assumed you would store that in an input
Upvotes: 3 [selected_answer]<issue_comment>username_3: try
```
@foreach($usersview as $usersview)
| {{$usersview->id}} | {{$usersview->firstname}} | {{$usersview->filename}} |
@endforeach
```
Upvotes: 1
|
2018/03/17
| 487 | 1,721 |
<issue_start>username_0: I have an error when I create my ngIf in the img tag here is my code:
```
![]()
```
Do you have an idea of the problem ?
Thank you
---
Thank you for answering, ok I put you a little more code. For information, if I remove the NgIf everything works correctly.
```
![]()
{{ results.title }}
```
[](https://i.stack.imgur.com/ZQTdv.png)<issue_comment>username_1: Try this:
```
[View]({{ URL::to('participant/show/{id}',$row->id) }}) |
```
Because laravel is figuring out where you want to place your $row->id variable, and to my guessing it's not passing the variable correctly in your route.
Upvotes: 1 <issue_comment>username_2: well you only have $usersview in your blade file and you're calling $row->id in viewparticipant.blade.php , which should be the $usersview->id instead
after Edit -->
so you need to make an ajax call to the function you want to get the results. the ajax must contain the id of the user so you should get the id some how. I usually define an on click function and get the id. then on the same click trigger an ajax call, something like this:
```
$('#user').on('click', function (event) {
$.ajax({
url: '/users?user_id=' + $(this).val(),
success: function (data) {
// parse the data
},
fail: function () {
// do something in case of failure
}
});
});
```
$(this).val(); is the id here, I assumed you would store that in an input
Upvotes: 3 [selected_answer]<issue_comment>username_3: try
```
@foreach($usersview as $usersview)
| {{$usersview->id}} | {{$usersview->firstname}} | {{$usersview->filename}} |
@endforeach
```
Upvotes: 1
|
2018/03/17
| 975 | 3,690 |
<issue_start>username_0: I have some trouble with my project in IE11 (It's react project, I use create-react-app prod build). It works fine in other browsers and in IE11 too, except if I click precise link to one route in IE11 (other routes work), it throws an error "Object doesn't support property or method 'includes'". I added 'babel-polyfill' but problem still exists, but if I, for example, not just load page, but reload it then too and then click that link, or when I load directly that link page it works fine.
I don't use 'includes' in my code, suppose it is used in some library, among those I use.
May be someone know, why it not work properly after loading page and after reloading only.
Thanks for help.<issue_comment>username_1: It appears to be handled separately from the rest of babel through [this](https://www.npmjs.com/package/babel-plugin-array-includes) plugin.
`includes` is a Javascript function that determines whether an item exists in an array, and it is not available in Internet Explorer. See docs/chart below. (Apparently it isn't part of babel by default because of some difficulty identifying whether a variable is an array. There are issues around this going back 2+ years in the babel repos.)
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes>
Part of the browser compatibility chart from those docs:
[](https://i.stack.imgur.com/IcAyE.png)
Upvotes: 2 <issue_comment>username_2: username_1's answer is great if you can control your javascript compilation process, however including a shim might be faster.
In my create-react-app project using react-select v2 i was hitting a few of these errors, and so included [air-bnb's bundle](https://www.npmjs.com/package/airbnb-js-shims):
`yarn add airbnb-js-shims`
and then added this single line to my code:
`import 'airbnb-js-shims';`
good luck!
Upvotes: 1 <issue_comment>username_3: Add below function in top of the all imports.
```
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value: function (searchElement, fromIndex) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If len is 0, return false.
if (len === 0) {
return false;
}
// 4. Let n be ? ToInteger(fromIndex).
// (If fromIndex is undefined, this step produces the value 0.)
var n = fromIndex | 0;
// 5. If n ≥ 0, then
// a. Let k be n.
// 6. Else n < 0,
// a. Let k be len + n.
// b. If k < 0, let k be 0.
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
function sameValueZero(x, y) {
return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}
// 7. Repeat, while k < len
while (k < len) {
// a. Let elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(searchElement, elementK) is true, return true.
if (sameValueZero(o[k], searchElement)) {
return true;
}
// c. Increase k by 1.
k++;
}
// 8. Return false
return false;
}
});
}
```
Upvotes: 0
|
2018/03/17
| 1,191 | 3,768 |
<issue_start>username_0: I am trying to find a way to create a named vector from two columns in a data frame (one of values, one of names) using pipes. Thus far I have the following (using `mtcars` as example data)...
```
library(tidyverse)
x <- mtcars %>%
rownames_to_column("car") %>%
select(car, mpg)
pull(mpg)
names(x) <- row.names(mtcars)
x
# Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout
# 21.0 21.0 22.8 21.4 18.7
# Valiant Duster 360 Merc 240D Merc 230 Merc 280
# 18.1 14.3 24.4 22.8 19.2
# Merc 280C Merc 450SE Merc 450SL Merc 450SLC Cadillac Fleetwood
# 17.8 16.4 17.3 15.2 10.4
# Lincoln Continental Chrysler Imperial Fiat 128 Honda Civic Toyota Corolla
# 10.4 14.7 32.4 30.4 33.9
# Toyota Corona Dodge Challenger AMC Javelin Camaro Z28 Pontiac Firebird
# 21.5 15.5 15.2 13.3 19.2
# Fiat X1-9 Porsche 914-2 Lotus Europa Ford Pantera L Ferrari Dino
# 27.3 26.0 30.4 15.8 19.7
# Maserati Bora Volvo 142E
# 15.0 21.4
```
This is not very convenient when it comes to my actual data, as I want to avoid saving a copy of the transformed data frame to only use the column of names for the `name` function.<issue_comment>username_1: We can use the `names<-` to get a named `vector`
```
library(tidyverse)
mtcars %>%
rownames_to_column("car") %>%
{'names<-'(.$mpg, .$car)}
```
---
Or with `set_names`
```
mtcars %>%
rownames_to_column("car") %>%
select(x = mpg, nm = car) %>%
pmap(set_names) %>%
unlist
```
Upvotes: 3 <issue_comment>username_2: Since {tibble} 1.3.0 (2017-04-02), you can use `tibble::deframe()` :
```
library(tidyverse)
mtcars %>%
rownames_to_column("car") %>%
select(car, mpg) %>%
deframe()
```
---
```
Mazda RX4 Mazda RX4 Wag Datsun 710
21,0 21,0 22,8
Hornet 4 Drive Hornet Sportabout Valiant
21,4 18,7 18,1
Duster 360 Merc 240D Merc 230
14,3 24,4 22,8
Merc 280 Merc 280C Merc 450SE
19,2 17,8 16,4
Merc 450SL Merc 450SLC Cadillac Fleetwood
17,3 15,2 10,4
Lincoln Continental Chrysler Imperial Fiat 128
10,4 14,7 32,4
Honda Civic Toyota Corolla Toyota Corona
30,4 33,9 21,5
Dodge Challenger <NAME> Camaro Z28
15,5 15,2 13,3
Pontiac Firebird Fiat X1-9 Porsche 914-2
19,2 27,3 26,0
Lotus Europa <NAME> L <NAME>
30,4 15,8 19,7
<NAME> Volvo 142E
15,0 21,4
```
Upvotes: 4 [selected_answer]
|
2018/03/17
| 1,447 | 4,761 |
<issue_start>username_0: I am printing list of arrays using checkboxes, the scenario is if I click one checkbox it display a list of numbers in the array, so my problem is if I click any checkbox it is displaying if I uncheck list is still in the display? so I want the code for, if I uncheck my list should go and when I click it should display.
```js
var men=[1,2,5,4,8,1,5];
var women=[45,55,45];
var children=[256,365];
document.getElementById("checkbox1").onchange=function(){
for(i=0; i";
document.getElementById("checkbox1").onchange='';
}
}
document.getElementById("checkbox2").onchange=function(){
for(i=0; i";
document.getElementById("checkbox2").onchange='';
}
}
document.getElementById("checkbox3").onchange=function(){
document.getElementById("checkbox3").onchange='';
for(i=0; i";
}
}
```
```html
men
women
children
```<issue_comment>username_1: Because you are removing `onchange` event from the element once shown all li's and not hiding them instead, see the update below
```js
var men = [1, 2, 5, 4, 8, 1, 5];
var women = [45, 55, 45];
var children = [256, 365];
document.getElementById("checkbox1").onchange = function() {
if (this.checked) {
for (i = 0; i < men.length; i++) {
document.getElementById("userlist").innerHTML += "- " + men[i] + "
";
//document.getElementById("checkbox1").onchange='';
}
} else {
document.getElementById("userlist").innerHTML = '';
}
}
document.getElementById("checkbox2").onchange = function() {
if (this.checked) {
for (i = 0; i < women.length; i++) {
document.getElementById("userlist").innerHTML += "- " + women[i] + "
";
//document.getElementById("checkbox2").onchange='';
}
} else {
document.getElementById("userlist").innerHTML = '';
}
}
document.getElementById("checkbox3").onchange = function() {
if (this.checked) {
for (i = 0; i < children.length; i++) {
document.getElementById("userlist").innerHTML += "- " + children[i] + "
";
}
} else {
document.getElementById("userlist").innerHTML = '';
}
}
```
```html
men
women
children
```
Upvotes: 0 <issue_comment>username_2: One option is to add all `-` on load and just hide/show on checkbox click.
```js
var men = [1, 2, 5, 4, 8, 1, 5];
var women = [45, 55, 45];
var children = [256, 365];
//Adding all the elements with style display:none
for (i = 0; i < men.length; i++) {
document.getElementById("userlist").innerHTML += "- " + men[i] + "
";
}
for (i = 0; i < women.length; i++) {
document.getElementById("userlist").innerHTML += "- " + women[i] + "
";
}
for (i = 0; i < children.length; i++) {
document.getElementById("userlist").innerHTML += "- " + children[i] + "
";
}
document.getElementById("checkbox1").onchange = function() {
var li = document.getElementsByClassName('li-men');
for (var i = 0; i < li.length; i++) {
if (document.getElementById('checkbox1').checked) {
li[i].style.display = '';
} else {
li[i].style.display = 'none';
}
}
}
document.getElementById("checkbox2").onchange = function() {
var li = document.getElementsByClassName('li-women');
for (var i = 0; i < li.length; i++) {
if (document.getElementById('checkbox2').checked) {
li[i].style.display = '';
} else {
li[i].style.display = 'none';
}
}
}
document.getElementById("checkbox3").onchange = function() {
var li = document.getElementsByClassName('li-children');
for (var i = 0; i < li.length; i++) {
if (document.getElementById('checkbox3').checked) {
li[i].style.display = '';
} else {
li[i].style.display = 'none';
}
}
}
```
```html
men
women
children
```
Upvotes: 1 <issue_comment>username_3: You can minimise and make your code generic in addition to showing and hiding the array values. You can associate a `onclick` function to each checkbox and pass parameters to those function like `type` which specifies the array that should be shown and checkbox reference so that you can manipulate this checkbox in javascript code:
```js
var men=[1,2,5,4,8,1,5];
var women=[45,55,45];
var children=[256,365];
function clickCb(type, cbElem){
var targetArray;
if(type === 'men'){
targetArray = men;
}
if(type === 'women'){
targetArray = women;
}
if(type === 'children'){
targetArray = children;
}
if (cbElem.checked) {
for (i = 0; i < targetArray.length; i++) {
document.getElementById("userlist").innerHTML += "- " + targetArray[i] + "
";
}
} else {
document.getElementById("userlist").innerHTML = '';
}
}
```
```html
men
women
children
```
Upvotes: 0
|
2018/03/17
| 186 | 604 |
<issue_start>username_0: I need dynamically change some options in Vue FullCalendar, but calendar didn't apply it.
Please look my example <https://codesandbox.io/s/3q2j3r7pjq>
Button in bottom set maxTime option from 20:00 to 18:00
How i can refresh calendar view?<issue_comment>username_1: I found it =)
```js
this.$refs.calendar.fireMethod('option', optionName, optionValue)
```
Upvotes: 2 <issue_comment>username_2: You have to define reference for the calendar component and call setOption on its api
```
...
this.$refs.fullCalendar.getApi().setOption('maxTime', '18:00:00');
```
Upvotes: 0
|
2018/03/17
| 412 | 1,482 |
<issue_start>username_0: I am querying my users to return a list of them, here is an example
```
$user_list = DB::table('users')
->select('name','email','created_at')
->orderBy('created_at')
->get();
```
I am seeing the correct results, but I am trying to split these results up so that they are grouped by month.
Does anybody have some docs I can read or some example code of doing this?<issue_comment>username_1: Try this:
```
$user_list = DB::table('users')
->select('name','email','created_at')
->orderBy('created_at')
->groupBy(DB::raw('MONTH(created_at)'))
->get();
```
Upvotes: 2 <issue_comment>username_2: There is section in the docs, where you can find an information about the `groupBy` method - [method](https://laravel.com/docs/5.6/collections#collection-method)
In your code you can write this():
```
$user_list = User::select('name','email','created_at')
->orderBy('created_at')->get();// get User collection
$user_list->groupBy(function ($item, $key) {
return $item->created_at->format('m');
});
```
Upvotes: 1 [selected_answer]<issue_comment>username_3: ```
$groupedUsers = $users->mapToGroups(function ($user, $key) {
return $user->created_at->month => $user;
});
```
This may be a little less code than some of the others. They will all work though. Here, you can replace `$users` with `User::all()` if you have your model set up correctly.
Upvotes: 0
|
2018/03/17
| 841 | 3,002 |
<issue_start>username_0: I used scroll view with images in table view cell But there are two problems :
1- there is an extra page not the count of my images and
2: the image doesn't fill the screen and there are white space between each image [](https://i.stack.imgur.com/geMpy.png)
and here is my table view cell with scroll view codes
```
class scrollViewCell: UITableViewCell , UIScrollViewDelegate {
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var scrollView: UIScrollView!
var contentWidth : CGFloat = 0.0
override func awakeFromNib() {
super.awakeFromNib()
scrollView.delegate = self
for image in 0...2 {
let imageToDisplay = UIImage(named : "1")
let imageView = UIImageView(image : imageToDisplay)
let xCoordinate = self.contentView.frame.midX + self.contentView.frame.width * CGFloat(image)
contentWidth += self.contentView.frame.width
scrollView.addSubview(imageView)
imageView.frame = CGRect(x: xCoordinate - 50 , y: 0 , width: self.contentView.frame.width, height: 100)
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleBottomMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleTopMargin]
imageView.contentMode = .scaleAspectFit // OR .scaleAspectFill
imageView.clipsToBounds = true
}
scrollView.contentSize = CGSize(width: contentWidth, height: self.contentView.frame.height)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(scrollView.contentOffset.x / CGFloat(414))
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
```<issue_comment>username_1: Issues is in your xCoordinate calculation, the contentView frame wont be available in awakeFromNib.
You should not user `super.awakeFromNib` to calculate the frames.
create a method called
`func configureUI(){
//Update your UI here
}`
Call this method from `cellForRowAtIndex:` delegate method of UITableViewCell
Upvotes: 0 <issue_comment>username_2: Can you try this
```
func addscrollV()
{
for image in 0...2 {
let imageToDisplay = UIImage(named : "1")
let imageView = UIImageView(image : imageToDisplay)
let xCoordinate = self.contentView.frame.width * CGFloat(image)
contentWidth += self.contentView.frame.width
scrollView.addSubview(imageView)
imageView.frame = CGRect(x: xCoordinate , y: 0 , width: self.contentView.frame.width, height: self.contentView.frame.height)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
}
scrollView.contentSize = CGSize(width: contentWidth, height: self.contentView.frame.height)
}
func layoutSubviews()
{
super.layoutSubviews()
if(Once)
{
Once = false
self.addscrollV()
}
}
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 675 | 2,601 |
<issue_start>username_0: I have a list of objects in my component and want to add functionality that when toggled, either get their `title` prop pushed onto an array or removed. The push part i implemented rather easily, however removing the value is pretty difficult since splicing by index doesn't help in this situation being that the items can be selected and pushed onto the array in any order:
**data**
```
data () {
return {
options = [
{
title: "pie",
isSelected: false
},
{
title: "cupcakes",
isSelected: false
},
{
title: "muffins",
isSelected: false
}
],
selected : []
}
},
```
**template**
```
{{ item.title }}
```
**script**
```
toggleSelected: function (index, item) {
item.isSelected = !item.isSelected
if (this.selected.includes(item.title)) {
return this.selected.splice(item.title) // does not work as expected
}
return this.selected.push(item.title)
}
```
I know i am syntactically using `splice` incorrectly, so how do i achieve what i am looking to do? with or without `splice`?<issue_comment>username_1: Why not simply filter it out?
```
return this.selected = this.selected.filter(title => title !== item.title);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: The expected parameters of the [`splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) function are the **start index** and the **delete count**
Which means that you'll have to do something like this:
```
this.selected.splice(this.selected.indexOf(item.title), 1);
```
Upvotes: 2 <issue_comment>username_3: [The correct form for splice is `(index, count, insert)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice). The last parameter `insert` changes the behavior of the function to *add* to the array, as opposed to removing. To use splice here, you'll first have to get the index of the item, then specify that you want to remove one item by leaving the last parameter out.
```
const index = this.selected.indexOf(item.title)
if (index > -1) {
this.selected.splice(index, 1);
}
```
Alternatively, [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) works as a simple alternative, and is the approach I'd go with here.
```
this.selected = this.selected.filter(title => title !== item.title)
```
Upvotes: 1
|
2018/03/17
| 670 | 2,015 |
<issue_start>username_0: Say I have four dates, for example:
* 1/1/2018
* 2/5/2018
* 4/8/2018
* 9/9/2018
I want to 'select' a date in between the min and max. Either the 2/5/2018 record or the 4/8/2018 record ONLY.
I think I'm close, but this query returns ALL the rows:
```
SELECT * FROM RUBERIC R
WHERE R.SCHOOLID = 75
AND R.TEACHERID = 610
AND R.OBSERVED = 'Observed Classroom'
AND R.DATE BETWEEN
(SELECT MIN(DATE) FROM RUBERIC WHERE R.SCHOOLID = 75
AND R.TEACHERID = 610 AND R.OBSERVED = 'Observed Classroom' )
AND
(SELECT MAX(DATE) FROM RUBERIC WHERE R.SCHOOLID = 75
AND R.TEACHERID = 610 AND R.OBSERVED = 'Observed Classroom' )
```<issue_comment>username_1: Why not simply filter it out?
```
return this.selected = this.selected.filter(title => title !== item.title);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: The expected parameters of the [`splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) function are the **start index** and the **delete count**
Which means that you'll have to do something like this:
```
this.selected.splice(this.selected.indexOf(item.title), 1);
```
Upvotes: 2 <issue_comment>username_3: [The correct form for splice is `(index, count, insert)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice). The last parameter `insert` changes the behavior of the function to *add* to the array, as opposed to removing. To use splice here, you'll first have to get the index of the item, then specify that you want to remove one item by leaving the last parameter out.
```
const index = this.selected.indexOf(item.title)
if (index > -1) {
this.selected.splice(index, 1);
}
```
Alternatively, [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) works as a simple alternative, and is the approach I'd go with here.
```
this.selected = this.selected.filter(title => title !== item.title)
```
Upvotes: 1
|
2018/03/17
| 626 | 2,168 |
<issue_start>username_0: I am trying to set the drop down height of my `AutoCompleteTextView` to be 60dp above the bottom of screen.
```
displayMetrics = new DisplayMetrics();
WindowManager windowmanager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
int height = Math.round(displayMetrics.heightPixels / displayMetrics.density - 60);
edtSeach.setDropDownHeight(height);
```
This works on my Huawei P9 Lite running Android 7.0.
[](https://i.stack.imgur.com/jJmAf.png)
However, when I try on emulator running Android 6.0, it is not working.
[](https://i.stack.imgur.com/M74h0.png)
How to solve this?<issue_comment>username_1: Why not simply filter it out?
```
return this.selected = this.selected.filter(title => title !== item.title);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: The expected parameters of the [`splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) function are the **start index** and the **delete count**
Which means that you'll have to do something like this:
```
this.selected.splice(this.selected.indexOf(item.title), 1);
```
Upvotes: 2 <issue_comment>username_3: [The correct form for splice is `(index, count, insert)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice). The last parameter `insert` changes the behavior of the function to *add* to the array, as opposed to removing. To use splice here, you'll first have to get the index of the item, then specify that you want to remove one item by leaving the last parameter out.
```
const index = this.selected.indexOf(item.title)
if (index > -1) {
this.selected.splice(index, 1);
}
```
Alternatively, [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) works as a simple alternative, and is the approach I'd go with here.
```
this.selected = this.selected.filter(title => title !== item.title)
```
Upvotes: 1
|
2018/03/17
| 285 | 1,150 |
<issue_start>username_0: I'm trying to write my first watchOS app. I don't have an actual Apple Watch yet so I wanted to see if I could test it on my iPhone 7. So I wrote a basic Hello World app, and I can see that when I run it on my phone, it loads the launchscreen storyboard first and then moves onto the Main storyboard. But when will the app then move onto the Interface storyboard which is where the "Hello world!" on a Watch-sized screen is printed?<issue_comment>username_1: You cannot run the watch app on an iPhone for testing. When you create the watch app in Xcode, you can use an Xcode simulator to run the watch app on your computer for testing. This way you can test without having an Apple Watch.
Upvotes: 1 <issue_comment>username_2: iPhone app runs in iPhone/iPad/iPod with same UI if app is not universal.
If app is universal, then same app can be run on iPhone/iPad/iPod but XIBs/Interface may vary for iPad and iPhone/iPod.
watchOS app runs on watch either via Simulator or directly on watch with iPhone pairing.
watchOS app has two parts - WatchKit app and WatchKit extension. Both boxed under the iPhone bundle.
Upvotes: 0
|
2018/03/17
| 696 | 2,623 |
<issue_start>username_0: I have a PDFView that's set to use a pageViewController:
```
let pdfView = PDFView()
let pdfDoc = PDFDocument(url: Bundle.main.url(forResource: "test", withExtension: "pdf")!)
pdfView.document = pdfDoc
pdfView.autoScales = true
pdfView.displayDirection = .horizontal
pdfView.usePageViewController(true, withViewOptions: [:])
```
Whenever I swipe to get to the next page, said next page is blurry for half a second before it's rendered sharply. That is quite annoying. Can I somehow preload the pages? I haven't found any attributes/methods in the documentation.
(Interestingly, I have the exact same problem in `Preview` on `MacOS` when it's in fullscreen mode [since forever, on every mac I own])
It's not reliant on pdf (file) size. The problem occurs with every pdf I tried.
Thanks for any help<issue_comment>username_1: I think this is due to the high resolution of your PDF and the way PDFView renders PDF. Do you have more information on your PDF?
Could you try with a PDF with less heavy images? It should render fine. If so, it's not your code which is at fault, but the resources needed to display and render it to the view.
**UPDATE**
You can try using the PDFView without PageViewController and see you it behaves. You could do this:
```
pdfView = PDFView(frame: view.frame)
pdfView.backgroundColor = UIColor.white
var documentName: String = "test"
if let documentURL = Bundle.main.url(forResource: documentName, withExtension: "pdf") {
if let document = PDFDocument(url: documentURL) {
pdfView.autoScales = true
pdfView.displayDirection = .horizontal
pdfView.displayMode = .singlePageContinuous
pdfView.document = document
}
}
self.view.addSubview(pdfView)
```
Does it behave differently? I've notice that the option `usePageViewController` loads the document faster for big PDF documents. Something to take into consideration when implementing.
I hope this helps
Upvotes: 1 <issue_comment>username_2: Please make sure to add values of .maxScaleFactor .minScaleFactor also as per your requirement and see if it makes any difference in the loading time.
e.g.
```
.maxScaleFactor = 4.0;
.minScaleFactor = self.scaleFactorForSizeToFit;
```
Upvotes: 1 <issue_comment>username_3: Did you try to change the interpolationQuality option ?
>
> The interpolation quality for images drawn into the PDFView context.
>
>
>
Possible values are
* none
* low
* high
Maybe you could try something like
```
pdfView.interpolationQuality = .low
```
or
```
pdfView.interpolationQuality = .none
```
Upvotes: 0
|
2018/03/17
| 588 | 2,370 |
<issue_start>username_0: I'm using a Unity WebGL App in a Bootstrap modal (dialogbox) of a website. As long as this modal isn't visible (`display:none`), there is always this error in the console log: `"Screen position out of view frustum"`.
How can I handle or avoid this error?<issue_comment>username_1: Ok, I've got a dirty solution for this issue in my case.
I've written a function in Unity to disable my main camera. So every time I'm hiding the container with the Unity WebGL (modal or dialogbox, etc.), I'm going to call this function do disable the main camera from JavaScript and the error disappears. By showing the container (modal or dialogbox, etc.) I'm simply enabling the camera again. Not an elegant solution but works for me. But I would appreciate a better solution.
Upvotes: 1 <issue_comment>username_1: The code for my solution is very simple. In Unity I've written a ***C# script*** which gets the camera as public variable `mainCamera` and two functions `disableCamera()` and `enableCamera()`. Cause my WebGL View is hidden on startup, I set the camera by calling `disableCamera()` in the `Start()` function. Just assign your main camera to the `mainCamera` variable by drag and drop in the Unity editor. Drag this Script to any object in the scene. For me, the object is a Canvas called **`Controller`**.
```
[Header ("Camera")]
public Camera mainCamera;
// Use this for initialization
void Start () {
disableCamera();
}
public void disableCamera() {
mainCamera.enabled = false;
}
public void enableCamera() {
mainCamera.enabled = true;
}
```
On my website I've loaded the Unity WebGL App and call the function `enableCamera()` from ***JavaScript*** whenever I need it. My Unity WebGL app is loaded like that:
```
var myApp = UnityLoader.instantiate("myDivContainerID", "pathToUnityBuild.json", etc....);
```
Now you can call the function to activate or deactivate the camera by using the `SendMessage` methode of the `GameInstance` (`myApp`). It can call a function of a script assigned to an object in Unity. In this case it's called **`Controller`**:
```
myApp.SendMessage('Controller','enableCamera');
```
`SendMessage` accepts 3 parameters, so you can call a function with a value if you want. E.g.:
```
myApp.SendMessage('Controller','enableCamera', 'true');
```
And that's it!
Upvotes: 3 [selected_answer]
|
2018/03/17
| 762 | 2,330 |
<issue_start>username_0: I've been toying around with Scala's floating point interpolation feature but I can't really totally understand its rules. Could anyone shed light in what the different components of the formatting are?
```
println(f"${1234.5678}%1.2f") // prints 1234.57
println(f"${1234.5678}%1.5f") // prints 1234.56780
println(f"${1234.5678}%09.2f") // prints 001234.57
println(f"${1234.5678}%9.2f") // prints " 1234.57"
```
For example, is it possible to left pad the string with any other different character than `' '` or `0`? Is it possible when rounding to just chop off decimal places instead of rounding them as it actually does in the examples above?
Thanks<issue_comment>username_1: ```
println (f"${1234.5678}%1.2f") // prints 1234.57
```
2 decimal places. 1 Place in total is too few, to display the whole number, which has 4+dot+2 = digits at least
```
println (f"${1234.5678}%1.5f") // prints 1234.56780
```
Like above: 1 in total is too few. 4+dot+5= 10 in reality
```
println (f"${1234.5678}%09.2f") // prints 001234.57
```
9 in total, filled with zeros, 2 after delimiter fits.
```
println (f"${1234.5678}%9.2f") // prints " 1234.57"
```
9 in total, filled with spaces, 2 after delimiter fits.
So the numbers %T.Rf are the total width=T and the decimal places are R. But if the number doesn't fit, the layout is sacrificed for correctness. Better you know how much to pay, how hot the cpu is or whatever the number shows - the JVM doesn't know. So T should always be bigger than R (+ 1 for the delimiter).
Upvotes: 0 <issue_comment>username_2: Afaik, scala `f` use java `System.out.printf` formatter.
If you look at `src.zip!\java\util\Formatter.java`, you could see something like follows:
```
// parse those flags which may be provided by users
private static Flags parse(char c) {
switch (c) {
case '-': return LEFT_JUSTIFY;
case '#': return ALTERNATE;
case '+': return PLUS;
case ' ': return LEADING_SPACE;
case '0': return ZERO_PAD;
case ',': return GROUP;
case '(': return PARENTHESES;
case '<': return PREVIOUS;
default:
throw new UnknownFormatFlagsException(String.valueOf(c));
}
}
```
Here you can see just above symbol supports, cannot customize your own, FYI.
Upvotes: 1
|
2018/03/17
| 514 | 1,740 |
<issue_start>username_0: I am working on a website, which is using Bootstrap 4. In this, I am facing the responsive issues as follows:
In my website, I have a search box and company name and my cart box as look like in the image. (in a maximized window)
[](https://i.stack.imgur.com/jUQXX.png)
When I reduce the browser window size it changes to:
[](https://i.stack.imgur.com/jQx42.png)
HTML code:
```

```
How to solve this issue?<issue_comment>username_1: ```html
@
```
Upvotes: -1 <issue_comment>username_2: >
> Bootstrap input-group not responsive
>
>
>
That's because **you aren't using responsive classes**.
You are using classes like `col-3`, `col-1` and `col-4`.
Those classes literally mean:
>
> "Keep this column 3 units wide, 1 unit wide, 4 units wide etc starting from the smallest screens and on."
>
>
>
So, at any screen size, your columns will take up exactly the specified number of units. In other words, Bootstrap is behaving exactly as expected because you haven't specified/added any responsive column classes.
On the smallest screen (inside a container), 3 units will roughly result in 73px. So, on the smallest screen, your `col-3` column will be only 73px wide and if you take 15px of padding on each side into account, then you really don't have much space left for any content.
Docs for responsive grid and column layout:
<https://getbootstrap.com/docs/4.0/layout/grid/#grid-options>
And:
<https://getbootstrap.com/docs/4.0/layout/grid/#responsive-classes>
Upvotes: 1 [selected_answer]
|
2018/03/17
| 1,315 | 4,463 |
<issue_start>username_0: I am following Chapter 5, "React with JSX", of "Learning React" from O'Reilly.
I wrote the Recipes App using `create-react-app` as the base.
**index.js**
```js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Menu from './Menu';
import registerServiceWorker from './registerServiceWorker';
import data from './data/recipes';
window.React = React;
ReactDOM.render(, document.getElementById('root'));
registerServiceWorker();
```
**Menu.js**
```js
import Recipes from './Recipes';
const Menu = ({recipes}) => (
Delicious Recipes
=================
{recipes.map((recipe, i)=>
)}
);
export default Menu;
```
And have the following error:
```sh
Failed to compile ./src/Menu.js
Line 5: 'React' must be in scope when using JSX react/react-in-jsx-scope
Line 6: 'React' must be in scope when using JSX react/react-in-jsx-scope
Line 7: 'React' must be in scope when using JSX react/react-in-jsx-scope
Line 9: 'React' must be in scope when using JSX react/react-in-jsx-scope
Line 11: 'React' must be in scope when using JSX react/react-in-jsx-scope
Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed.
```
The book says "setting `window.React` to `React` exposes the React library globally in the browser. This way all calls to `React.createElement` are assured to work". But it seems like I still need to import React on each file that uses JSX.<issue_comment>username_1: Import React on top of your Menu.js file:
```
import React from 'react'
```
React should always be imported in a particular file, that uses JSX if you are working with this library (React) in your project.
Upvotes: 7 [selected_answer]<issue_comment>username_2: This happens due to “React” import necessary in JSX file. The React library must also always be in scope from JSX code because JSX compiles as a react.
in your case 'React' must be import in Menu.js,
```
import React from "react";
```
[this is an error most beginner react developers made.](http://sandny.com/2019/10/24/the-most-common-errors-and-warnings-that-beginner-react-developers-make/#more-404)
[And also You can refer](https://reactjs.org/docs/jsx-in-depth.html#react-must-be-in-scope)
Upvotes: 2 <issue_comment>username_3: This is as aresult of not importing React module from 'react' properties hence you can try importing the module and try using 'export' when declaring a function so that it will be easy to import them in other pages using 'import {Menu} from menu' as shown below
```
import React from 'react';
import Recipes from './Recipes';
export const Menu = ({recipes}) => (
Delicious Recipes
=================
{recipes.map((recipe, i)=>
)}
);
```
Upvotes: 2 <issue_comment>username_4: In react 17 there is no need to import.
We can write code without importing react from React
<https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html>
>
> Together with the React 17 release, we’ve wanted to make a few
> improvements to the JSX transform, but we didn’t want to break
> existing setups. This is why we worked with Babel to offer a new,
> rewritten version of the JSX transform for people who would like to
> upgrade.
>
>
> Upgrading to the new transform is completely optional, but it has a
> few benefits:
>
>
> * With the new transform, you can use JSX without importing React.
>
>
>
eslint default config for react will still warn about it. But that can be disabled:
<https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md>
>
> If you are using the new JSX transform from React 17, you should
> disable this rule by extending react/jsx-runtime in your eslint config
> (add "plugin:react/jsx-runtime" to "extends").
>
>
>
Upvotes: 3 <issue_comment>username_5: **UPDATE 2022**
Importing `React` is considered as "unused import" and is recommended to be removed on longer term, see [react documentation](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#removing-unused-react-imports).
I got this error when setting up linter, here this is also pointed out by the [eslint documentation](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md#when-not-to-use-it), that you don't the need extra import from the React version 17 on.
Upvotes: 2
|
2018/03/17
| 958 | 3,299 |
<issue_start>username_0: I just installed php-cuong customer avatar (<https://github.com/php-cuong/magento2-customer-avatar>) on magento 2.1.8
My problem is that when I want to upload an image in customer panel it has error and not to upload image. In the admin panel, customer tab when I choose a customer and upload image it saves in pub/media but not show avatar and sends error.<issue_comment>username_1: Import React on top of your Menu.js file:
```
import React from 'react'
```
React should always be imported in a particular file, that uses JSX if you are working with this library (React) in your project.
Upvotes: 7 [selected_answer]<issue_comment>username_2: This happens due to “React” import necessary in JSX file. The React library must also always be in scope from JSX code because JSX compiles as a react.
in your case 'React' must be import in Menu.js,
```
import React from "react";
```
[this is an error most beginner react developers made.](http://sandny.com/2019/10/24/the-most-common-errors-and-warnings-that-beginner-react-developers-make/#more-404)
[And also You can refer](https://reactjs.org/docs/jsx-in-depth.html#react-must-be-in-scope)
Upvotes: 2 <issue_comment>username_3: This is as aresult of not importing React module from 'react' properties hence you can try importing the module and try using 'export' when declaring a function so that it will be easy to import them in other pages using 'import {Menu} from menu' as shown below
```
import React from 'react';
import Recipes from './Recipes';
export const Menu = ({recipes}) => (
Delicious Recipes
=================
{recipes.map((recipe, i)=>
)}
);
```
Upvotes: 2 <issue_comment>username_4: In react 17 there is no need to import.
We can write code without importing react from React
<https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html>
>
> Together with the React 17 release, we’ve wanted to make a few
> improvements to the JSX transform, but we didn’t want to break
> existing setups. This is why we worked with Babel to offer a new,
> rewritten version of the JSX transform for people who would like to
> upgrade.
>
>
> Upgrading to the new transform is completely optional, but it has a
> few benefits:
>
>
> * With the new transform, you can use JSX without importing React.
>
>
>
eslint default config for react will still warn about it. But that can be disabled:
<https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md>
>
> If you are using the new JSX transform from React 17, you should
> disable this rule by extending react/jsx-runtime in your eslint config
> (add "plugin:react/jsx-runtime" to "extends").
>
>
>
Upvotes: 3 <issue_comment>username_5: **UPDATE 2022**
Importing `React` is considered as "unused import" and is recommended to be removed on longer term, see [react documentation](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#removing-unused-react-imports).
I got this error when setting up linter, here this is also pointed out by the [eslint documentation](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md#when-not-to-use-it), that you don't the need extra import from the React version 17 on.
Upvotes: 2
|
2018/03/17
| 996 | 3,345 |
<issue_start>username_0: I want to know that why the latest version of Android Studio(3.0.1) has no drawable(ldpi,mdpi,hdpi,xdpi,xxdpi,xxxdpi), and has drawable-v21 ,drawable-24 and drawable folder only. for different resolution what we have to do?
I have few Questions here.
**1) Whey not the drawable(ldpi,mdpi,hdpi,xdpi,xxdpi,xxxdpi) created by default as before?**
**2) What is the purpose of drawable-21 and drawable-24?**<issue_comment>username_1: Import React on top of your Menu.js file:
```
import React from 'react'
```
React should always be imported in a particular file, that uses JSX if you are working with this library (React) in your project.
Upvotes: 7 [selected_answer]<issue_comment>username_2: This happens due to “React” import necessary in JSX file. The React library must also always be in scope from JSX code because JSX compiles as a react.
in your case 'React' must be import in Menu.js,
```
import React from "react";
```
[this is an error most beginner react developers made.](http://sandny.com/2019/10/24/the-most-common-errors-and-warnings-that-beginner-react-developers-make/#more-404)
[And also You can refer](https://reactjs.org/docs/jsx-in-depth.html#react-must-be-in-scope)
Upvotes: 2 <issue_comment>username_3: This is as aresult of not importing React module from 'react' properties hence you can try importing the module and try using 'export' when declaring a function so that it will be easy to import them in other pages using 'import {Menu} from menu' as shown below
```
import React from 'react';
import Recipes from './Recipes';
export const Menu = ({recipes}) => (
Delicious Recipes
=================
{recipes.map((recipe, i)=>
)}
);
```
Upvotes: 2 <issue_comment>username_4: In react 17 there is no need to import.
We can write code without importing react from React
<https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html>
>
> Together with the React 17 release, we’ve wanted to make a few
> improvements to the JSX transform, but we didn’t want to break
> existing setups. This is why we worked with Babel to offer a new,
> rewritten version of the JSX transform for people who would like to
> upgrade.
>
>
> Upgrading to the new transform is completely optional, but it has a
> few benefits:
>
>
> * With the new transform, you can use JSX without importing React.
>
>
>
eslint default config for react will still warn about it. But that can be disabled:
<https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md>
>
> If you are using the new JSX transform from React 17, you should
> disable this rule by extending react/jsx-runtime in your eslint config
> (add "plugin:react/jsx-runtime" to "extends").
>
>
>
Upvotes: 3 <issue_comment>username_5: **UPDATE 2022**
Importing `React` is considered as "unused import" and is recommended to be removed on longer term, see [react documentation](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#removing-unused-react-imports).
I got this error when setting up linter, here this is also pointed out by the [eslint documentation](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md#when-not-to-use-it), that you don't the need extra import from the React version 17 on.
Upvotes: 2
|
2018/03/17
| 182 | 621 |
<issue_start>username_0: I use raspberry pi 3.
Type 'bluetoothctl' in the linux command shell and type 'scan on', then
Raspberry pi search nearby devices.
i want to be able to search for devices on one command line.
for example, bluetoothctl + scan on , but i can't find this command
i tried `bluetoothctl` && `scan on(X)
bluetoothctl --agent` `scan on (X)
bluetoothctl ;`
`scan on(X)`
but these do not work.<issue_comment>username_1: you can make one python script for execute command
import os;
os.system("")
Upvotes: 0 <issue_comment>username_2: Use this
```
bluetoothctl -- scan on
```
Upvotes: 1
|
2018/03/17
| 180 | 631 |
<issue_start>username_0: I have the next XML with 4 Imagebuttons , I've set the images in two LinearLayouts and i gave the buttons weight of 1 so they will be oredered in the same line ,
```
```
And as you can there are empty space between the buttons , is there a way to remove that space and make the stick to each other?
[](https://i.stack.imgur.com/yjaos.png)<issue_comment>username_1: you can make one python script for execute command
import os;
os.system("")
Upvotes: 0 <issue_comment>username_2: Use this
```
bluetoothctl -- scan on
```
Upvotes: 1
|
2018/03/17
| 1,231 | 3,953 |
<issue_start>username_0: I have legacy PHP application. It used mysqli to make mysql things. So in config I have DSN string to connect to mysql service. Like that
`mysql://username:password@db_hostname/dbname`
Mysqli returns error
**Warning: mysqli::real\_connect(): php\_network\_getaddresses: getaddrinfo failed: Name or service not known**
But if I will try connect by hand using this
`mysqli::real_connect("db_hostname")`
It says **Warning: mysqli::real\_connect(): (HY000/1045): Access denied for user ''@'172.21.0.3' (using password: NO)**
`real_connect("user@db_hostname")`, `real_connect("mysql:db_hostname")`, `real_connect("mysql:host=db_hostname")` can not resolve host address.
What I'm doing wrong?
docker-compose.yml:
```
version: "3"
services:
nginx:
image: nginx:1.13-alpine
volumes:
- ./docker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
- ./docker/nginx/errors.log:/var/logs/errors.log
- ./docker/nginx/access.log:/var/logs/access.log
- ./:/var/www/html
ports:
- "8081:80"
command: nginx -g "daemon off;"
php:
build:
context: ./docker/
dockerfile: php.Dockerfile
user: "1000"
volumes:
- ./docker/timezone.php.ini:/usr/local/etc/php/conf.d/timezone.php.ini:ro
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
- ./:/var/www/html
db_hostname:
image: mysql:5.5
user: "1000"
environment:
- MYSQL_DATABASE=db
- MYSQL_ROOT_PASSWORD=root
- MYSQL_USER=user
- MYSQL_PASSWORD=<PASSWORD>
volumes:
- ./docker/mysql:/var/lib/mysql
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
```<issue_comment>username_1: As you missing **linking** you db container with php. When you link db with PHP it will be accessible from localhost of PHP.
Here is I modified your docker-compose file as I like alpine everywhere ;). And I use adminer and link with db to verfiy connection instead of code level checking. As i dont have you php docker file so i am creating php:alpine which contain php7.
```
version: "3"
services:
nginx:
image: nginx:1.13-alpine
container_name: nginx
ports:
- "8081:80"
command: nginx -g "daemon off;"
db:
image: mysql:5.5
environment:
MYSQL_ROOT_PASSWORD: <PASSWORD>
php:
image: php:alpine
container_name: php
tty: true
links:
- db
adminer:
image: adminer
container_name: adminer
ports:
- 8080:8080
links:
- db
```
Then i installed mysqli in php container
```
docker exec -it php ash
```
and run below command
```
docker-php-ext-install mysqli;
```
Then create test.php
here server name is **db**. Note that your server name will be what is db container name which is link to php.
if you `ping db` in php container it will ping db container.
```
php
$servername = "db";
$username = "root";
$password = "<PASSWORD>";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn-connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
```
Now run this file in php container. You can mount and run your php code but this is what I did for testing. And I tried as a root user.
```
php -f test.php
```
[](https://i.stack.imgur.com/76SZj.png)
And here is adminer which also link with db
[](https://i.stack.imgur.com/Z9lGY.png)
[](https://i.stack.imgur.com/5o9np.png)
Upvotes: 3 [selected_answer]<issue_comment>username_2: `docker-compose rm -v` use and delete MySQL volume.
Volumes:
* `./docker/mysql:/var/lib/mysql -> pathmysql`
* `/etc/timezone:/etc/timezone:ro`
* `/etc/localtime:/etc/localtime:ro`
Upvotes: 0
|
2018/03/17
| 931 | 3,434 |
<issue_start>username_0: I want to check if a method has returned a particular type of value of and want to use it in `if` statement.
I have a class called `DBConn` and there I have a static method called `dbConnect()` which returns a `Connection` type value if had a successful connection otherwise throws an exception.
In my `main class` I want to do something like
```
if (DBConn.dbConnect() == Connection) {
// then do something
}
```
Note that I am calling this static function inside the if condition.
How can I realize this in Java?<issue_comment>username_1: >
> I want to check if a method has returned a particular type of value
>
>
>
Use the `instanceof` operator.
```
if (DBConn.dbConnect() instanceof Connection) { ... }
```
It returns `true` if the left operand can be cast to the right operand. That is, if it either is `Connection` or a subtype of it, like some `FastConnection extends Connection`.
It is described in detail in the [JLS$15.20.2](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.20.2):
>
> At run time, the result of the `instanceof` operator is `true` if the value of the *RelationalExpression* is not `null` and the reference **could be cast** ([§15.16](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.16)) to the *ReferenceType* without raising a `ClassCastException`. Otherwise the result is `false`.
>
>
>
---
Note that your description sounds like you don't even need to check that. You say
>
> It returns `Connection` or throws an exception
>
>
>
If the method throws the exception your current code will fail and the `instanceof` doesn't help at all.
Instead you should to **catch the exception** ([official tutorial by Oracle](https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html)):
```
try {
Connection con = DBConn.dbConnect();
// Do something with con
} catch (ConnectionFailedException e) {
System.err.println("Connection failed!");
e.printStackTrace();
}
```
Also note that if you plan to use the result of the method later, you should probably save it in some variable. Otherwise you will need to repeatedly call the method which is just unnecessary and might introduce some problems depending on the implementation.
```
Connection con = DBConn.dbConnect();
// Rest of code
```
Upvotes: 1 <issue_comment>username_2: If the method is going to return a `Connection` or throw an exception, the correct way to handle this is
```
try {
Connection connection = SomeClass.someConnectionProvidingMethod();
} catch ( SomeException ) {
... handle exception ...
}
```
That is because the language itself would have to be broken to receive a non-Connection from a method like
```
public Connection someConnectionProvidingMethod() {
... implementation here ...
}
```
Now, if you really want to spend CPU cycles, time, and electricity checking if the language compiled correctly and the JVM is running properly, you could also do
```
if ( someVariable instanceof Connection ) {
...
}
```
but as you described it, the above statement could never be false, so you might as well have written
```
if ( true ) {
...
}
```
or
```
if ( 1 == 1 ) {
...
}
```
I recommend not putting in `if` statements that test conditions which are constant; because, they mislead other people reading your code, and will mislead you when you revisit your older code.
Upvotes: 0
|
2018/03/17
| 2,575 | 7,840 |
<issue_start>username_0: I have an array which is built from the user input. I am trying to loop through a nested key value pair and check whether the values in it matches any value of the given array. The purpose is to make a search facility.
My array :
```
FilteredSelectedOptions=["20180211","Trax","Vienna","AN01020"]
```
My key value pair is :
```
trips = {
"20180201": [{
"journeyId": 1001,
"Number": "001",
"DriverName": "Alex",
"Transporter": {
"id": "T1",
"number": "AN01001",
"Company": "Tranzient"
},
"place": [{
"id": 001,
"value": "Washington DC"
},
{
"id": 002,
"value": "Canberra"
}
],
},
{
"journeyId": 1002,
"Number": "001",
"DriverName": "Tom",
"Transporter": {
"id": "T2",
"number": "AN01002",
"Company": "Trax"
},
"place": [{
"id": 2,
"value": "Canberra"
},
{
"id": 4,
"value": "Vienna"
}
],
},
{
"journeyId": 1003,
"Number": "004",
"DriverName": "Jack",
"Transporter": {
"id": "T3",
"number": "AN01003",
"Company": "Trax"
},
"place": [{
"id": 1,
"value": "Washington DC",
}, {
"id": 4,
"value": "Vienna",
}],
}
],
"20180211": [{
"journeyId": 1004,
"Number": "005",
"DriverName": "Jack",
"Transporter": {
"id": "T3",
"number": "AN01013",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Ottawa"
},
{
"id": 4,
"value": "Vienna"
}
],
},
{
"journeyId": 1005,
"Number": "005",
"DriverName": "Jerry",
"Transporter": {
"id": "T3",
"number": "AN01020",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Ottawa"
}
],
}
],
"20180301": [{
"journeyId": 1006,
"Number": "005",
"DriverName": "demy",
"Transporter": {
"id": "T3",
"number": "AN01003",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Ottawa"
}
],
}],
};
```
I am expecting output like this :
```
trips = {
"20180201":
[{
"journeyId": 1002,
"Number": "001",
"DriverName":"Tom",
"Transporter": {
"id": "T2",
"number": "AN01002",
"Company": "Trax"
},
"place": [{"id":002,"value":"Canberra" }]
[{"id":004,"value":"Vienna"}]
},
{
"journeyId": 1003,
"Number": "004",
"DriverName":"Jack",
"Transporter": {
"id": "T3",
"number": "AN01003",
"Company": "Trax"
},
"place": [{"id":001,"value":"Washington DC" }]
[{"id":004,"value":"Vienna"}]
}],
"20180211": [{
"journeyId": 1004,
"Number": "005",
"DriverName":"Jack",
"Transporter": {
"id": "T3",
"number": "AN01013",
"Company": "Trax"
},
"place": [{"id":005,"value":"Bridgetown" }]
[{"id":006,"value":"Ottawa"}]
[{"id":004,"value":"Vienna"}]
},
{
"journeyId": 1005,
"Number": "005",
"DriverName": "Jerry",
"Transporter": {
"id": "T3",
"number": "AN01020",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Ottawa"
}
]
};
```
I am trying to use a for loop to check each array elements against the key value pair. What I want to do basically is
```
for (option in FilteredselectedOptions)
{
//logic
}
```
I have been able to do it for one particular array value:
```
const filteredTrips = Object.keys(trips).reduce((tmp, x) => {
const filtered = trips[x].filter(y => y.place && y.place.some(z => z.value === 'Vienna'));
if (filtered.length) {
tmp[x] = filtered;
}
return tmp;
}, {});
```
But how do I do it for all array elements irrespective of how many elements are inside array. Please help in the loop.<issue_comment>username_1: One could use recursion to search for values in an object:
```
function hasValue(obj, values){
for(const value of Object.values(obj)){
if(typeof value === "object"){
if(hasValue(value, values))
return true;
} else {
if(values.includes(value))
return true;
}
}
return false;
}
```
Now we could filter your trips by comparing the keys and using the function above:
```
const filteredTrips = Object.keys(trips).filter(key => {
if(FilteredSelectedOptions.includes(key))
return true;
if(hasValue(trips[key], FilteredSelectedOptions))
return true;
return false;
});
```
Upvotes: 1 <issue_comment>username_2: Let me know if you want a complete code.
Lets begin that objects in javascript don't have built in filter or reduce methods, only arrays do. What I would do, I would loop through the object properties, which are arrays, and check if they have one of the properties that are found in the FilteredSelectedOptions. If I find one, I will push it to a new array containing the results.
Upvotes: 0 <issue_comment>username_3: Just an approach by trying to filter with finding a single item in the data.
```js
function filter(object, options) {
const check = v => options.includes(v) || v && typeof v === 'object' && Object.keys(v).some(l => check(v[l]));
var result = {};
Object.keys(object).forEach(function (k) {
var temp = options.includes(k)
? object[k]
: object[k].filter(check);
if (temp.length) {
result[k] = temp;
}
});
return result;
}
var trips = { "20180201": [{ journeyId: 1001, Number: "001", DriverName: "Alex", Transporter: { id: "T1", number: "AN01001", Company: "Tranzient" }, place: [{ id: "001", value: "Washington DC" }, { id: "002", value: "Canberra" }] }, { journeyId: 1002, Number: "001", DriverName: "Tom", Transporter: { id: "T2", number: "AN01002", Company: "Trax" }, place: [{ id: 2, value: "Canberra" }, { id: 4, value: "Vienna" }] }, { journeyId: 1003, Number: "004", DriverName: "Jack", Transporter: { id: "T3", number: "AN01003", Company: "Trax" }, place: [{ id: 1, value: "Washington DC" }, { id: 4, value: "Vienna" }] }], "20180211": [{ journeyId: 1004, Number: "005", DriverName: "Jack", Transporter: { id: "T3", number: "AN01013", Company: "Trax" }, place: [{ id: 5, value: "Bridgetown" }, { id: 6, value: "Ottawa" }, { id: 4, value: "Vienna" }] }, { journeyId: 1005, Number: "005", DriverName: "Jerry", Transporter: { id: "T3", number: "AN01020", Company: "Trax" }, place: [{ id: 5, value: "Bridgetown" }, { id: 6, value: "Ottawa" }] }], "20180301": [{ journeyId: 1006, Number: "005", DriverName: "demy", Transporter: { id: "T3", number: "AN01003", Company: "Trax" }, place: [{ id: 5, value: "Bridgetown" }, { id: 6, value: "Ottawa" }] }] },
options = ["20180211", /* "Trax", */ "Vienna", "AN01020"];
console.log(filter(trips, options));
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 468 | 1,449 |
<issue_start>username_0: In fact I have a table to store the details of calls and I need to filter the calls which entered the IVR after 16:00:00 till 06:59:00 the next day for **ENTIRE MONTH** I have used *BETWEEN* clause but it includes the details of all times of the month.
```
SELECT
[conversationId],
[conversationStart]
FROM
[Customer].[dbo].[vw_Conversations]
WHERE
conversationStart BETWEEN '2018-01-01 16:00:00.000' AND '2018-01-31 06:59:59.000'
```
Any help would be appreciated<issue_comment>username_1: You need to just test the time component. I am not sure what date range you want, but the query is something like this:
```
SELECT conversationId, conversationStart
FROM Customer.dbo.[w_Conversations c
WHERE CONVERT(date, conversationStart) >= '2018-01-01' AND
CONVERT(date, conversationStart) < '2018-02-01' AND
(CONVERT(time, conversationStart) >= '16:00:00') OR
CONVERT(time, conversationStart) < '07:00:00')
);
```
Upvotes: 2 <issue_comment>username_2: Use [`DATEPART()`](https://learn.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql) function to test hour of the day. In your case, checking hours is enough:
```
SELECT conversationId,
conversationStart
FROM [Customer].[dbo].[vw_Conversations]
WHERE conversationStart BETWEEN '2018-01-01' AND '2018-02-01'
AND DATEPART(hour, conversationStart) NOT BETWEEN 7 AND 15
```
Upvotes: 3 [selected_answer]
|
2018/03/17
| 916 | 2,815 |
<issue_start>username_0: Hello i am creating a best recently product view based on php cookies. first of all whenever user view some data so i store cookie as follow
```
//by Creating Manually array
$cookieArr = array("productid"=>$row_category[0],"views"=>1);
setcookie("myshopping", $cookieArr, time() + (8640000 * 30), "/");
```
Which Output As follow
```
(
[productid] => 27
[views] => 1
)
```
Now When user visit another page as example if `35 number page` so output should be like
```
(
[productid] => 27,35
[views] => 1,1
)
```
this is not a problem to how to add this. the problem is i have to increement view if user visit same page again. for example if user visit 27 page again so arrray should like. means data is not add just update the views.
```
(
[productid] => 27,35
[views] => 2,1
)
```
i tried by
```
foreach ($cookieArr as $key => $value) {
//Get all products
$allProdcutid = $cookieArr["productid"];
}
//than checking
if(in_array($myproductid, $cookieArr['productid'])){
echo "Avaibality";
}else{
echo "exit";
}
```
*This is for demonstration.*<issue_comment>username_1: Take a look at multi dimensional arrays... <https://www.w3schools.com/php/php_arrays_multi.asp>
You can form your cookie array like the below
```
(
[products] => [13=>array("views"=>1),27=>array("Views"=>4)]
)
```
then you can use array\_key\_exists on the products array to find your product id or add it.
Below is the php code:
```
if(array_key_exists($myproductid,$cookie['products'])
{
$cookie['products'][$myproductid]['views']++;
}
else
{
$cookie['products'][$myproductid]=array('views'=>1);
}
```
This way you can later add other properties than views to your product array...
Upvotes: 0 <issue_comment>username_2: You need to store your array with product\_id as key and views as a value. For example,
```
(
27 => 1,
37 => 2
)
```
By this you just have to check the key of the array and increment its value.
For example if user visits product id 27.
Upvotes: -1 <issue_comment>username_3: ***1.*** you can create array like below:-
```
Array(
27=>1,
35=>1
)
```
This will be even more easy to handle. keys are productid's and values are how many time they visited.
***2.*** Or modify your code like below:-
```
php
$myproductid = 27;
$cookieArr= array(
'productid' = '27,35',
'views' => '1,1'
);
if(in_array($myproductid, explode(',',$cookieArr['productid']))){
$searched_key = array_search($myproductid,explode(',',$cookieArr['productid']));
$views_array = explode(',',$cookieArr['views']);
$views_array[$searched_key] +=1;
$cookieArr['views'] = implode(',',$views_array);
}else{
echo "exit";
}
print_r($cookieArr);
```
Output:-<https://eval.in/973605>
Upvotes: 1 [selected_answer]
|
2018/03/17
| 519 | 1,605 |
<issue_start>username_0: I just wanted to know that I have some values written in Cell `J10` as shown in image and want to sum these values in cell `K10` cell.
To do so, I currently add them manually by typing `=1.25+1.25-1+.5` in cell `K10`.
Is there any way that cell `K10` automatically calculates the values entered in cell `J10` as shown in image, and cell `K10` automatically updates the total if I make any changes in values in cell `J10`?
[](https://i.stack.imgur.com/BHbF4.png)
[enter image description here](https://i.stack.imgur.com/BHbF4.png)<issue_comment>username_1: Use the following UDF
```
Function mySum(s As String) As Variant
mySum = Evaluate(s)
End Function
```
Upvotes: 2 <issue_comment>username_2: I'll assume you want to type the formula into J10 and have the result in K10 (per your narrative and image).
[](https://i.stack.imgur.com/iwkPD.png)
Go to Formulas, Defined Names, Name Manager and click New. Set up a new named range called `evalJ` with workbook scope and a Refers to: of,
```
=evaluate(column!$J1)
```
Click OK to create the name and exit the Name Manager.
Type your formula into J10 (e.g. 1.25+1.25-1+.5) without an equals sign. Put the following formula into K10,
```
=iferror(evalJ, "")
```
This can be used in any column to evaluate an equation in column J of the same row.
[](https://i.stack.imgur.com/8kNBX.png)
Upvotes: 1 [selected_answer]
|
2018/03/17
| 927 | 3,496 |
<issue_start>username_0: I want to make something like article to read view controller that contains UIImage and Label nested in the scroll view.
I want if the article content is not to big, the scrolling function is disabled, but if the content is big, I want it can be scrolled and it can be scrolled as the same height of the label content height.
(if the content article is not too much, then i don't need to scroll)
[](https://i.stack.imgur.com/EGUtE.png)
but if the content is a lot then I expect that I can scroll. at the moment, I can scroll if the content is big like below
[](https://i.stack.imgur.com/h7pWP.png)
I have tried to set the bottom anchor like my code below but it doesn't work. here is the autolayout I use for the bottom label contraint andthe view hierarchy
[](https://i.stack.imgur.com/mGcsF.png)
class NotificationDetailVC: UIViewController {
```
@IBOutlet weak var notificationTitleLabel: UILabel!
@IBOutlet weak var notificationImage: UIImageView!
@IBOutlet weak var notificationDateLabel: UILabel!
@IBOutlet weak var notificationScrollView: UIScrollView!
@IBOutlet weak var notificationContentLabel: UILabel!
var dataNotification : [String:Any]?
override func viewDidLoad() {
super.viewDidLoad()
notificationScrollView.contentLayoutGuide.bottomAnchor.constraint(equalTo: notificationContentLabel.bottomAnchor).isActive = true
}
```
}<issue_comment>username_1: Set Label bottom constaint equal to any constant height (say 20) & `number of lines = 0`.
as you are using `scrollview` then you have to give height to the `imageview`. You don't need to worry about label height bcz its heigght will be calculated by its content height.
Now your `scrollviewContentHeight = imgView.height + all labels content height`. Make sure each component (imageview & every label) have top and bottom constraint.
That's all you have to do.
Upvotes: 0 <issue_comment>username_2: Don't make bottom constraint to greater than. just set it equal to.
Scroll view has a content view which contains all scrollable view. You have to set height, width and x,y position of content view.
Set top, bottom, leading and trailing constraint to content view.
Scrollview's scrolling directions depands on height and width of contantview. if you set content view's width equal to scrollview than scrollview is not scrollable in horizontal direction. Same for height , if you set content view's height equal to scrollview's height than scrollview is not scrollable in vertical direction.
In your case you have to set content view's width equal to scrollview's width therefore scrollview is not scrollable in horizontal direction. Content view automatically get height according to subviews(In your case UIimageview and uilabel). so set height, top, bottom constraint of imageview and top and bottom constraints of uilabel because uilabel height automatically set by it's text. Set `number of line = 0` in UILabel.
[](https://i.stack.imgur.com/HkGyA.png)
[](https://i.stack.imgur.com/X6ARP.png)
[](https://i.stack.imgur.com/6k3UL.png)
Upvotes: 4 [selected_answer]
|
2018/03/17
| 479 | 1,831 |
<issue_start>username_0: I have one question, can we modify or assign any viewing angle to HTML visible tags because when I visited one website <https://datatables.net/download/>
While I see header of this website the first thought was come in my mind is whether there's any problem with the header? After scrolling I found the Bottom(footer) as a reciprocal of header and my thought was changed, the guy who developed this site have creative mind, but I found the contents of this site was not visually hatched after that I was think that if there is any way to modify or assign the value of angle by it will hatched, if it will possible then I will create one website which is looks like completely hatched means all tags like div, a, p, span, will render as hatched on screen, and I am now so excited to create about.
I know this is maybe impossible, but I know here on stackoverflow all types of genius available to help so can anyone tell me how it is possible or not
or is there any way to modify internal structure by JS or something else
**In short I want to create like this image if you don't understand the meaning of hatched line or viewing angle >>** [think of it as a 3 div element and one submit button](https://i.stack.imgur.com/0ZjZl.png)
thanks.<issue_comment>username_1: You could transform each element of the content by CSS. For the website you gave as example this rule would have to be applied:
```
.fw-body .content > * {
transform: rotate(-2deg);
}
```
[](https://i.stack.imgur.com/Z2Smt.png)
Upvotes: 1 <issue_comment>username_2: The sloped edges on the header of the page you noted, can be made with CSS3. Check out [this blog](https://kilianvalkhof.com/2017/design/sloped-edges-with-consistent-angle-in-css/) for an example.
Upvotes: 0
|
2018/03/17
| 412 | 1,400 |
<issue_start>username_0: I want read variable value from another jar
*Main.jar*
```
public static int version = 2;
```
I already did add libraries navigate to Main.jar (lib/Main.jar)
then I do this from Loader.jar
```
int version = dummy.Main.version;
```
Do replace with a new one if there are update
*Loader.jar*
```
URL url = new URL("http://127.0.0.1/cn/Main.jar");
try (InputStream in = url.openStream()) {
Files.copy(in, Paths.get("lib/Main.jar"), StandardCopyOption.REPLACE_EXISTING);
}
catch (HeadlessException | IOException | NumberFormatException e) {
//do exception
}
}
```
But the problem is i can not replace file because the file is being used, since Main.jar is used by Loader.jar
How the solution to replace the file being used ?<issue_comment>username_1: You could transform each element of the content by CSS. For the website you gave as example this rule would have to be applied:
```
.fw-body .content > * {
transform: rotate(-2deg);
}
```
[](https://i.stack.imgur.com/Z2Smt.png)
Upvotes: 1 <issue_comment>username_2: The sloped edges on the header of the page you noted, can be made with CSS3. Check out [this blog](https://kilianvalkhof.com/2017/design/sloped-edges-with-consistent-angle-in-css/) for an example.
Upvotes: 0
|
2018/03/17
| 272 | 957 |
<issue_start>username_0: ```
public class Fruit {
public String name;
public double juiceAmount;
public Color color;
}
```
---
```
public class Orange extends Fruit {
public String name = "Orange";
public double juiceAmount = 0.3 * 250;
public Color color = Color.ORANGE;
public void setN(){
super.name = this.name;
}
}
```
I want to call setN method automatically after initializing object of Orange class!! tnx for help and sorry for bad English :))<issue_comment>username_1: You could just put it in a default constructor like this:
```
public Orange() {
this.setN();
}
```
Upvotes: 1 <issue_comment>username_2: ```
public class Orange extends Fruit {
public String name = "Orange";
public double juiceAmount = 0.3 * 250;
public Color color = Color.ORANGE;
public Orange() {
this.setN();
}
public void setN(){
super.name = this.name;
}
}
```
Upvotes: 0
|
2018/03/17
| 280 | 912 |
<issue_start>username_0: I want a JavaScript object which should have multiple key values pairs. However, I am unable to add.
On clicking a function, I am getting multiple key value pairs as
```
{id:"1" ,desc: "first"} , {id:"2", desc:"two"} , {id:"3" , desc:"three"} ...
```
How can I add them to the object so that the final object should look like this:
```
prdObj= ({id:"1" ,desc: "first"} , {id:"2", desc:"two"} , {id:"3" , desc:"three"});
```<issue_comment>username_1: You could just put it in a default constructor like this:
```
public Orange() {
this.setN();
}
```
Upvotes: 1 <issue_comment>username_2: ```
public class Orange extends Fruit {
public String name = "Orange";
public double juiceAmount = 0.3 * 250;
public Color color = Color.ORANGE;
public Orange() {
this.setN();
}
public void setN(){
super.name = this.name;
}
}
```
Upvotes: 0
|
2018/03/17
| 637 | 2,188 |
<issue_start>username_0: I am having an issue running the schema.sql upon running the program.
In my pom.xml, I already have the mysql config:
```
mysql
mysql-connector-java
runtime
```
I only have one class
```
@SpringBootApplication
public class Application {...}
```
Under src/resources, I have schema.sql containing:
```
DROP TABLE IF EXISTS test_table;
CREATE TABLE test_table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
...
);
```
Under src/resources, I have application.yml containing:
```
spring.datasource.driverClassName: "com.mysql.jdbc.Driver"
spring.datasource.url: "jdbc:mysql://localhost:3306/sample?useSSL=false"
spring.datasource.username: "****"
spring.datasource.password: "****"
```
I have confirmed that I am able to connect to the database "sample" upon starting the application, however, it's not creating the table. Please advise.<issue_comment>username_1: That's because Spring Boot has check in `DataSourceInitializer's initSchema()` method.
[](https://i.stack.imgur.com/LOjSo.jpg)
It will execute scripts only if your database is of type `H2,DERBY,HSQL`
However, you can override this behaviour by using following setting in application.properties
```
spring.datasource.initialization-mode=always
```
[DataSourceInitializer.java](https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializer.java)
[EmbeddedDatabaseConnection.java](https://github.com/spring-projects/spring-boot/blob/306c79f0de3166288a9bdc570776b7743b58b5c7/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java)
Upvotes: 3 <issue_comment>username_2: In my case (Spring Boot 2.0.0+) it worked as expected only when property setting `spring.datasource.initialization-mode=always` was combined with `spring.jpa.hibernate.ddl-auto=none`.
Upvotes: 3 <issue_comment>username_3: From spring boot version 2.7 onward, this will work:
```
spring.sql.init.mode=always
spring.jpa.hibernate.ddl-auto=update
```
Upvotes: 1
|
2018/03/17
| 1,448 | 5,137 |
<issue_start>username_0: When I click the button I get the following error:
***index.html:12 Uncaught ReferenceError: greet is not defined
at HTMLButtonElement.onclick (index.html:12)***
It seems as if the javascript code generated by webpack or ts-loader is not correct. Any ideas?
**this is my index.ts**
```js
function greet(){
let p:HTMLElement=document.getElementById("p1")
p.innerHTML="hello"
}
```
**this is my bundle.js**
```js
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/index.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./src/index.ts":
/*!**********************!*\
!*** ./src/index.ts ***!
\**********************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("function greet() {\r\n var p = document.getElementById(\"p1\");\r\n p.innerHTML = \"hello\";\r\n}\r\n\n\n//# sourceURL=webpack:///./src/index.ts?");
/***/ })
/******/ });
```
**this is my index.html**
```html
Document
Greet
```
**this is my tsconfig.json**
```js
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true
}
}
```
**this is my webpack.config.js**
```js
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode:"development"
};
```<issue_comment>username_1: you have to expose the function as a library. Extend the output object in webpack.config.js:
```
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
libraryTarget: 'var',
library: 'MyLib'
}
```
Then put the function inside a static class named as in 'library' above and export it.
```
export static class MyLib {
public static greet() {
let p: HTMLElement = document.getElementById("p1")
p.innerHTML = "hello"
}
}
```
last step is to change the event in html code:
```
Greet
```
Upvotes: 1 <issue_comment>username_2: You could do something along the lines of @username_1's answer . But the easiest is to do is,
```
function greet() {
let p: HTMLElement | null = document.getElementById("p1")
if(p)
p.innerHTML = "hello"
}
(window).greet = greet;
```
Now your function is in global scope.
Upvotes: 0
|
2018/03/17
| 1,428 | 5,030 |
<issue_start>username_0: There are situations where you want a factory function to create some data, but for whatever reasons the data you return *must* contain references. This does not seem possible because you cannot return references from functions.
Let's look at the following example code:
```
// Important: traits are of unknown size, and so must be passed around
// as a reference
trait Shape {
fn area(&self) -> f32;
}
// As seen here.
struct ShapeCollection<'a> {
shapes: Vec<&'a Shape>
}
// This function needs to return a ShapeCollection, but since the
// data structure requires references to work, it seems impossible!
fn make_shapes<'a>(needRectangle: bool, multiplier: f32) -> ShapeCollection<'a> {
let rect = Rectangle {
width: 42.0 * multiplier,
height: 24.0 * multiplier
};
let circle = Circle {
radius: 42.0 * multiplier
};
match needRectangle {
true => ShapeCollection {
shapes: vec![▭, &circle]
},
false => ShapeCollection {
shapes: vec![&circle]
},
}
}
// ^ This function won't compile because rect and circle do not
// life long enough, and the compiler dies at this point
// Impls if you're interested / want to compile, but not that important
struct Rectangle {
width: f32,
height: f32
}
impl Shape for Rectangle {
fn area(&self) -> f32 {
self.width * self.height
}
}
struct Circle {
radius: f32
}
impl Shape for Circle {
fn area(&self) -> f32 {
(std::f32::consts::PI * self.radius).powf(2f32)
}
}
```
This is a simplified example built out of a more complex code I am writing. The gist of the issue is two conflating requirements:
* I need polymorphism. Since I'm using traits for this, and traits are not sized, the `Vec` must contain references not values
* I need a factory function. Since I want to generate this list of objects from multiple parts of my code but with different parameters, it makes sense to make a function that encapsulates that, instead of copying and pasting logic around
**How can I solve both of these requirements in Rust?**
The two choices seems to be:
* Do something else to achieve polymorphism, something that is allowed to be passed around as a value
* De-duplicate multiple code blocks in some way that *isn't* creating a parameterised function<issue_comment>username_1: One possibility seems to be to use enums instead of traits for polymorphism.
For this example that would be:
```
enum Shape2 {
Rectangle { width: f32, height: f32 },
Circle { radius: f32 }
}
fn area(shape: Shape2) -> f32 {
match shape {
Shape2::Rectangle {width, height} => width * height,
Shape2::Circle {radius} => (std::f32::consts::PI * radius).powf(2f32)
}
}
struct Shape2Collection {
shapes: Vec
}
fn make\_shapes2(needRectangle: bool, multiplier: f32) -> Shape2Collection {
let rect = Shape2::Rectangle {
width: 42.0 \* multiplier,
height: 24.0 \* multiplier
};
let circle = Shape2::Circle {
radius: 42.0 \* multiplier
};
match needRectangle {
true => Shape2Collection {
shapes: vec![rect, circle]
},
false => Shape2Collection {
shapes: vec![circle]
},
}
}
```
The downside of this is that your implementations aren't methods anymore, but are functions, and that your implementations are smushed together in the same function.
Upvotes: 0 <issue_comment>username_2: You simply [cannot return a reference to a variable created in a function](https://stackoverflow.com/q/32682876/155423).
>
> Important: traits are of unknown size, and so must be passed around as a reference
>
>
>
This isn't strictly true. They must be passed around via some kind of indirection, but a reference (`&`) isn't the only kind of indirection that a *trait object* can use. There's also boxed trait objects:
```
struct ShapeCollection {
shapes: Vec>,
}
fn make\_shapes(need\_rectangle: bool, multiplier: f32) -> ShapeCollection {
let rect = Rectangle {
width: 42.0 \* multiplier,
height: 24.0 \* multiplier,
};
let circle = Circle {
radius: 42.0 \* multiplier,
};
match need\_rectangle {
true => ShapeCollection {
shapes: vec![Box::new(rect), Box::new(circle)],
},
false => ShapeCollection {
shapes: vec![Box::new(circle)],
},
}
}
```
In 99.9% of the cases, a function signature with a lifetime that's only in the return position can never work (or doesn't do what you want) and should *always* give you pause:
```
fn make_shapes<'a>(need_rectangle: bool, multiplier: f32) -> ShapeCollection<'a>
```
Note that the Rust style is `snake_case`, so I've renamed `need_rectangle`.
See also:
* [What makes something a "trait object"?](https://stackoverflow.com/q/27567849/155423)
* [Is there any way to return a reference to a variable created in a function?](https://stackoverflow.com/q/32682876/155423)
* [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/q/32300132/155423)
Upvotes: 3 [selected_answer]
|
2018/03/17
| 753 | 3,136 |
<issue_start>username_0: We are in the processing of migrating from apache hbase to bigquery.
Currently we have end to end tests (using cucumbers) that work with a docker container running hbase.
There don't seem to be any bigquery docker containers or emulators (<https://cloud.google.com/sdk/gcloud/reference/beta/emulators/>)
How would we be able to create end to end tests for an application working with bigquery?<issue_comment>username_1: Currently there is not any kind of BigQuery local emulator or anything similar to that. As pointed out by the link you shared about [available GCP emulators](https://cloud.google.com/sdk/gcloud/reference/beta/emulators/), there are some other products that have such a feature, but probably the reason why BigQuery does not have one is that its true potential is only seen when working in its real infrastructure, plus the fact that the costs of working with BigQuery can be relatively low depending on the usage you make of it, plus you have a Free Tier to start working with.
Let me summarize some info about BigQuery pricing that can be useful for you:
* BigQuery storage and operation costs are summarized in the [pricing documentation](https://cloud.google.com/bigquery/pricing#pricing_summary).
* BigQuery offers some operations that are [free of charge](https://cloud.google.com/bigquery/pricing#free).
* There's a [Storage free tier](https://cloud.google.com/bigquery/pricing#free-tier-storage) with 10GB of free storage. It may not be a lot, given that BQ is designed to work with enormous amounts of data, but it can be a good starting point to do some tests.
* There's also an [Operations free tier](https://cloud.google.com/bigquery/pricing#free-tier), where the first TeraByte of processed data (per month) is free of charge.
* You can set up alerts in order to monitor usage with [Stackdriver](https://cloud.google.com/stackdriver/), using the [available metrics](https://cloud.google.com/bigquery/docs/monitoring#metrics).
In any case, if you still think that working with BigQuery directly is not the best option for you, can always forward your requests to the Engineering team by creating a Feature Request in the [Public Issue Tracker](https://cloud.google.com/support/docs/issue-trackers) for BigQuery, although it will be in hands of the engineering team whether to decide if (and when) to implement such a feature, even more considering the complexity of BigQuery and that its performance is optimized for working in its current architecture.
Upvotes: 4 [selected_answer]<issue_comment>username_2: This is an old post but if you can use Python and you plan to test your SQL and assert your result based on input, I would suggest [bq-test-kit](https://github.com/tiboun/python-bq-test-kit). This framework allows you to interact with BigQuery in Python and make tests reliables.
You have 3 ways to inject data into it :
* Create datasets and tables with an ability to isolate their name and therefore have your own namespace
* Rely on temp tables, where data is inserted with data literals
* data literal merged into your query
Hope that this helps.
Upvotes: 3
|
2018/03/17
| 679 | 2,344 |
<issue_start>username_0: How do I send a notification email after a form has been submitted?
I have a Google Form, I open it and I go to menu *More->Script Editor* and add a script:
```
function OnSubmit(e) {
MailApp.sendEmail ("<EMAIL>", "Form Submited: Foo feedback " + Date.now(), "Form Submited: Foo feedback");
}
```
I save the script and test it works by pressing the run button. The email gets delivered to *<EMAIL>*.
Then I fill in the Google Form, but the email does not arrive in <EMAIL> mailbox.
P.S.
I do not want to use "Email Notifications for Forms" plugin because it requests access to to many privileges. I do not want to use "Form Notifications" because for some reason it does not work for me (the emails do not get delivered).<issue_comment>username_1: To send an email on submit you need to save this script, test it in the script editor (and accept when you see the permissions popup), and then submit a form.
The script looks for submit triggers, if it finds none it adds a new one that sends the email.
```
function respondToFormSubmit() {
MailApp.sendEmail ("<EMAIL>", "Form Submited: Foo feedback " + Date.now(), "Form Submited: Foo feedback");
}
var form = FormApp.getActiveForm();
var triggers = ScriptApp.getUserTriggers(form);
var existingTrigger = null;
for (var i = 0; i < triggers.length; i++) {
if (triggers[i].getEventType() == ScriptApp.EventType.ON_FORM_SUBMIT) {
existingTrigger = triggers[i];
break;
}
}
if (!existingTrigger) {
var form = FormApp.getActiveForm();
var trigger = ScriptApp.newTrigger('respondToFormSubmit')
.forForm(form)
.onFormSubmit()
.create();
}
```
Upvotes: 2 <issue_comment>username_2: [](https://i.stack.imgur.com/DUT03.png)
The easier way, now, is to use the "Notification rules..." item under "Tools".
[](https://i.stack.imgur.com/1WIB3.png)
Upvotes: 0 <issue_comment>username_3: Finally found it, well hidden under
* Edit form mode
* `Responses` tab
* `...` menu button
* `Get email notifications for new responses`.
[](https://i.stack.imgur.com/eMVM4.png)
Upvotes: 4 [selected_answer]
|
2018/03/17
| 1,463 | 4,191 |
<issue_start>username_0: I have a list of lists containing:
```
animal = [[1, 'Crocodile','Lion'],[2, 'Eagle','Sparrow'],[3, 'Hippo','Platypus','Deer']]
```
and I want to join the string elements in each list inside the animal table so that it becomes a single string:
```
animal = [[1, 'Crocodile, Lion'],[2, 'Eagle, Sparrow'],[3,'Hippo, Platypus, Deer']]
```
I tried using a for loop to join them:
```
for i in range(len(animal)):
''.join(animal[1:]) #string at index 1 and so on
print(animal)
```
I'm getting a type error saying "TypeError: sequence item 0: expected str instance, list found".<issue_comment>username_1: `animal` could be called `table`, and should indicate that it's not just a single animal. It also shouldn't be called `animals`, because it's not just a list of animals.
Thanks to [unpacking](https://www.python.org/dev/peps/pep-3132/), you can split your sub-lists directly into an integer and a list of animals:
```
>>> table = [[1, 'Crocodile','Lion'],[2, 'Eagle','Sparrow'],[3, 'Hippo','Platypus','Deer']]
>>> [[i, ', '.join(animals)] for (i, *animals) in table]
[[1, 'Crocodile, Lion'], [2, 'Eagle, Sparrow'], [3, 'Hippo, Platypus, Deer']]
```
Upvotes: 1 <issue_comment>username_2: ```
>>> [[a[0], ','.join(a[1:])] for a in animal]
>>> [[1, 'Crocodile,Lion'], [2, 'Eagle,Sparrow'], [3, 'Hippo,Platypus,Deer']]
```
Upvotes: 1 <issue_comment>username_3: There are two problems with your code:
`animal[1:]` is the following list
```
>>> animal[1:]
[[2, 'Eagle', 'Sparrow'], [3, 'Hippo', 'Platypus', 'Deer']]
```
what do you expect to happen if you `join` it in every iteration of your loop?
The second problem is that you do not assign the return value of `join` to anything, so even if the operation would not throw an error, you would lose the result.
Here's a solution with [extended iterable unpacking](https://www.python.org/dev/peps/pep-3132/):
```
>>> animal = [[1, 'Crocodile','Lion'],[2, 'Eagle','Sparrow'],[3,'Hippo','Platypus','Deer']]
>>> [[head, ', '.join(tail)] for head, *tail in animal]
[[1, 'Crocodile, Lion'], [2, 'Eagle, Sparrow'], [3, 'Hippo, Platypus, Deer']]
```
Here's one without:
```
>>> [[sub[0], ', '.join(sub[1:])] for sub in animal]
[[1, 'Crocodile, Lion'], [2, 'Eagle, Sparrow'], [3, 'Hippo, Platypus, Deer']]
```
Upvotes: 0 <issue_comment>username_4: Just a small change needed, you just forgot the index i in your loop:
```
animal = [[1, 'Crocodile','Lion'],[2, 'Eagle','Sparrow'],[3, 'Hippo','Platypus','Deer']]
merged_animal = []
for element in animal:
merged_animal.append([element[0], ", ".join(element[1:])])
print(merged_animal)
```
But if you know list-comprehensions, better use them as shown in many answers.
Upvotes: 2 [selected_answer]<issue_comment>username_5: `animal` is a list of lists so you need an extra index. You see this by adding
```
print(animal[i])
print(animal[i][0])
print(animal[i][1])
```
etc in the loop
```
animal = [[1, 'Crocodile','Lion'],[2, 'Eagle','Sparrow'],[3, 'Hippo','Platypus','Deer']]
for i in range(len(animal)):
print(animal[i][1:])
animal[i][1] = ' '.join(animal[i][1:]) #string at index 1 and so on
del animal[i][2:]
print(animal)
```
Upvotes: 0 <issue_comment>username_6: Firstly, the type error is coming because you are applying `join()` on the list animal not on the sublists of list animal.
You should also keep in mind that join does not edit the original list, it just returns the new string.
Hence if you keep the above two things in mind your new code will look something like this
```
for i in range(len(animal)):
animal[i] = [animal[i][0], ', '.join(animal[i][1:])] #string at index 1 and so on
print(animal)
```
the above code replaces each sublist with another sublist containing the sublist number and a string formed by joining the remaining part of original sublist with a `', '` *(note your mistake here, you were joining with an empty character but your requirement is a comma and a space).*
Upvotes: 0 <issue_comment>username_7: ```
l1=[[1, 'Crocodile','Lion'],[2, 'Eagle','Sparrow'],[3, 'Hippo','Platypus','Deer']]
l2 = list(map(lambda x: [x[0],"{}, {}".format(x[1],x[2])],l1))
print(l2)
```
Upvotes: 0
|
2018/03/17
| 615 | 2,133 |
<issue_start>username_0: I'm constructing text, and some pieces of the text should contain a hyperlink. However, these hyperlinks do not redirect to a webpage but should open a page in the UWP app (the currently running UWP app, not a new instance of it or a different app).
A `HyperlinkButton` can only open URL's that lead to an external browser, it can't open a page inside the app.
Using an `InlineUIContainer` doesn't work, I get
>
> Exception thrown: 'System.ArgumentException' in mscorlib.ni.dll
> Additional information: Value does not fall within the expected range.
>
>
>
With this code
```
List ic = new List();
InlineUIContainer container = new InlineUIContainer();
TextBlock tbClickable = new TextBlock();
tbClickable.Foreground = new SolidColorBrush(Colors.Red);
tbClickable.Text = label?.name;
tbClickable.Tag = label?.id;
tbClickable.Tapped += TbArtist\_Tapped;
container.Child = tbClickable;
ic.Add(container);
```
When I use
```
foreach (var item in ic)
{
dTb.Inlines.Add(item);
}
```
Where `tbCurrent` is the `TextBlock`.
Any other ways to get a clickable link as an Inline element?
Best case scenario I can attach a `Tapped`/`Click` event handler.
But opening the page via a URI method or so is also good.<issue_comment>username_1: There is no reason you could not use a `HyperlinkButton` for this. Quick example:
```
```
And the `Click` handler:
```
private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(MainPage));
}
```
Upvotes: 0 <issue_comment>username_2: I changed to a RichTextBlock and using Blocks I could add a clickable TextBlock.
This works in UWP.
```
List ic = new List();
Paragraph para = new Paragraph();
InlineUIContainer iuic = new InlineUIContainer();
TextBlock hpb = new TextBlock();
hpb.Text = "link text";
hpb.Tag = "some tag to pass on to the click handler";
hpb.Tapped += ClickHandler;
hpb.TextDecorations = TextDecorations.Underline;
hpb.Foreground = new SolidColorBrush((Windows.UI.Color)page.Resources["SystemAccentColor"]);
iuic.Child = hpb;
para.Inlines.Add(iuic);
ic.Add(para);
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 379 | 1,253 |
<issue_start>username_0: I have an app configured
```
config :my_app,
ecto_repos: [MyApp.Repo, MyApp.LegacyRepo]
```
MyApp.Repo's migrations are managed by Ecto.
MyApp.LegacyRepo migrations are handled by Rails and error out on `mix ecto.migrate`
Is there a way to specify "I have two repos, but please ignore the second for migrations"?<issue_comment>username_1: You can pass a repo into mix ecto.migrate like this
```
mix ecto.migrate -r MyApp.Repo
```
You can update test/test\_helper.ex in a phoenix app to only run one repo migrations like this
```
Mix.Task.run "ecto.migrate", ["-r", "MyApp.Repo", "--quiet"]
```
Upvotes: 1 <issue_comment>username_2: Another option is to change your `config.exs`. Change it to...
```
config :my_app, ecto_repos: [MyApp.Repo]
```
According to [the ecto.migrate documentation](https://hexdocs.pm/ecto/Mix.Tasks.Ecto.Migrate.html)...
>
> The repositories to migrate are the ones specified under the
> :ecto\_repos option in the current app configuration. However, if the
> -r option is given, it replaces the :ecto\_repos config.
>
>
>
Not having a MyApp.LegacyRepo in ecto\_repos doesn't prevent reads or writes or anything else you'd expect. It just configures the migration task.
Upvotes: 2
|
2018/03/17
| 398 | 1,015 |
<issue_start>username_0: I have a list that looks like:
```
[['a', 'b', 'null', 'c'], ['d', 'e', '5', 'f'], ['g' ,'h', 'null' ,'I'] ]
```
I want to uppercase all strings, but when I try:
```
x = 0
for row in range(1, sheet.nrows):
listx.append(sheet.cell(row, x))
[x.upper() for x in x in listx]
x += 1
```
I got:
```
TypeError: 'bool' object is not iterable
```
How can I make a statement for it?<issue_comment>username_1: This list comprehension does it, and retains your list of lists structure:
```
listx = [['a', 'b', 'null', 'c'], ['d', 'e', '5', 'f'], ['g' ,'h', 'null' ,'I'] ]
[[x.upper() for x in sublist] for sublist in listx]
```
returns:
```
[['A', 'B', 'NULL', 'C'], ['D', 'E', '5', 'F'], ['G', 'H', 'NULL', 'I']]
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: is this what you're looking for:
```
l = [['a', 'b', 'null', 'c'], ['d', 'e', '5', 'f'], ['g' ,'h', 'null' ,'I']]
new_list = []
for row in l:
new_list.append([x.upper() for x in row])
```
Upvotes: 1
|
2018/03/17
| 462 | 1,249 |
<issue_start>username_0: So this code takes an input from the user and displays it stripped character by character as shown in the sample run down below. however. there is syntax as well as logical errors in this code which I tried to solve for days and it didn't work with me:
```
#include
using namespace std;
int main()
{
char name[20];
char\* ptr1,\*ptr2;
cout << "Input a name -> ";
cin >> name;
cout << "Output : ";
for (ptr1 = &name ptr1 != '0'; ptr1++) {
for (ptr2 = &ptr1 ptr2 != '0'; ptr2++) {
cout << \*ptr2;
cout << ' ';
}
}
}
```
sample run:
>
> input a name -> John
>
>
>
output:
>
> John ohn hn n
>
>
><issue_comment>username_1: This list comprehension does it, and retains your list of lists structure:
```
listx = [['a', 'b', 'null', 'c'], ['d', 'e', '5', 'f'], ['g' ,'h', 'null' ,'I'] ]
[[x.upper() for x in sublist] for sublist in listx]
```
returns:
```
[['A', 'B', 'NULL', 'C'], ['D', 'E', '5', 'F'], ['G', 'H', 'NULL', 'I']]
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: is this what you're looking for:
```
l = [['a', 'b', 'null', 'c'], ['d', 'e', '5', 'f'], ['g' ,'h', 'null' ,'I']]
new_list = []
for row in l:
new_list.append([x.upper() for x in row])
```
Upvotes: 1
|
2018/03/17
| 273 | 894 |
<issue_start>username_0: Im trying a simple request to get data from a webserver, but running into an error on the console.
```
fetch('http://tcokchallenge.com/admin_cp/test2.json', {mode: 'no-cors'})
.then(function(response) {
return response.json();
})
.then(function(text) {
console.log('Request successful');
})
.catch(function(error) {
console.log('Request failed', error)
});
```
it returns
```
Request failed SyntaxError: Unexpected end of input
```
What gives?<issue_comment>username_1: If you request the data manually:
```
curl http://tcokchallenge.com/admin_cp/test2.json
```
you see that the output is:
```
{
"hello": "world"
```
so the json is invalid, and thus `response.json()` fails
Upvotes: 1 <issue_comment>username_2: The JSON file is
```
{
"hello": "world"
}%
```
Remove that last character `%` from your JSON.
Upvotes: 0
|
2018/03/17
| 815 | 2,639 |
<issue_start>username_0: I'm writing a LLVM parser to analyse whether a program is adhering to a certain programming paradigm. To that I need to analyse each block of the IR and check certain instructions. When I created the .ll file, I don't see the label names but an address:
```
; :4 ; preds = %0
%5 = load i32\* %c, align 4
%6 = add nsw i32 %5, 10
store i32 %6, i32\* %c, align 4
br label %10
; :7 ; preds = %0
%8 = load i32\* %c, align 4
%9 = add nsw i32 %8, 15
store i32 %9, i32\* %c, align 4
br label %10
; :10 ; preds = %7, %4
%11 = load i32\* %1
ret i32 %11
```
What I need is to get these "labels" into a list. I have also seen that some .ll files has following format:
```
if.then: ; preds = %entry
%5 = load i32* %c, align 4
%6 = add nsw i32 %5, 10
store i32 %6, i32* %c, align 4
br label %10
if.else: ; preds = %entry
%8 = load i32* %c, align 4
%9 = add nsw i32 %8, 15
store i32 %9, i32* %c, align 4
br label %10
if.end: ; preds = %if.else,
%11 = load i32* %1
ret i32 %11
```
With the 2nd format, I can use the `getName()` to get the name of the block: i.e: 'if.then', 'if.else' etc.
But with the 1st format, it's impossible as it doesn't have a name. But I tested with `printAsOperand(errs(), true)` from which I can print the addresses like: '%4, %7 %10'. What my question is, how to add these addresses (or operands) into a stings list? or obtain these values and assign to a certain variable.<issue_comment>username_1: Instruction / basic block names is a debugging feature that simplifies the development of IR-level passes, but no guarantees are made towards them. E.g. they could be simply stripped off, they could be misleading, etc. You should not rely on them for anything meaningful (and in general they may not have any connection to the original source code). Normally the names are no generated in Release builds of LLVM. You need to build everything in Debug (or Release+Assertions) mode.
Upvotes: 1 <issue_comment>username_2: Here's the way to do it;
`raw_ostream` should be used in `printAsOperand()` method to get the required address into a variable:
following is the method I used for the purpose:
```
#include "llvm/Support/raw_ostream.h"
std::string get_block_reference(BasicBlock *BB){
std::string block_address;
raw_string_ostream string_stream(block_address);
BB->printAsOperand(string_stream, false);
return string_stream.str();
}
```
Upvotes: 3 [selected_answer]
|
2018/03/17
| 760 | 2,292 |
<issue_start>username_0: Hello everyone i have a problem with my code and i'm not sure how to do this , i need to write code that draw this in console:
[Draw '\*' in every even number](https://i.stack.imgur.com/Ox4BL.png)
For that i need to use nested loops.
So far i have only this:
```
var n = 5;
var stars = '';
for (var i = 1; i <= n; i++) {
var starsline = '';
for (var j = 1; j <= n; j++) {
console.log(i + j);
}
if ( i % 2 === 0){
starsline += '2';
} else {
starsline += '1'
}
stars += starsline;
}
console.log(stars);
```
This numbers 2 and 1 are only to check if the number is even or odd.<issue_comment>username_1: Try this:
```
var n = 5;
var stars = '';
for (var i = 1; i <= n; i++)
{
var starsline = '';//<-- reset the value of line
if ( i % 2 === 0)//<--this identifies which line will the stars be created
{
starsline += '* * *';//<--creating the stars on each line
}
else
{
starsline += ' * * ';//<--creating the stars on each line
}
stars += starsline+'\n';//<-- '\n' add line breaks for each lines
}
console.log(stars);//<-- print the stars
```
Upvotes: 0 <issue_comment>username_2: Just a few things:
1) you got some weird bracket here:
```
/*}*/ if ( i % 2 === 0){
```
which causes a syntax error later on.
2) you actually log the right thing:
```
console.log(i + j)
```
but you dont use it. Just put that into your condition:
```
if((i + j) % 2 === 0)
```
and you are done :)
---
```
let size = 5, stars = "";
for (var row = 1; row <= size; row++) {
var starsline = "";
for (var col = 1; col <= size; col++){
if ((row + col) % 2 === 0){
starsline += '*';
} else {
starsline += ' ';
}
stars += starsline + "\n";
}
console.log(stars);
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: I think what you tried to do is something like this:
```
var n = 5;
var stars = '';
for (var i = 1; i <= n; i++) {
var starsline = '';
for (var j = 1; j <= n; j++){
if ( (i + j) % 2 === 0){
// used three spaces for consistency in the drawing
starsline += ' ';
} else {
starsline += ' * '
}
}
stars += starsline + '\n';
}
console.log(stars);
```
Upvotes: 0
|
2018/03/17
| 2,090 | 7,031 |
<issue_start>username_0: I'm having problems, Excel is not updating rows referring to other sheets in same workbook when ordering rows alphabetically.
I have a userform in which there's a button `insertCM` with this code:
```
Private Sub insertButton_Click()
ActiveCell.EntireRow.Select
Selection.Insert Shift:=xltoDown
Range("A9:AK9").Copy
Range("A8:AK8").Select
Selection.PasteSpecial Paste:=xlPasteFormulas
Selection.PasteSpecial Paste:=xlPasteFormats
Range("C10").Copy
Range("C8:C9").Select
Selection.PasteSpecial Paste:=xlPasteFormulas
Range("H9:AK9").Copy
Range("H8:AK8").Select
Selection.PasteSpecial Paste:=xlPasteAll
nomCM = Empty
CXinitial = Empty
resteCX = Empty
CCselect = Empty
C4initial = Empty
resteC4 = Empty
compteurCT = Empty
Range("A8").Activate
ActiveCell.RowHeight = 18.6
For i = 2 To ThisWorkbook.Sheets.Count
With Sheets(i).Select
emptyRow = Range("A9").End(xlDown).Offset(0, 2).Row
Range("A9:AL" & emptyRow).Sort _
Key1:=Range("A9"), Order1:=xlAscending
Set SearchRange = Range("A8", Range("A200").End(xlUp))
Set FindRow = SearchRange.Find(nomCM, LookIn:=xlValues, LookAt:=xlWhole)
Range("A" & FindRow.Row).Select
ActiveCell.EntireRow.Activate
End With
Next i
Sheet2.Select
End
End Sub
```
The userform is used for inserting new clients in several sheets at the same time. `Textbox` inserts Name, Cost Center, etc., in a blank row and `insertButton` inserts a new row leaving data inserted in `row 8` to go to `row 9`. After that the code puts all rows alphabetical order so the new client now in `row 9` goes to the new one, and cells containing formulas change row numbers.
However some of the sheets have cells containing references to other sheets' cells in the same row. So imagine:
I insert client name `"LORUM" "Cost Center 4"` and it puts him in `row 9` so formula is:
```
=$C9-COUNTIF($E9:$P9;"CT")+'Sheet5'!$D9
```
...but when it changes his row to the final one, formula row is:
```
=$C18-COUNTIF($E18:$P18;"CT")+'Sheet5'!$D9
```
It does not change row when referring to other sheets.
Any ideas?<issue_comment>username_1: as per my test, sorting actually doesn't change other sheet *direct* references
so you may want to use OFFSET to keep referencing the actual current row index
instead of:
```
=$C9-COUNTIF($E9:$P9;"CT")+'Sheet5'!$D9
```
use
```
=$C9-COUNTIF($E9:$P9;"CT")+ OFFSET('Sheet5'!$D1,ROW()-1,0)
```
Upvotes: 0 <issue_comment>username_2: It's looks like you've made a good effort, but there are still **numerous** problems with your code (beside the one line), and I can guarantee that a combination of these issues are preventing your intended outcome.
I can't fix it completely because there are so many bugs that I'm not clear on what you're trying to do, but hopefully this will get you started on the right track...
* `xlToDown` is not a valid reference. You probably mean `xlDown`
* you have a number of undeclared variables and objects, like: `i, emptyRow, SearchRange, FindRow, nomCM`
* you have things (objects?) "set to nothing" that aren't declared **or** used anywhere: `CXinitial, resteCX, CCselect, C4initial, resteC4, compteurCT`
* your `Find` statement is looking for `nomCM` which is **empty** (and never set), so the `Find` statement will never find anything.
* **You should put `Option Explicit` at the top of every module** (especially when learning or troubleshooting). This will prevent issues like the ones above by "forcing" you to properly declare & handle all of your variables, objects, properties, etc.
* Near the end, you refer to `Sheet2.Select` as if `Sheet2` is a *declared object*, instead of using `Sheets("Sheet2").Select`. I'm not sure why you're selecting the sheet at the very end anyhow.
* You have an `With..End` statement that is doing absolutely nothing since you don't reference it with a `.` dot anywhere: `With Sheets(i).Select` .. `End With`, and also `Select` isn't used like that.
* A mystery `End` near the end for some reason.
Also, you're unnecessarily doubling up commands like:
```
ActiveCell.EntireRow.Select
Selection.Insert Shift:=xlDown
```
..instead of:
```
ActiveCell.EntireRow.Insert Shift:=xlDown
```
and another example, *all* this:
```
Range("A9:AK9").Copy
Range("A8:AK8").Select
Selection.PasteSpecial Paste:=xlPasteFormulas
Selection.PasteSpecial Paste:=xlPasteFormats
Range("C10").Copy
Range("C8:C9").Select
Selection.PasteSpecial Paste:=xlPasteFormulas
Range("H9:AK9").Copy
Range("H8:AK8").Select
Selection.PasteSpecial Paste:=xlPasteAll
```
...instead of:
```
Range("A9:AK9").Copy
Range("A8:AK8").PasteSpecial xlPasteValuesAndNumberFormats
Range("C10").Copy
Range("C8:C9").PasteSpecial Paste:=xlPasteFormulas
Range("H9:AK9").Copy Range("H8:AK8")
```
All of this would be more clear by *Googling* the documentation for each command you're unfamiliar with, such as:
* [Range.Copy Method (Excel)](https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-copy-method-excel)
* [Range.PasteSpecial Method (Excel)](https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-pastespecial-method-excel)
* [XlPasteType Enumeration (Excel)](https://msdn.microsoft.com/en-us/vba/excel-vba/articles/xlpastetype-enumeration-excel)
All the `ActiveCell` and `ThisWorkbook` references are troublesome but again, I'm not sure what to do with them since I don't know your workbook.
**Indentation** (and general organization) are very important as well. It may not change the way that the code runs, but it will help you (and others) track down existing & potential issues more easily.
---
Here is your code cleaned up as best as I could:
```
Option Explicit 'this line goes at the very top of the module
Private Sub insertButton_Click()
Dim i As Long, emptyRow As Long, SearchRange As Range, FindRow As Range, nomCM
nomCM = Empty
ActiveCell.EntireRow.Insert Shift:=xlDown
Range("A9:AK9").Copy
Range("A8:AK8").PasteSpecial xlPasteValuesAndNumberFormats
Range("C10").Copy
Range("C8:C9").PasteSpecial Paste:=xlPasteFormulas
Range("H9:AK9").Copy Range("H8:AK8")
Range("A8").RowHeight = 18.6
For i = 2 To ThisWorkbook.Sheets.Count
With Sheets(i)
emptyRow = .Range("A9").End(xlDown).Offset(0, 2).Row
.Range("A9:AL" & emptyRow).Sort Key1:=.Range("A9"), Order1:=xlAscending
Set SearchRange = .Range("A8", .Range("A200").End(xlUp))
Set FindRow = SearchRange.Find(nomCM, LookIn:=xlValues, LookAt:=xlWhole)
.Range("A" & FindRow.Row).Select
ActiveCell.EntireRow.Activate
End With
Next i
Sheets("Sheet2").Select
End Sub
```
Upvotes: 1 <issue_comment>username_3: I found a solution:
```
=INDIRECT(ADDRESS(ROW();4;3;1;"Sheet5"))
```
Where `Row()` will always refer to the actual cell's row.
Hope it will help you!
Upvotes: 0
|
2018/03/17
| 713 | 2,495 |
<issue_start>username_0: I am trying to connect a facebook app but it is displaying error as "Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings."
the domain i am using is <https://app.streamlivve.com>
I tried all of solutions but nothing happen. here is my settings of FB app page
[](https://i.stack.imgur.com/HxN36.jpg)
[](https://i.stack.imgur.com/ZxXGX.jpg)
[](https://i.stack.imgur.com/sasRU.jpg)
Can you please guide me to solve this error:
[](https://i.stack.imgur.com/FY1LT.jpg)<issue_comment>username_1: Make sure you're using Facebook SDK 5.6.2. There was an important fix.
Upvotes: 0 <issue_comment>username_2: Facebook announced in Dec 2017 that in March 2018 they would change the settings for Oauth redirects:
<https://developers.facebook.com/blog/post/2017/12/18/strict-uri-matching/>
In a nutshell, you can only redirect to explicit, precise pre-determined URIs now. Which is annoying if (like me) you want to pass URI parameters back as well...
Upvotes: 3 [selected_answer]<issue_comment>username_3: Since this March (started running a couple of days ago), [strict mode is now enabled by default](https://developers.facebook.com/blog/post/2017/12/18/strict-uri-matching/). This means you now need to have the exact redirect URLs you're using marked as such in the app configuration.
You can see more [here](https://developers.facebook.com/docs/facebook-login/security#strict_mode) about what this entails and how to get on with the change.
Further, you **need** to update your dependency to version 5.6.2, as there's a bug in the previous version that wouldn't work with strict URI matching (yes, the one that is now enabled by default), so the login would break. You can see more about the fix [in the pull request that fixed it](https://github.com/facebook/php-graph-sdk/pull/913). I can confirm that updating to 5.6.2 (PHP) fixed the issue.
To update your version in PHP, it depends on which expression you have in your `composer.json`, but if you have `"facebook/graph-sdk": "^5.6"`, for example, a simple `composer update` will suffice.
Upvotes: 0
|