date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/17
| 672 | 2,366 |
<issue_start>username_0: I'm building a personal project with React and TypeScript to learn the ropes, and I'm stuck with a strange (to me) error on the following block, where I use Axios to fetch some data:
```
const fetchItem = async () => {
const response = await axios
.get("http://localhost:4000/items?id=2")
.catch(error => console.log(error));
console.log(response.data);
};
```
The error message is `Property 'data' does not exist on type 'void'` and pops up immediately on Visual Studio Code as soon as I try to access the `data` property of my `response` object.
How can I access `response.data` correctly (without having both my IDE and Webpack complaining)?
Here is the full code of my component, for reference:
```
import * as React from "react";
import { css } from "emotion";
import axios from "axios";
import { Item } from "./Item/Item";
export interface ContentProps {
view: string;
}
const fetchItem = async () => {
const response = await axios
.get("http://localhost:4000/items?id=2")
.catch(error => console.log(error));
console.log(response.data);
};
export class Content extends React.Component {
state = {
text: "test"
};
componentDidMount() {
fetchItem();
}
render() {
return (
{this.props.view === "item" ? (
) : (
)}
);
}
}
```
The error on webpack:
[](https://i.stack.imgur.com/ULek0.png)
The full error text on VSC's tooltip states: `Property 'data' does not exist on type 'void | AxiosResponse'.`.<issue_comment>username_1: Would comment, but can't yet...
The inner `catch` can return a possible `void`. If you remove that/handle it different then at least TS doesn't complain.
Upvotes: 1 <issue_comment>username_2: Your `await`, when erroring out returns `undefined`, since `console.log` in your `catch` returns `undefined`, and the return value is inferred as `void`.
Basically here you are mixing async/await sync style with promise async style of writing async code, it's better to stick to one to avoid confusion like here with good'ol `try catch`.
So it can go like this:
```
const fetchItem = async() => {
try {
const response = await axios("http://localhost:4000/items?id=2");
console.log(response.data);
} catch (error) {
console.log(error)
}
};
```
Upvotes: 5 [selected_answer]
|
2018/03/17
| 608 | 2,761 |
<issue_start>username_0: I am working on LINQ query where I need all the questions where each question may or may not have sub-question.
I am getting group by null/ exception issue as some parent question doesn't have child question. I am doing left join followed; group by parent question
```
(from question in Context.Questions.Where(question => question.ConsultationId == ConsultationId)
join questionHierarchy in Context.QuestionHierarchy on question.Id equals questionHierarchy.ParentQuestionId into qs
from childQuestion in qs.DefaultIfEmpty()
group childQuestion by question into g
select new
{
g.Key,
g
}).ToList();
```<issue_comment>username_1: found the answer
```
(from question in Context.Questions.Where(question => question.ConsultationId == ConsultationId)
join questionHierarchy in Context.QuestionHierarchy on question.Id equals questionHierarchy.ParentQuestionId into qs
from childQuestion in qs.DefaultIfEmpty()
group childQuestion by question into groupQuestions
select new
{
groupQuestions.Key,
childQuestions = groupQuestions.DefaultIfEmpty() == null? null : groupQuestions
}).ToList();
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: If you want something like "questions with their sub-questions" cnsider using [GroupJoin?](https://msdn.microsoft.com/en-us/library/bb534805(v=vs.110).aspx) instead of an inner join followed by a GroupBy
In small steps:
```
IQueryable questions = dbContext.Questions.Where(...)
IQueryable subQuestions = Context.QuestionHierarchy;
var questionsWithTheirSubQuestions = questions.GroupJoin( // GroupJoin the questions
subQuestions, // with the subQuestions
question => question.Id, // from every question take the Id
subQuestion => subQuestion.ParentQuestionId,
// from every subQuestion take the ParentQuestionId,
(question, subQuestions) => new // take the question with all matching subQuestions
{ // to make one new object:
// select only the question items you plan to use
Title = question.Title,
Priority = question.Priority,
...
// select only the subQuestions that you want (or all)
// for example only the answered sub questions:
SubQuestions = subQuestions
.Where(subQuestion.Type = QuestionType.Answered)
.Select(subQuestion => new
{
// again: select only the subQuestion properties you plan to use
Name = subQuestion.Name,
Date = subQuestion.Date,
...
})
.ToList(),
});
```
TODO: if desired, make one big statement.
Upvotes: 0
|
2018/03/17
| 522 | 2,252 |
<issue_start>username_0: I want assign the data which is retrieve from database (sqlit3) particular column for a variable and call that variable for **word tokenize**.
please help with this
I know tokenize part but I want to know how to assign the db value to a variable in python.<issue_comment>username_1: found the answer
```
(from question in Context.Questions.Where(question => question.ConsultationId == ConsultationId)
join questionHierarchy in Context.QuestionHierarchy on question.Id equals questionHierarchy.ParentQuestionId into qs
from childQuestion in qs.DefaultIfEmpty()
group childQuestion by question into groupQuestions
select new
{
groupQuestions.Key,
childQuestions = groupQuestions.DefaultIfEmpty() == null? null : groupQuestions
}).ToList();
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: If you want something like "questions with their sub-questions" cnsider using [GroupJoin?](https://msdn.microsoft.com/en-us/library/bb534805(v=vs.110).aspx) instead of an inner join followed by a GroupBy
In small steps:
```
IQueryable questions = dbContext.Questions.Where(...)
IQueryable subQuestions = Context.QuestionHierarchy;
var questionsWithTheirSubQuestions = questions.GroupJoin( // GroupJoin the questions
subQuestions, // with the subQuestions
question => question.Id, // from every question take the Id
subQuestion => subQuestion.ParentQuestionId,
// from every subQuestion take the ParentQuestionId,
(question, subQuestions) => new // take the question with all matching subQuestions
{ // to make one new object:
// select only the question items you plan to use
Title = question.Title,
Priority = question.Priority,
...
// select only the subQuestions that you want (or all)
// for example only the answered sub questions:
SubQuestions = subQuestions
.Where(subQuestion.Type = QuestionType.Answered)
.Select(subQuestion => new
{
// again: select only the subQuestion properties you plan to use
Name = subQuestion.Name,
Date = subQuestion.Date,
...
})
.ToList(),
});
```
TODO: if desired, make one big statement.
Upvotes: 0
|
2018/03/17
| 575 | 2,072 |
<issue_start>username_0: I am learning React and I have already created a few apps with CRA.
I haven't found a good and easy way to include sass on my react projects so I came up with this:
`install node-sass on the src folder`
add this to the `package.json`:
`"node:sass": "node-sass src/index.scss src/index.css -w"`
then on each component, I would add a sass partial file, so I could keep the style and the js file in the same folder.
is there any problems with doing that?
I've read some tutorials to config webpack to use sass but it sounded to complicated.<issue_comment>username_1: Including partials per component is just fine and actually encouraged as a standard. Then you include it in the webpack with the `ExtractTextPlugin`, which allows you to bundle all your sass files into a single css file that you import in `index.html`. You can see an example here: <https://github.com/ianshowell/react-serverless-kickstart/blob/master/webpack.common.js#L46>
For this to work, you also need to include the `sass-loader` which will let your Js files parse your Sass class names. Feel free to use my starter pack that the above code is linked in to help you figure it all out.
Edit: Also, take a look at this example component to see how importing styles works: <https://github.com/ianshowell/react-serverless-kickstart/tree/master/src/components/TodoItem>
Upvotes: 1 <issue_comment>username_2: If you want to use sass in your react app, install chokidar
It will help you:
<https://www.npmjs.com/package/react-scripts-sass-chokidar>
Upvotes: 0 <issue_comment>username_3: Create react app v2, support SASS out of the box (<https://reactjs.org/blog/2018/10/01/create-react-app-v2.html>)
Here a link to read the documentation: <https://facebook.github.io/create-react-app/docs/adding-a-sass-stylesheet#docsNav>
All you need is to install node-sass if not already
```
npm i node-sass --save-dev
```
And then make sure you import files with scss extension.
If you need to change old css files, change the extension, and so follow with the imports.
Upvotes: 0
|
2018/03/17
| 790 | 2,642 |
<issue_start>username_0: I wondering why my first `if` statement returns `Error` when my input data is an object of class `numeric`?
I have clearly stated for the first `if` statement to only turn on IF the data `class` is `"data.frame"`, but when data class is `numeric`, this first `if` statement return an error! am I missing anything here?
**Update:**
I have changed instances of `&` to `&&` but when data is a `data.frame`, the function doesn't produce any output? For example, run: `standard(mtcars)`
```
standard <- function(data){
if(class(data) == "data.frame" && ncol(data) > 1){
data[paste0(names(data), ".s")] <- scale(data)
data
}
if(class(data) == "data.frame" && ncol(data) == 1){
colnames(data) <- paste0(names(data), ".s")
data <- scale(data)
data
}
if(class(data) != "data.frame"){
d <- as.data.frame(data)
colnames(d) <- paste0("Var", ncol(d), ".s")
data <- scale(d)
data
}
}
###### EXAMPLES: #######
standard(mtcars[,2]) ##Problem: `Error in if(class(data) == "data.frame" & ncol(data) > 1)`
standard(mtcars["wt"]) ## OK
standard(mtcars) ## after UPDATE, doesn't give any output
```<issue_comment>username_1: Including partials per component is just fine and actually encouraged as a standard. Then you include it in the webpack with the `ExtractTextPlugin`, which allows you to bundle all your sass files into a single css file that you import in `index.html`. You can see an example here: <https://github.com/ianshowell/react-serverless-kickstart/blob/master/webpack.common.js#L46>
For this to work, you also need to include the `sass-loader` which will let your Js files parse your Sass class names. Feel free to use my starter pack that the above code is linked in to help you figure it all out.
Edit: Also, take a look at this example component to see how importing styles works: <https://github.com/ianshowell/react-serverless-kickstart/tree/master/src/components/TodoItem>
Upvotes: 1 <issue_comment>username_2: If you want to use sass in your react app, install chokidar
It will help you:
<https://www.npmjs.com/package/react-scripts-sass-chokidar>
Upvotes: 0 <issue_comment>username_3: Create react app v2, support SASS out of the box (<https://reactjs.org/blog/2018/10/01/create-react-app-v2.html>)
Here a link to read the documentation: <https://facebook.github.io/create-react-app/docs/adding-a-sass-stylesheet#docsNav>
All you need is to install node-sass if not already
```
npm i node-sass --save-dev
```
And then make sure you import files with scss extension.
If you need to change old css files, change the extension, and so follow with the imports.
Upvotes: 0
|
2018/03/17
| 373 | 1,458 |
<issue_start>username_0: I was creating some kind of base system for internal project, I was implementing a custom form system using OOP approach as I am using TypeScript.
```
class Form extends React.Component {}
abstract class FormElement extends React.Component<{validations?:ValidationLogic[]}> {
validate();
setData();
setValidation();
}
class FormText extends FormElement {}
```
Referring to these: <https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4>
I want to know, is the downside of using class is purely subjective, or there is an objective point of view, if there's performance issue, I would be happy to see the data.
Thanks<issue_comment>username_1: When you create React components with the class syntax you will have access to the React's life cycle methods. You can read more about them [here](https://reactjs.org/docs/react-component.html). Also if your component need to access to `this`, set state, or set `ref` you should use a class component.
Upvotes: 2 <issue_comment>username_2: It is fine to do OO with React, and have the benefits as @username_1 points out.
However, avoid using OO as a mechanism to reuse functions, or add more "features" to a React component such as extra logic.
It would be best to keep them separate from your React Components.
Your logic would be best to be handled in other places, such as using Redux, Mobx, or any other means.
Upvotes: 2 [selected_answer]
|
2018/03/17
| 2,262 | 7,673 |
<issue_start>username_0: I just downloaded spark-2.3.0-bin-hadoop2.7.tgz. After downloading I followed the steps mentioned here [pyspark installation for windows 10](http://deelesh.github.io/pyspark-windows.html).I used the comment bin\pyspark to run the spark & got error message
```
The system cannot find the path specified
```
Attached is the screen shot of error message[](https://i.stack.imgur.com/LM9le.png)
Attached is the screen shot of my spark bin folder
[](https://i.stack.imgur.com/7U7jQ.png)
Screen shot of my path variable looks like
[](https://i.stack.imgur.com/1nuQB.png)
[](https://i.stack.imgur.com/lb59n.png)
I have python 3.6 & Java "1.8.0\_151" in my windows 10 system
Can you suggest me how to resolve this issue?<issue_comment>username_1: Most likely you forgot to define the Windows environment variables such that the Spark bin directory is in your PATH environment variable.
Define the following environment variables using the usual methods for Windows.
First define an environment variable called SPARK\_HOME to be C:\spark\spark-2.3.0-bin-hadoop2.7
Then either add %SPARK\_HOME%\bin to your existing PATH environment variable, or if none exists (unlikely) define PATH to be %SPARK\_HOME%\bin
If there is no typo specifying the PATH,
echo %PATH% should give you the fully resolved path to the Spark bin directory i.e. it should look like
```
C:\spark\spark-2.3.0-bin-hadoop2.7\bin;
```
If PATH is correct, you should be able to type pyspark in any directory and it should run.
If this does not resolve the issue perhaps the issue is as specified in [pyspark: The system cannot find the path specified](https://stackoverflow.com/questions/46849585/pyspark-the-system-cannot-find-the-path-specified?noredirect=1&lq=1) in which case this question is a duplicate.
Upvotes: 0 <issue_comment>username_2: Update: in my case it came down to wrong path for JAVA, I got it to work...
I'm having the same problem. I initially installed Spark through pip, and pyspark ran successfully. Then I started messing with Anaconda updates and it never worked again. Any help will be appreciated...
I'm assuming PATH is installed correctly for the original author. A way to check that is to run `spark-class` from command prompt. With correct PATH it will return `Usage: spark-class []` when ran from an arbitrary location. The error from `pyspark` comes from a string of .cmd files that I traced to the last lines in spark-class2.cmd
This maybe silly, but altering the last block of code shown below changes the error message you get from `pyspark` from "The system cannot find the path specified" to "The syntax of the command is incorrect". Removing this whole block makes `pyspark` do nothing.
```
rem The launcher library prints the command to be executed in a single line suitable for being
rem executed by the batch interpreter. So read all the output of the launcher into a variable.
set LAUNCHER_OUTPUT=%temp%\spark-class-launcher-output-%RANDOM%.txt
"%RUNNER%" -Xmx128m -cp "%LAUNCH_CLASSPATH%" org.apache.spark.launcher.Main
%* > %LAUNCHER_OUTPUT%
for /f "tokens=*" %%i in (%LAUNCHER_OUTPUT%) do (
set SPARK_CMD=%%i
)
del %LAUNCHER_OUTPUT%
%SPARK_CMD%
```
I removed "del %LAUNCHER\_OUTPUT%" and saw that the text file generated remains empty. Turns out "%RUNNER%" failed to find correct directory with java.exe because I messed up the PATH to Java (not Spark).
Upvotes: 0 <issue_comment>username_3: Worked hours and hours on this. My problem was with Java 10 installation. I uninstalled it and installed Java 8, and now Pyspark works.
Upvotes: 2 <issue_comment>username_4: Switching SPARK\_HOME to `C:\spark\spark-2.3.0-bin-hadoop2.7` and changing PATH to include `%SPARK_HOME%\bin` did the trick for me.
Originally my SPARK\_HOME was set to `C:\spark\spark-2.3.0-bin-hadoop2.7\bin` and PATH was referencing it as `%SPARK_HOME%`.
Running a spark command directly in my SPARK\_HOME dir worked but only once. After that initial success I then noticed your same error and that `echo %SPARK_HOME%` was showing `C:\spark\spark-2.3.0-bin-hadoop2.7\bin\..` I thought perhaps spark-shell2.cmd had edited it in attempts to get itself working, which led me here.
Upvotes: 1 <issue_comment>username_5: My problem was that the JAVA\_HOME was pointing to JRE folder instead of JDK. Make sure that you take care of that
Upvotes: 4 <issue_comment>username_6: Actually, the problem was with the `JAVA_HOME` environment variable path. The `JAVA_HOME` path was set to `.../jdk/bin previously`,
I stripped the last `/bin` part for `JAVA_HOME` while keeping it (`/jdk/bin`) in system or environment path variable (`%path%`) did the trick.
Upvotes: 5 <issue_comment>username_7: if you use anaconda for window. The below command can save your time
```sh
conda install -c conda-forge pyspark
```
After that restart anaconda and start "jupyter notebook"
[](https://i.stack.imgur.com/SBDKI.png)
Upvotes: 0 <issue_comment>username_8: I know this is an old post, but I am adding my finding in case it helps anyone.
The issue is mainly due to the line `source "${SPARK_HOME}"/bin/load-spark-env.sh` in pyspark file. As you can see it's not expecting 'bin' in SPARK\_HOME. All I had to do was remove 'bin' from my SPARK\_HOME environment variable and it worked (`C:\spark\spark-3.0.1-bin-hadoop2.7\bin` to `C:\spark\spark-3.0.1-bin-hadoop2.7\`).
The error on Windows Command Prompt made it appear like it wasn't recognizing 'pyspark', while the real issue was with it not able to find the file 'load-spark-env.sh.'
Upvotes: 0 <issue_comment>username_9: For those who use Windows and still trying, what solved to me was reinstalling Python (3.9) **as a local user** (`c:\Users\\AppData\Local\Programs\Python`) and defined both env variables `PYSPARK_PYTHON` and `PYSPARK_DRIVER_PYTHON` to `c:\Users\\AppData\Local\Programs\Python\python.exe`
Upvotes: 2 <issue_comment>username_10: Fixing problems installing Pyspark (Windows)
**Incorrect JAVA\_HOME path**
```
> pyspark
The system cannot find the path specified.
```
Open System Environment variables:
```
rundll32 sysdm.cpl,EditEnvironmentVariables
```
Set JAVA\_HOME: System Variables > New:
```
Variable Name: JAVA_HOME
Variable Value: C:\Program Files\Java\jdk1.8.0_261
```
Also, check that SPARK\_HOME and HADOOP\_HOME are correctly set, e.g.:
```
SPARK_HOME=C:\Spark\spark-3.2.0-bin-hadoop3.2
HADOOP_HOME=C:\Spark\spark-3.2.0-bin-hadoop3.2
```
Important: Double-check the following
1. The path exists
2. The path does not contain the `bin` folder
**Incorrect Java version**
```
> pyspark
WARN SparkContext: Another SparkContext is being constructed
UserWarning: Failed to initialize Spark session.
java.lang.NoClassDefFoundError: Could not initialize class org.apache.spark.storage.StorageUtils$
```
Ensure that JAVA\_HOME is set to Java 8 (jdk1.8.0)
**winutils not installed**
```
> pyspark
WARN Shell: Did not find winutils.exe
java.io.FileNotFoundException: Could not locate Hadoop executable
```
Download [winutils.exe](https://github.com/steveloughran/winutils/raw/master/hadoop-3.0.0/bin/winutils.exe) and copy it to your spark home bin folder
```
curl -OutFile C:\Spark\spark-3.2.0-bin-hadoop3.2\bin\winutils.exe -Uri https://github.com/steveloughran/winutils/raw/master/hadoop-3.0.0/bin/winutils.exe
```
Upvotes: 1
|
2018/03/17
| 871 | 2,754 |
<issue_start>username_0: I am still learning xpath and I am trying to skip the first row of a table because the first row has no values. I am not having success i searched through stack over flow and could not find anyone with a similar issue. My code is below:
```
int reqIndex = 0;
do {
List payDates = driver.findElements(By.xpath("//tr[starts-with(@id,'changeStartWeekGrid\_row\_')]/td[contains(@id,'\_cell\_4')/span]"));
System.out.println(payDates);
for(WebElement pd:payDates) {
LocalDate localDate = LocalDate.now();
java.util.Date d = new SimpleDateFormat("yyyy-MM-dd").parse(localDate.toString());
String str = pd.getText();
if ( str >= (d) ){ // still figuring this out
driver.findElement(By.xpath( "//tr[@id='changeStartWeekGrid\_row\_'" + reqIndex +"])/TBODY[@id='changeStartWeekGrid\_rows\_tbody']/TR[7]/TD[1]/DIV[1]/DIV[1]/DIV[1]")).click();
break;
}else{
reqIndex++;
}
}
}while(reqIndex < 7 ); /// do this 7 times
Thread.sleep(10000);
```
This is the part i am trouble shooting right now
```
List payDates = driver.findElements(By.xpath("//tr[starts-with(@id,'changeStartWeekGrid\_row\_')]/td[contains(@id,'\_cell\_4')/span]"));
System.out.println(payDates);
Thread.sleep(10000);
```
The xpath works the problem is that it is selecting the first row and it has no values row zero does so it needs to skip the first row and go to row zero.
when i run the code i get this message:
```
( //tr[starts-with(@id,'changeStartWeekGrid_row_')]/td[contains(@id,'_cell_4')/span])
ilter expression must evaluate to nodeset.
```
the row highlighted is the row i am trying to skip
[](https://i.stack.imgur.com/dn2I6.png)
cell 4 image
[](https://i.stack.imgur.com/xCVRj.png)
-----radio button html code below
```
```
---radio button picture
[](https://i.stack.imgur.com/4alvc.png)<issue_comment>username_1: Try to use XPath
```
//table[@id='changeStartWeekGrid_rows_table']//tr[preceding-sibling::tr]
```
to select all `tr` nodes except the firts one
You can also use [`position()`](https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/position) as below:
```
//table[@id='changeStartWeekGrid_rows_table']//tr[position()>1]
```
Note that in XPath indexation starts from `1` and so `[position()>1]` predicate means *return all sibling nodes skiping the first one*
Upvotes: 2 <issue_comment>username_2: You may also use
```
//tr[starts-with(@id,'changeStartWeekGrid_row_') and not(starts-with(@id, 'changeStartWeekGrid_row_column'))]/td[5]/span
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 2,044 | 8,080 |
<issue_start>username_0: I'm trying to build a simple flying game. I have two scenes- a Management scene to spawn GameManager and SceneController instances, and a Game scene that is loaded where the player can fly through some red gates.
**Once the game scene is loaded additively, I add some gates to it. However, the gates don't show up under this scene in the hierarchy- they show up under the management scene.** The prefab does show up in the game scene. I would expect all of these to show up under the game scene.
Two questions:
1. Am I loading the game scene improperly? Does something else need to happen to make it fully active?
2. Do I not understand how scenes work, and if so, what should I be doing differently?
---
SceneController code:
```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneController : MonoBehaviour {
// This is a singleton
private static SceneController _instance;
public static SceneController Instance { get { return _instance; } }
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
} else {
_instance = this;
}
}
// Scene names
private string sceneNameGameScene = "GameScene";
// Use this for initialization
void Start () {
SceneManager.sceneLoaded += OnSceneLoaded;
StartCoroutine(LoadSceneAdditive(sceneNameGameScene, LoadSceneMode.Additive));
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode) {
if (scene.name == sceneNameGameScene) {
SceneManager.SetActiveScene(scene);
Debug.Log("OnSceneLoaded Active Scene : " + SceneManager.GetActiveScene().name);
SetupGameScene();
}
}
IEnumerator LoadSceneAdditive(string sceneName, LoadSceneMode loadSceneMode){
AsyncOperation _async = new AsyncOperation();
_async = SceneManager.LoadSceneAsync(sceneName, loadSceneMode);
while (!_async.isDone) {
yield return null;
}
Scene nextScene = SceneManager.GetSceneByName( name );
if (nextScene.IsValid ()) {
SceneManager.SetActiveScene (nextScene);
}
}
private void SetupGameScene() {
// Create a game map
GameMap gameMap = new GameMap();
gameMap.Setup(this.transform);
}
}
```
GameMap Code:
```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameMap {
private GameObject gatePrefab = GameObject.Instantiate(Resources.Load("GatePrefab")) as GameObject;
private Transform transform;
public GameMap() {}
public void Setup (Transform parentTransform) {
transform = parentTransform;
Vector3 position;
Quaternion rotation;
position = new Vector3(0, 0, 0);
rotation = Quaternion.identity;
CreateGate(position, rotation, 10.0f, 2.0f, "Gate 1");
position = new Vector3(0, 0, 20);
rotation = Quaternion.identity * Quaternion.Euler(0, 45, 0);
CreateGate(position, rotation, 10.0f, 1.0f, "Gate 2");
position = new Vector3(20, 0, 20);
rotation = Quaternion.identity * Quaternion.Euler(0, 90, 0);
CreateGate(position, rotation, 8.0f, 1.0f, "Gate 3");
CreateGround();
}
private void CreateGate(Vector3 position, Quaternion rotation, float lengthOfSide, float thickness, string name) {
// Create the gates, and call the "Initialize" method to populate properties as Unity doesn't have constructors.
GameObject clone = GameObject.Instantiate(gatePrefab, position, rotation, transform) as GameObject;
clone.name = name;
clone.GetComponent().Initialize(lengthOfSide, thickness);
}
private void CreateGround() {
Debug.Log("OnSceneLoaded Active Scene : " + SceneManager.GetActiveScene().name);
GameObject ground = GameObject.CreatePrimitive(PrimitiveType.Plane);
ground.name = "Ground";
ground.transform.parent = transform;
ground.transform.localPosition = new Vector3(0, -10, 0);
ground.transform.localRotation = Quaternion.identity;
ground.transform.localScale = new Vector3(50, 1, 50);
ground.GetComponent().material.color = Color.grey;
}
}
```
Gate code:
```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gate : MonoBehaviour {
float lengthOfSide;
float thickness;
public void Initialize (float lengthOfSide, float thickness) {
this.lengthOfSide = lengthOfSide;
this.thickness = thickness;
}
// Use this for initialization
void Start () {
SetupRigidBody();
Setup3dEntities();
}
void SetupRigidBody() {
Rigidbody rb = this.gameObject.AddComponent();
rb.detectCollisions = true;
rb.mass = 1000;
rb.useGravity = false;
}
// Create the physical gate
void Setup3dEntities() {
Vector3 position;
Vector3 scale;
float lengthOfVeritcalSegment = lengthOfSide - (2 \* thickness);
float yPosHorizontalSegment = (lengthOfSide - thickness) / 2;
float xPosVerticalSegment = lengthOfSide - thickness;
// Bottom
position = new Vector3(0, -yPosHorizontalSegment, 0);
scale = new Vector3(lengthOfSide, thickness, thickness);
CreatePrimitiveCube(position, scale);
// Top
position = new Vector3(0, yPosHorizontalSegment, 0);
scale = new Vector3(lengthOfSide, thickness, thickness);
CreatePrimitiveCube(position, scale);
// Left
position = new Vector3(xPosVerticalSegment/2, 0, 0);
scale = new Vector3(thickness, lengthOfVeritcalSegment, thickness);
CreatePrimitiveCube(position, scale);
// Right
position = new Vector3(-xPosVerticalSegment/2, 0, 0);
scale = new Vector3(thickness, lengthOfVeritcalSegment, thickness);
CreatePrimitiveCube(position, scale);
}
void CreatePrimitiveCube(Vector3 position, Vector3 scale) {
// Create a primitive cube. Note that we want to set the position and rotation to match the parent!
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.parent = gameObject.transform;
cube.transform.localPosition = position;
cube.transform.localRotation = Quaternion.identity;
cube.transform.localScale = scale;
// TODO: Make a better color/material mechanism!
cube.GetComponent().material.color = Color.red;
// Debug.Log("Cube.parent: " + cube.transform.parent.gameObject.name);
// Debug.Log("Cube.localScale: " + cube.transform.localScale);
}
}
```
Screenshot- note hierarchy is weird:
[](https://i.stack.imgur.com/kzh5p.png)<issue_comment>username_1: So, as i understand, you want to have a Managment Scene, where you can manage the game with a script.
My idea is that you dont use `LoadSceneAdditive` but [DontDestroyOnLoad](https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html). This will make your script still be loaded even when you load an another scene. This will also make the gameobjects spawn in the currently loaded scene.
So, you will only have to use `LoadSceneMode.Single` instead of `LoadSceneMode.Additive`
An another option is to use [SceneManager.SetActiveScene](https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.SetActiveScene.html) to change which scene you want to set as "parent scene" or the scene you want to spawn gameobjects on.
Upvotes: 0 <issue_comment>username_2: Your SceneController passes it's transform to the GameMap Setup method.
(I assume that the SceneController transform is the "app" object?)
The GameMap Setup method then creates the gates and uses the given parentTransform
as a parent for each gate (because it's passend in the GameObject.Instantiate method)
So i guess it makes sense that the Gate objects are a child of the "app" object which is in the managment scene?
If you want to have them in the other scene, then you have to pass a different parent or no parent.
Upvotes: 3 [selected_answer]
|
2018/03/17
| 1,611 | 4,620 |
<issue_start>username_0: ```
var y;
function deci(y) {
var res = "";
while (y != 1) {
res = res + y % 2;
y = y / 2;
}
return (1 + res);
}
```<issue_comment>username_1: This to me looks like an endless loop. Try to modify the condition to y >= 1
```
var y;
function deci(y) {
var res = "";
while (y >= 1) {
res = res + y % 2;
y = y / 2;
}
return (1 + res);
}
```
Upvotes: -1 [selected_answer]<issue_comment>username_2: Three problems
* global `y` is bad practice β you're [shadowing](https://en.wikipedia.org/wiki/Variable_shadowing) it with a local `y` so I'm guessing you didn't intend to do this
* Your `while` condition is broken β repeatedly dividing a number by 2 will not always reach 1
* JavaScript performs floating point division, so you need to truncate the decimal
This is probably what you meant to write
```js
const deci = y =>
{
let res = ''
while (y >= 2)
{
res = res + String (y % 2)
y = y / 2 >> 0
}
return res + String (y)
}
console.log (deci (0))
console.log (deci (1))
console.log (deci (2))
console.log (deci (3))
console.log (deci (4))
console.log (deci (5))
```
Here's another way you can write the program
```js
const deci = y =>
y < 2
? String (y)
: deci (y / 2 >> 0) + String (y % 2)
console.log (deci (0))
console.log (deci (1))
console.log (deci (2))
console.log (deci (3))
console.log (deci (4))
console.log (deci (5))
```
A default parameter value and better name make this function a little nicer to read, imo
```
const decimalToBinary = (n = 0) =>
n < 2
? String (n)
: decimalToBinary (n / 2 >> 0) + String (n % 2)
```
As @NinaScholz points out, you can perform `n / 2 >> 0` in a single operation `n >> 1` - the function is further improved
```
const decimalToBinary = (n = 0) =>
n < 2
? String (n)
: decimalToBinary (n >> 1) + String (n % 2)
```
Alternatively, we could make `2` a parameter of our function to create a generic base converter
```js
const decimalToBase = (n = 0, base = 2) =>
n < base
? String (n)
: decimalToBase (n / base >> 0) + String (n % base)
const decimalToBinary = (n = 0) =>
decimalToBase (n, 2)
const decimalToOctal = (n = 0) =>
decimalToBase (n, 8)
console.log (decimalToBinary (0), decimalToOctal (0)) // 0 0
console.log (decimalToBinary (1), decimalToOctal (1)) // 0 1
console.log (decimalToBinary (2), decimalToOctal (2)) // 10 2
console.log (decimalToBinary (7), decimalToOctal (7)) // 111 7
console.log (decimalToBinary (8), decimalToOctal (8)) // 1000 10
console.log (decimalToBinary (9), decimalToOctal (9)) // 1001 11
```
Upvotes: -1 <issue_comment>username_3: When you call `deci(3)`, `y` will never become `1`, so you will get an infinite loop. The only inputs that does not result in an infinite loop are powers of 2 (1, 2, 4, 8, 16, ...)
To figure out what's going on, add a console.log call inside the `while` loop.
```js
function deci(y) {
console.log('converting', y, 'to binary')
var res = '1'
while (y != 1) {
res += y % 2
y = y / 2
console.log('y is', y)
// let's throw an error after a while to avoid freezing the computer
if (y < 0.001) throw "infinite loop"
}
console.log('the result is', res)
}
deci(64) // this works fine
deci(3) // this ends up in an infinite loop
```
In general do not use `=!` and `==` with floating point numbers. Since even when your logic seems correct, there might be rounding errors that you would not get with decimal numbers. [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)
To convert a number to base 2, you can use [`number.toString(2)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString)
```js
function deci(n) {
return n.toString(2)
}
console.log(deci(3)) // -> '11'
```
Upvotes: -1 <issue_comment>username_4: What you could do
* change the loop to a `do ... while` loop, because it loops at least one time, for zero values,
* switch the assignment of `res` to `res = y % 2 + res;`, because it has the right order now,
* take the integer value of the divided value for the next loop,
* check the value and go on with non zero values.
```js
function deci(y) {
var res = "";
do {
res = y % 2 + res;
y = Math.floor(y / 2);
} while (y)
return res;
}
console.log (deci(0));
console.log (deci(1));
console.log (deci(2));
console.log (deci(3));
console.log (deci(4));
console.log (deci(5));
console.log (deci(13));
```
Upvotes: 0
|
2018/03/17
| 1,682 | 5,060 |
<issue_start>username_0: I have a form which allows the adding of possibly hundreds of different association types to a form. I'm using the cocoon gem's `link_to_add_association` but rendering 100's of links is very slow as they're populated with all the html required to add them. Is there any way to dynamically create the links from an ajax request? The problem is `link_to_add_association` requires the form builder object which is unavailable after the initial page request.
As a side note the links are grouped so if I'm hoping to render the links for that particular group when it's clicked.<issue_comment>username_1: This to me looks like an endless loop. Try to modify the condition to y >= 1
```
var y;
function deci(y) {
var res = "";
while (y >= 1) {
res = res + y % 2;
y = y / 2;
}
return (1 + res);
}
```
Upvotes: -1 [selected_answer]<issue_comment>username_2: Three problems
* global `y` is bad practice β you're [shadowing](https://en.wikipedia.org/wiki/Variable_shadowing) it with a local `y` so I'm guessing you didn't intend to do this
* Your `while` condition is broken β repeatedly dividing a number by 2 will not always reach 1
* JavaScript performs floating point division, so you need to truncate the decimal
This is probably what you meant to write
```js
const deci = y =>
{
let res = ''
while (y >= 2)
{
res = res + String (y % 2)
y = y / 2 >> 0
}
return res + String (y)
}
console.log (deci (0))
console.log (deci (1))
console.log (deci (2))
console.log (deci (3))
console.log (deci (4))
console.log (deci (5))
```
Here's another way you can write the program
```js
const deci = y =>
y < 2
? String (y)
: deci (y / 2 >> 0) + String (y % 2)
console.log (deci (0))
console.log (deci (1))
console.log (deci (2))
console.log (deci (3))
console.log (deci (4))
console.log (deci (5))
```
A default parameter value and better name make this function a little nicer to read, imo
```
const decimalToBinary = (n = 0) =>
n < 2
? String (n)
: decimalToBinary (n / 2 >> 0) + String (n % 2)
```
As @NinaScholz points out, you can perform `n / 2 >> 0` in a single operation `n >> 1` - the function is further improved
```
const decimalToBinary = (n = 0) =>
n < 2
? String (n)
: decimalToBinary (n >> 1) + String (n % 2)
```
Alternatively, we could make `2` a parameter of our function to create a generic base converter
```js
const decimalToBase = (n = 0, base = 2) =>
n < base
? String (n)
: decimalToBase (n / base >> 0) + String (n % base)
const decimalToBinary = (n = 0) =>
decimalToBase (n, 2)
const decimalToOctal = (n = 0) =>
decimalToBase (n, 8)
console.log (decimalToBinary (0), decimalToOctal (0)) // 0 0
console.log (decimalToBinary (1), decimalToOctal (1)) // 0 1
console.log (decimalToBinary (2), decimalToOctal (2)) // 10 2
console.log (decimalToBinary (7), decimalToOctal (7)) // 111 7
console.log (decimalToBinary (8), decimalToOctal (8)) // 1000 10
console.log (decimalToBinary (9), decimalToOctal (9)) // 1001 11
```
Upvotes: -1 <issue_comment>username_3: When you call `deci(3)`, `y` will never become `1`, so you will get an infinite loop. The only inputs that does not result in an infinite loop are powers of 2 (1, 2, 4, 8, 16, ...)
To figure out what's going on, add a console.log call inside the `while` loop.
```js
function deci(y) {
console.log('converting', y, 'to binary')
var res = '1'
while (y != 1) {
res += y % 2
y = y / 2
console.log('y is', y)
// let's throw an error after a while to avoid freezing the computer
if (y < 0.001) throw "infinite loop"
}
console.log('the result is', res)
}
deci(64) // this works fine
deci(3) // this ends up in an infinite loop
```
In general do not use `=!` and `==` with floating point numbers. Since even when your logic seems correct, there might be rounding errors that you would not get with decimal numbers. [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)
To convert a number to base 2, you can use [`number.toString(2)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString)
```js
function deci(n) {
return n.toString(2)
}
console.log(deci(3)) // -> '11'
```
Upvotes: -1 <issue_comment>username_4: What you could do
* change the loop to a `do ... while` loop, because it loops at least one time, for zero values,
* switch the assignment of `res` to `res = y % 2 + res;`, because it has the right order now,
* take the integer value of the divided value for the next loop,
* check the value and go on with non zero values.
```js
function deci(y) {
var res = "";
do {
res = y % 2 + res;
y = Math.floor(y / 2);
} while (y)
return res;
}
console.log (deci(0));
console.log (deci(1));
console.log (deci(2));
console.log (deci(3));
console.log (deci(4));
console.log (deci(5));
console.log (deci(13));
```
Upvotes: 0
|
2018/03/17
| 604 | 1,919 |
<issue_start>username_0: So I have various UI components of varying dimensions, which I am putting up together in a page. I want to arrange them horizontally in a grid, where each row should be equal to the height of the component which has the maximum height in that row. There are no fixed number of columns for each row. Components should be placed next to each other without their dimensions being changed, and should automatically wrap to the next row if there is no space left for that component in that row.
I tried using bootstrap, but I must specify column width for each component like `col-xs-number`, which I can't do as I can't freeze the number of items in a row.
Edit: The application uses bootstrap version 3, so can't use V4.
Is this possible?<issue_comment>username_1: Check flexbox, bootstrap 4 is using flexbox, so you can have columns without numbers.
Example:
```css
.container{
border:1px solid black;
}
.col:first-of-type{
background:white;
}
.col:nth-of-type(2){
background:green;
}
.col:last-of-type{
background:red;
}
```
```html
First
Second
Third
```
Upvotes: 0 <issue_comment>username_2: You can do it without any kind of Bootstrap, just using `display: inline-block` for the elements.
Below is a demo where I add 12 elements of varying heights in a container div, where the width of the container div is set to a random value every time it is run to show how it will wrap differently each time.
```js
var heights = [100, 20, 80, 140, 65, 90, 30, 70, 130, 55, 75, 100];
for (var i = 0; i < heights.length; i++) {
$('#x').append($(''))
}
var w = Math.floor((Math.random() * 400) + 100);
$('#x').css("width", w + "px");
```
```css
#x div {
display: inline-block;
vertical-align: text-top;
width: 50px;
background: green;
margin: 10px;
}
#x {
border: solid 1px #888
}
```
```html
---
---
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 524 | 1,773 |
<issue_start>username_0: I need to run the server like I simply do with:
`npm run start`
but I need to use the production mode. Is this possible?
In ember or angular it is possible. How to do in `create-react-app`?
I tried `npm run start --prod` but nothing.<issue_comment>username_1: Yes you can run `npm start` command on server but there should be your ***node-modules***. If ***node-modules*** are not present there than you can get them with `npm install` command.
Upvotes: -1 <issue_comment>username_2: To serve the app in production mode you need to follow below steps
1. create a production build
npm run build
2. install [npm serve](https://www.npmjs.com/package/serve/v/10.1.1) globally
npm i -g serve
3. You may serve it with a static server now
serve -s build
You can check for more options [here](https://facebook.github.io/create-react-app/docs/available-scripts#npm-run-build).
For the development in production you can enable Hot reloading in react app without ejecting
With just 3 lines of code, you can turn on HMR, but with one big caveat: React state and DOM state are not preserved between reloads. This is kind of a bummer.
You can add these lines to index.js to turn on standard Webpack HMR that doesnβt preserve state between reloads:
```
if (module.hot) {
module.hot.accept();
}
```
Read more about it [here](https://medium.com/@brianhan/hot-reloading-cra-without-eject-b54af352c642) Hope it helps Thanks!
Upvotes: 3 <issue_comment>username_3: The best option is probably to do a normal production build and then run it locally.
First install an HTTP server:
```
npm install serve -g
```
Then:
```
npm run build
serve -s build
```
By default, it will run on port 5000 so your local URL is
<http://localhost:5000>
Upvotes: 6
|
2018/03/17
| 198 | 741 |
<issue_start>username_0: I am working on an Angular 4 project and using Arabic and English language, so I want to switch template from LTR to RTL based on language.
I use a bootstrap, how to handle rtl.css files?<issue_comment>username_1: You should use the [Angular CDK bidirectionnal](https://material.angular.io/cdk/bidi/overview) library to help you with bidirectionnality. The official Material Angular library use it.
Upvotes: 1 <issue_comment>username_2: [check this](https://stackoverflow.com/a/51720981/6270421)
you just need to use the css text-align property to LTR and RTL based on the selected language
```
```
or create a directive which you can use on all text elements that will fulfill the above requirement
Upvotes: -1
|
2018/03/17
| 519 | 1,953 |
<issue_start>username_0: Why does `Console` show type `B` not `A`, even though `a2` was assigned to `new B()`? I cannot understand exactly what happens in `A a2 = new B()`.
```
class A { }
class B : A { }
...
A a1 = new A();
A a2 = new B();
Console.WriteLine(a2.GetType());
```<issue_comment>username_1: Because you have created instance of class `B` not `A` and you are able to hold in variable of type `A` due to inheritance feature of OOP as you are inheriting your `B` class from `A`.
But the actual type of the `a2` is `B` not `A` though it can be represent as `A` as well, but the `GetType()` reutrns the run-time type which is `B`.
You can have a look at this [SO post](https://stackoverflow.com/q/983030/1875256) too which explains what the `GetType` is expected to return for an object and what is `typeof()` and how we can use `is` for inheritance hierarchy checking.
Hope it helps.
Upvotes: 1 <issue_comment>username_2: Just because you refer to it through type `A` doesn't mean that the actual type suddenly changes to `A`, it's still a `B` object. You decided to create one with `new B()`.
Upvotes: 0 <issue_comment>username_3: You should be aware of the difference between compile time type and runtime type. The compile time type is the type the compiler knows about in this case the type you have declared - A. The runtime type is the type of the object that happens to be referenced by the variable in this case B. Compile time (what the compiler knows about) and runtime (what happens when the program is actually run) is a very important distinction that applies to types, errors and even calculations.
Upvotes: 0 <issue_comment>username_4: A variable is just something that points to an object. You can refer an object through a variable of any type that it inherits from (or any interface it implements) but that doesn't change the type of the object itself - this is one of the forms of **polymorphism** in C#.
Upvotes: 2
|
2018/03/17
| 602 | 2,209 |
<issue_start>username_0: Hi guys i have been trying to find out how i can count each time a person has been entered in a database, i have duplicates in the same day so i need help with the code to just count 1 entry in a specific date eg below, i just want to count ID 56 once in the specific Date.
```
++++++++++++++++++++
+ ID + Date +
++++++++++++++++++++
+ 56 + 17/03/2018 +
++++++++++++++++++++
+ 56 + 17/03/2018 +
++++++++++++++++++++
+ 76 + 17/03/2018 +
++++++++++++++++++++
+ 56 + 16/03/2018 +
++++++++++++++++++++
```<issue_comment>username_1: Because you have created instance of class `B` not `A` and you are able to hold in variable of type `A` due to inheritance feature of OOP as you are inheriting your `B` class from `A`.
But the actual type of the `a2` is `B` not `A` though it can be represent as `A` as well, but the `GetType()` reutrns the run-time type which is `B`.
You can have a look at this [SO post](https://stackoverflow.com/q/983030/1875256) too which explains what the `GetType` is expected to return for an object and what is `typeof()` and how we can use `is` for inheritance hierarchy checking.
Hope it helps.
Upvotes: 1 <issue_comment>username_2: Just because you refer to it through type `A` doesn't mean that the actual type suddenly changes to `A`, it's still a `B` object. You decided to create one with `new B()`.
Upvotes: 0 <issue_comment>username_3: You should be aware of the difference between compile time type and runtime type. The compile time type is the type the compiler knows about in this case the type you have declared - A. The runtime type is the type of the object that happens to be referenced by the variable in this case B. Compile time (what the compiler knows about) and runtime (what happens when the program is actually run) is a very important distinction that applies to types, errors and even calculations.
Upvotes: 0 <issue_comment>username_4: A variable is just something that points to an object. You can refer an object through a variable of any type that it inherits from (or any interface it implements) but that doesn't change the type of the object itself - this is one of the forms of **polymorphism** in C#.
Upvotes: 2
|
2018/03/17
| 719 | 2,918 |
<issue_start>username_0: Let's say I'm building a shopping app and one of the features it has is to give users the ability to browse a category of items. While browsing the items, the user can store the items into their own lists (like Amazon's wish list feature). Therefore, I have a component called `item` which shows an item to the user.
The item component allows the user to click a `+` icon in it which will show the user's their lists. Then the user can select a list to add the item to. Kind of like what YouTube did here: <https://i.stack.imgur.com/7jMKz.png>.
I also plan to have a list page, where a user can browse the items of a specific list they made. The list page would have a lot of `item` components.
The problem is that while there are many `item` components displayed on the page, **they all need to know the lists that the user has created**, and their lists are retrieved from a web server (from a database).
So how would I do this? I could have all of them make an HTTP request, but that would execute an HTTP request for each item on the page, only to get the same data. I could pass this responsibility to a parent component, but sometimes the `item` components would be by itself with no parent to get the lists from.<issue_comment>username_1: Because you have created instance of class `B` not `A` and you are able to hold in variable of type `A` due to inheritance feature of OOP as you are inheriting your `B` class from `A`.
But the actual type of the `a2` is `B` not `A` though it can be represent as `A` as well, but the `GetType()` reutrns the run-time type which is `B`.
You can have a look at this [SO post](https://stackoverflow.com/q/983030/1875256) too which explains what the `GetType` is expected to return for an object and what is `typeof()` and how we can use `is` for inheritance hierarchy checking.
Hope it helps.
Upvotes: 1 <issue_comment>username_2: Just because you refer to it through type `A` doesn't mean that the actual type suddenly changes to `A`, it's still a `B` object. You decided to create one with `new B()`.
Upvotes: 0 <issue_comment>username_3: You should be aware of the difference between compile time type and runtime type. The compile time type is the type the compiler knows about in this case the type you have declared - A. The runtime type is the type of the object that happens to be referenced by the variable in this case B. Compile time (what the compiler knows about) and runtime (what happens when the program is actually run) is a very important distinction that applies to types, errors and even calculations.
Upvotes: 0 <issue_comment>username_4: A variable is just something that points to an object. You can refer an object through a variable of any type that it inherits from (or any interface it implements) but that doesn't change the type of the object itself - this is one of the forms of **polymorphism** in C#.
Upvotes: 2
|
2018/03/17
| 604 | 2,205 |
<issue_start>username_0: I can't figure out how to wrap a GLib.Array in a GLib.Value.
I tried this code.
```
public int main (string[] args) {
var value = Value(typeof (Array));
var a = new Array();
a.append\_val("test");
value.set\_object((Object) a);
return 0;
}
```
But it resulted in these errors.
```
(process:1797): GLib-GObject-WARNING **: invalid uninstantiatable type '(null)' in cast to 'GObject'
(process:1797): GLib-GObject-CRITICAL **: g_value_set_object: assertion 'G_VALUE_HOLDS_OBJECT (value)' failed
```<issue_comment>username_1: Because you have created instance of class `B` not `A` and you are able to hold in variable of type `A` due to inheritance feature of OOP as you are inheriting your `B` class from `A`.
But the actual type of the `a2` is `B` not `A` though it can be represent as `A` as well, but the `GetType()` reutrns the run-time type which is `B`.
You can have a look at this [SO post](https://stackoverflow.com/q/983030/1875256) too which explains what the `GetType` is expected to return for an object and what is `typeof()` and how we can use `is` for inheritance hierarchy checking.
Hope it helps.
Upvotes: 1 <issue_comment>username_2: Just because you refer to it through type `A` doesn't mean that the actual type suddenly changes to `A`, it's still a `B` object. You decided to create one with `new B()`.
Upvotes: 0 <issue_comment>username_3: You should be aware of the difference between compile time type and runtime type. The compile time type is the type the compiler knows about in this case the type you have declared - A. The runtime type is the type of the object that happens to be referenced by the variable in this case B. Compile time (what the compiler knows about) and runtime (what happens when the program is actually run) is a very important distinction that applies to types, errors and even calculations.
Upvotes: 0 <issue_comment>username_4: A variable is just something that points to an object. You can refer an object through a variable of any type that it inherits from (or any interface it implements) but that doesn't change the type of the object itself - this is one of the forms of **polymorphism** in C#.
Upvotes: 2
|
2018/03/17
| 516 | 1,974 |
<issue_start>username_0: Is there Any way to KILL/EXIT/CLOSE VI and ATOM from a running script
example script, test.sh:
EDITOR1=vi
EDITOR2=atom
$EDITOR1 helloWorld.txt
$EDITOR2 file1.txt
kill $EDITOR1
kill $EITOR2
Is there any NOT Set way to kill it, I mean with a variable fore example the Filename.<issue_comment>username_1: Because you have created instance of class `B` not `A` and you are able to hold in variable of type `A` due to inheritance feature of OOP as you are inheriting your `B` class from `A`.
But the actual type of the `a2` is `B` not `A` though it can be represent as `A` as well, but the `GetType()` reutrns the run-time type which is `B`.
You can have a look at this [SO post](https://stackoverflow.com/q/983030/1875256) too which explains what the `GetType` is expected to return for an object and what is `typeof()` and how we can use `is` for inheritance hierarchy checking.
Hope it helps.
Upvotes: 1 <issue_comment>username_2: Just because you refer to it through type `A` doesn't mean that the actual type suddenly changes to `A`, it's still a `B` object. You decided to create one with `new B()`.
Upvotes: 0 <issue_comment>username_3: You should be aware of the difference between compile time type and runtime type. The compile time type is the type the compiler knows about in this case the type you have declared - A. The runtime type is the type of the object that happens to be referenced by the variable in this case B. Compile time (what the compiler knows about) and runtime (what happens when the program is actually run) is a very important distinction that applies to types, errors and even calculations.
Upvotes: 0 <issue_comment>username_4: A variable is just something that points to an object. You can refer an object through a variable of any type that it inherits from (or any interface it implements) but that doesn't change the type of the object itself - this is one of the forms of **polymorphism** in C#.
Upvotes: 2
|
2018/03/17
| 636 | 2,024 |
<issue_start>username_0: I've created a `Header.php` file in the root directory.
Below is the tree structure.
```
-SiteName
-Header.php
-Books
-Samples
-Math
-MathBook.php
-index.php
-About.php
```
So MathBook.php includes Header.php like below
```
include '../../../Header.php';
```
Header.php is included in About.php like this
```
include 'Header.php';
```
Now Header.php contains the code for the navigation menu.
```
* [Home](index.php)
* [About Us](About.php)
```
So now when I'm in Math.php and I press home it takes me to:
```
/Books/Samples/Math/index.php
```
Obviously the URL doesn't exist.
How i can make sure when the user is in Math.php it should go to `index.php` without including current path.
Header.php is included in all files.<issue_comment>username_1: You are using a **relative path**.
by typing "index.php" in the href attribute, you are pointing to a file named "index.php" in the current folder.
If you want to point to a file in the root folder, you need to use a slash `/`
```
href="//index.php"
href="//About.php"
```
This will take the user to the file you would like, also if you are unsure about what to use, just use absolute paths like this:
```
href="https://www.example.com//index.php"
href="https://www.example.com//About.php"
```
**EDIT**
Adding a slash works because by adding `/` you tell the browser to go to the root folder/website and start the path from there.
Let's say you are in `yourwebsite.com/current/path/file.html`.
A link to `/some/path/to/a-file.php` resolves to `yourwebsite.com/some/path/to/a-file.php`
But a link to `some/path/to/a-file.php` resolves to `yourwebsite.com/current/path/some/path/to/a-file.php`
Upvotes: 1 [selected_answer]<issue_comment>username_2: You could define includes and links relative to your site's base url.
The hrefs can be written like so:
```
* [Home](<?php echo $_SERVER['HTTP_HOST'].'/index.php';?>)
* [About Us](<?php echo $_SERVER['HTTP_HOST'].'/About.php';?>)
```
Upvotes: 1
|
2018/03/17
| 813 | 3,204 |
<issue_start>username_0: I am integrating SNS and Slack. I have created a slack app with incoming webhook enabled. I have got the webhook URL. I created a subscription for a SNS Topic with HTTPS protocol and set the Endpoint the webhookURL. Now the subscription is PendingConfirmation. I didnot receive any confirmation message, not in the destined channel.
How do I confirm the subscription?<issue_comment>username_1: You have create a lambda function that receives SNS feedback and POST it to your webhook URL.
When you create a subscription to your lambda topic you choose AWS Lambda as protocol and select the lambda that you just created.
More info about it here: <https://medium.com/cohealo-engineering/how-set-up-a-slack-channel-to-be-an-aws-sns-subscriber-63b4d57ad3ea>
Upvotes: 2 <issue_comment>username_2: The reason you're not seeing it in Slack is because the default [JSON format for SNS messages](https://docs.aws.amazon.com/sns/latest/dg/sns-message-and-json-formats.html#http-notification-json) doesn't conform to the format required by Slack:
>
> You have two options for sending data to the Webhook URL above:
>
>
> * Send a JSON string as the payload parameter in a POST request
> * Send a JSON string as the body of a POST request
>
>
> For a simple message, your JSON payload could contain a text property at minimum. This is the text that will be posted to the channel.
>
>
>
As another user suggested you can use an AWS Lambda function to facilitate this. There are free, public solutions available already, such as [this one](http://ashiina.github.io/2015/06/cloudwatch-lambda-slack) (which I did not author, and have not used...only including as a reference point).
Upvotes: 3 <issue_comment>username_3: You don't need to create a lambda function or create an HTTPS subscription with Slack.
On your slack channel, add the "email integration" app. Once done, Slack will provide you an email address with slack.com domain.
Emails sent to this address will be imported into your slack channel.
Then, on SNS create an email subscription and provide the slack email above.
Upvotes: 6 <issue_comment>username_4: I might be late on this topic but you can configure AWS Chatbot (slack application) to send all the notifications to your slack.
More info here : <https://aws.amazon.com/chatbot/>
Upvotes: 2 <issue_comment>username_5: You can confirm the subscription WITHOUT lambda. It is easy.
I found a way to integrate AWS SNS with slack **WITHOUT** `AWS Lambda` or `AWS chatbot`.
Follow the video which show all the step clearly.
<https://www.youtube.com/watch?v=CszzQcPAqNM>
Steps to follow:
* Create slack channel or use existing channel
* Create a work flow with selecting Webhook
* Create a variable name as `SubscribeURL`. The name is very important
* Add the above variable in the message body of the workflow
* Publish the workflow and get the url
* Add the above Url as subscription of the SNS
* You will see the subscription URL in the slack channel
* Follow the URl and complete the subscription
* Come back to the work flow and change the variable to `Message`
* The publish the message in SNS. you will see the message in the slack channel.
Upvotes: 4
|
2018/03/17
| 778 | 3,017 |
<issue_start>username_0: **If method A calls method B, should you test method B before testing method A in JUnit?**
I think method A is the answer since method B depends on method A. What are your thoughts?<issue_comment>username_1: You have create a lambda function that receives SNS feedback and POST it to your webhook URL.
When you create a subscription to your lambda topic you choose AWS Lambda as protocol and select the lambda that you just created.
More info about it here: <https://medium.com/cohealo-engineering/how-set-up-a-slack-channel-to-be-an-aws-sns-subscriber-63b4d57ad3ea>
Upvotes: 2 <issue_comment>username_2: The reason you're not seeing it in Slack is because the default [JSON format for SNS messages](https://docs.aws.amazon.com/sns/latest/dg/sns-message-and-json-formats.html#http-notification-json) doesn't conform to the format required by Slack:
>
> You have two options for sending data to the Webhook URL above:
>
>
> * Send a JSON string as the payload parameter in a POST request
> * Send a JSON string as the body of a POST request
>
>
> For a simple message, your JSON payload could contain a text property at minimum. This is the text that will be posted to the channel.
>
>
>
As another user suggested you can use an AWS Lambda function to facilitate this. There are free, public solutions available already, such as [this one](http://ashiina.github.io/2015/06/cloudwatch-lambda-slack) (which I did not author, and have not used...only including as a reference point).
Upvotes: 3 <issue_comment>username_3: You don't need to create a lambda function or create an HTTPS subscription with Slack.
On your slack channel, add the "email integration" app. Once done, Slack will provide you an email address with slack.com domain.
Emails sent to this address will be imported into your slack channel.
Then, on SNS create an email subscription and provide the slack email above.
Upvotes: 6 <issue_comment>username_4: I might be late on this topic but you can configure AWS Chatbot (slack application) to send all the notifications to your slack.
More info here : <https://aws.amazon.com/chatbot/>
Upvotes: 2 <issue_comment>username_5: You can confirm the subscription WITHOUT lambda. It is easy.
I found a way to integrate AWS SNS with slack **WITHOUT** `AWS Lambda` or `AWS chatbot`.
Follow the video which show all the step clearly.
<https://www.youtube.com/watch?v=CszzQcPAqNM>
Steps to follow:
* Create slack channel or use existing channel
* Create a work flow with selecting Webhook
* Create a variable name as `SubscribeURL`. The name is very important
* Add the above variable in the message body of the workflow
* Publish the workflow and get the url
* Add the above Url as subscription of the SNS
* You will see the subscription URL in the slack channel
* Follow the URl and complete the subscription
* Come back to the work flow and change the variable to `Message`
* The publish the message in SNS. you will see the message in the slack channel.
Upvotes: 4
|
2018/03/17
| 858 | 3,159 |
<issue_start>username_0: Why this doesnt work for me? I'm trying to select jobs that are performed by more than 2 employees in each billing unit (OJ).
```
select W.NAME as NAME,
W.OJ as OJ,
W.JOB as JOB,
W.MONTHLY_PAY as MONTHLY_PAY ,
SUM(W.OJ) AS "SUM"
from WORKER W
WHERE W.OJ > 2
GROUP BY W.IME, W.POSAO, W.MJESECNA_PLACA
```<issue_comment>username_1: You have create a lambda function that receives SNS feedback and POST it to your webhook URL.
When you create a subscription to your lambda topic you choose AWS Lambda as protocol and select the lambda that you just created.
More info about it here: <https://medium.com/cohealo-engineering/how-set-up-a-slack-channel-to-be-an-aws-sns-subscriber-63b4d57ad3ea>
Upvotes: 2 <issue_comment>username_2: The reason you're not seeing it in Slack is because the default [JSON format for SNS messages](https://docs.aws.amazon.com/sns/latest/dg/sns-message-and-json-formats.html#http-notification-json) doesn't conform to the format required by Slack:
>
> You have two options for sending data to the Webhook URL above:
>
>
> * Send a JSON string as the payload parameter in a POST request
> * Send a JSON string as the body of a POST request
>
>
> For a simple message, your JSON payload could contain a text property at minimum. This is the text that will be posted to the channel.
>
>
>
As another user suggested you can use an AWS Lambda function to facilitate this. There are free, public solutions available already, such as [this one](http://ashiina.github.io/2015/06/cloudwatch-lambda-slack) (which I did not author, and have not used...only including as a reference point).
Upvotes: 3 <issue_comment>username_3: You don't need to create a lambda function or create an HTTPS subscription with Slack.
On your slack channel, add the "email integration" app. Once done, Slack will provide you an email address with slack.com domain.
Emails sent to this address will be imported into your slack channel.
Then, on SNS create an email subscription and provide the slack email above.
Upvotes: 6 <issue_comment>username_4: I might be late on this topic but you can configure AWS Chatbot (slack application) to send all the notifications to your slack.
More info here : <https://aws.amazon.com/chatbot/>
Upvotes: 2 <issue_comment>username_5: You can confirm the subscription WITHOUT lambda. It is easy.
I found a way to integrate AWS SNS with slack **WITHOUT** `AWS Lambda` or `AWS chatbot`.
Follow the video which show all the step clearly.
<https://www.youtube.com/watch?v=CszzQcPAqNM>
Steps to follow:
* Create slack channel or use existing channel
* Create a work flow with selecting Webhook
* Create a variable name as `SubscribeURL`. The name is very important
* Add the above variable in the message body of the workflow
* Publish the workflow and get the url
* Add the above Url as subscription of the SNS
* You will see the subscription URL in the slack channel
* Follow the URl and complete the subscription
* Come back to the work flow and change the variable to `Message`
* The publish the message in SNS. you will see the message in the slack channel.
Upvotes: 4
|
2018/03/17
| 1,220 | 4,483 |
<issue_start>username_0: I'm trying to get all the conversations ordered by it last message, but when I use the `order_by` clausule, the conversations are repeated.
Query without order\_by:
```
conversaciones = Conversacion.objects.filter(usuarios=request.user)
```
Result (Grouped by Conversations but not ordered by the most recent last message first):
[](https://i.stack.imgur.com/hLb1x.png)
Query with order\_by:
```
conversaciones = Conversacion.objects.filter(usuarios=request.user).order_by('-mensaje__fechaEnvio')
```
Result:
[](https://i.stack.imgur.com/aptBm.png)
My models.py:
```
class Mensaje(models.Model):
remitente = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='remitente')
destinatario = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='destinatario')
cuerpo = models.TextField(validators=[MaxLengthValidator(750)])
leido = models.BooleanField(default=False)
fechaEnvio = models.DateTimeField(auto_now_add=True)
conversacion = models.ForeignKey('Conversacion', on_delete=models.CASCADE)
class Meta:
ordering = ['-fechaEnvio']
def __str__(self):
return str(self.remitente) + ' -> ' + str(self.destinatario)
class Conversacion(models.Model):
usuarios = models.ManyToManyField('Usuario', related_name='usuarios')
agresion = models.ForeignKey('Agresion', on_delete=models.CASCADE)
@property
def ultimoMensaje(self):
return self.mensaje_set.latest('fechaEnvio')
```<issue_comment>username_1: You have create a lambda function that receives SNS feedback and POST it to your webhook URL.
When you create a subscription to your lambda topic you choose AWS Lambda as protocol and select the lambda that you just created.
More info about it here: <https://medium.com/cohealo-engineering/how-set-up-a-slack-channel-to-be-an-aws-sns-subscriber-63b4d57ad3ea>
Upvotes: 2 <issue_comment>username_2: The reason you're not seeing it in Slack is because the default [JSON format for SNS messages](https://docs.aws.amazon.com/sns/latest/dg/sns-message-and-json-formats.html#http-notification-json) doesn't conform to the format required by Slack:
>
> You have two options for sending data to the Webhook URL above:
>
>
> * Send a JSON string as the payload parameter in a POST request
> * Send a JSON string as the body of a POST request
>
>
> For a simple message, your JSON payload could contain a text property at minimum. This is the text that will be posted to the channel.
>
>
>
As another user suggested you can use an AWS Lambda function to facilitate this. There are free, public solutions available already, such as [this one](http://ashiina.github.io/2015/06/cloudwatch-lambda-slack) (which I did not author, and have not used...only including as a reference point).
Upvotes: 3 <issue_comment>username_3: You don't need to create a lambda function or create an HTTPS subscription with Slack.
On your slack channel, add the "email integration" app. Once done, Slack will provide you an email address with slack.com domain.
Emails sent to this address will be imported into your slack channel.
Then, on SNS create an email subscription and provide the slack email above.
Upvotes: 6 <issue_comment>username_4: I might be late on this topic but you can configure AWS Chatbot (slack application) to send all the notifications to your slack.
More info here : <https://aws.amazon.com/chatbot/>
Upvotes: 2 <issue_comment>username_5: You can confirm the subscription WITHOUT lambda. It is easy.
I found a way to integrate AWS SNS with slack **WITHOUT** `AWS Lambda` or `AWS chatbot`.
Follow the video which show all the step clearly.
<https://www.youtube.com/watch?v=CszzQcPAqNM>
Steps to follow:
* Create slack channel or use existing channel
* Create a work flow with selecting Webhook
* Create a variable name as `SubscribeURL`. The name is very important
* Add the above variable in the message body of the workflow
* Publish the workflow and get the url
* Add the above Url as subscription of the SNS
* You will see the subscription URL in the slack channel
* Follow the URl and complete the subscription
* Come back to the work flow and change the variable to `Message`
* The publish the message in SNS. you will see the message in the slack channel.
Upvotes: 4
|
2018/03/17
| 1,213 | 3,931 |
<issue_start>username_0: I have some text of the form:
```
This is some text, and here's some in "double quotes"
"and here's a double quote:\" and some more", "text that follows"
```
The text contains strings within double quotes, as can be seen above. A double quoted may be escaped with a backslash (`\`). In the above, there are three such strings:
```
"double quotes"
"and here's a double quote:\" and some more"
"text that follows"
```
To extract these strings, I tried the regex:
```
"(?:\\"|.)*?"
```
However, this gives me the following results:
```
>>> preg_match_all('%"(?:\\"|.)*?"%', $msg, $matches)
>>> $matches
[
[ "double quotes",
"and here's a double quote:\",
", "
]
]
```
How can I correctly obtain the strings?<issue_comment>username_1: If you let the regex capture backslash characters *as characters*, then it will terminate your capture group on the " of \" (because the preceding \ is considered a single character). So what you need to do is allow \" to be captured, but not \ or " individually. The result is the following regex:
```
"((?:[^"\\]*(?:\\")*)*)"
```
[Try it here!](https://regex101.com/r/cbJyxH/1)
Explained in detail below:
```
" begin with a single quote character
( capture only what follows (within " characters)
(?: don't break into separate capture groups
[^"\\]* capture any non-" non-\ characters, any number of times
(?:\\")* capture any \" escape sequences, any number of times
)* allow the previous two groups to occur any number of times, in any order
) end the capture group
" make sure it ends with a "
```
Note that, in many languages, when feeding a regex string to a method to parse some text, you'll need to escape the backslash characters, quotes, etc. In PHP, the above would become:
```
'/"((?:[^"\\\\]*(?:\\\\")*)*)"/'
```
Upvotes: 1 <issue_comment>username_2: One way to do it would involve neg. lookbehinds:
```
".*?(?
```
---
Which in `PHP` would be:
```
php
$text = <<<TEXT
This is some text, and here's some in "double quotes"
"and here's a double quote:\" and some more", "text that follows"
TEXT;
$regex = '~".*?(?<!\\\\)"~';
if (preg_match_all($regex, $text, $matches)) {
print_r($matches);
}
?
```
---
This yields
```
Array
(
[0] => Array
(
[0] => "double quotes"
[1] => "and here's a double quote:\" and some more"
[2] => "text that follows"
)
)
```
---
See [**a demo on regex101.com**](https://regex101.com/r/mMsSE7/1/).
---
To let it span multiple lines, enable the `dotall` mode via
```
"(?s:.*?)(?
```
See [**a demo for the latter on regex101.com**](https://regex101.com/r/mMsSE7/2/) as well.
Upvotes: 2 <issue_comment>username_3: If you [`echo` your pattern, you'll see it's indeed passed as `%"(?:\"|.)*?"%`](https://eval.in/973798) to the regex parser. The single backslash will be treated as an escape character even by the regex parser.
So you need to add at least one more backslash if the pattern is inside single quotes to pass two backslashes to the parser (one for escaping backlsash) that the pattern will be: [`%"(?:\\"|.)*?"%`](https://eval.in/973802)
```
preg_match_all('%"(?:\\\"|.)*?"%', $msg, $matches);
```
Still this isn't a very efficient pattern. The question seems actually a [duplicate of this one](https://stackoverflow.com/questions/249791/regex-for-quoted-string-with-escaping-quotes).
There is a [better pattern available in this answer](https://stackoverflow.com/a/10786066) (what some would call [unrolled](http://www.softec.lu/site/RegularExpressions/UnrollingTheLoop)).
```
preg_match_all('%"[^"\\\]*(?:\\\.[^"\\\]*)*"%', $msg, $matches);
```
[See demo at eval.in](https://eval.in/973829) or compare steps with other patterns [in regex101](https://regex101.com/r/GjZrcT/2).
Upvotes: 2 [selected_answer]
|
2018/03/17
| 872 | 1,985 |
<issue_start>username_0: I often need to pluck properties out of an object
```
const obj = {a:1, b: 2, c: 3};
const plucked = pluck(obj, 'a', 'b'); // {a: 1, b:2}
```
However, this is not easy to do in TypeScript if you want type safety because I can't implement a function with the following signature in TypeScript, which I found on [TypeScript's manual](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#partial-readonly-record-and-pick).
```
declare function pick(obj: T, ...keys: K[]): Pick;
```
I couldn't get a version that compiled, here's a version I tried:
```
function pluck(obj: T, keys: K[]): Pick {
// Type '{}' is not assignable to type 'Pick'.
const ret: Pick = {};
for (let key of keys) {
ret[key] = obj[key];
}
return ret;
}
```
Does this mean I need to use ambient declarations and declare the function in JS?<issue_comment>username_1: I ended up using `any` on the object that I manipulate and TypeScript is happy allowing that as a return value. [See it in action](https://www.typescriptlang.org/play/#src=function%20pluck%3CT%2C%20K%20extends%20keyof%20T%3E(obj%3A%20T%2C%20keys%3A%20K%5B%5D)%3A%20Pick%3CT%2C%20K%3E%20%7B%0A%20%20%20%20let%20ret%3A%20any%20%3D%20%7B%7D%3B%0A%20%20%20%20for%20(let%20key%20of%20keys)%20%7B%20%0A%20%20%20%20%20%20%20%20ret%5Bkey%5D%20%3D%20obj%5Bkey%5D%3B%0A%20%20%20%20%7D%0A%20%20%20%20return%20ret%3B%20%0A%7D%0A%0Aconst%20less%20%3D%20pluck(%7B%20a%3A%201%2C%20b%3A%20'2'%2C%20c%3A%20true%20%7D%2C%20%5B'a'%2C%20'c'%5D)%3B%0A%0A%0A%0A%0A)
```
function pluck(obj: T, keys: K[]): Pick {
const ret: any = {};
for (let key of keys) {
ret[key] = obj[key];
}
return ret;
}
const less = pluck({ a: 1, b: '2', c: true }, ['a', 'c']);
```
Upvotes: 3 <issue_comment>username_2: Here's an alternative option:
```
function pluck(objs: T, keys: K[]): Pick {
return keys.reduce((result, key) =>
Object.assign(result, {[key as string]: objs[key]}), {}) as Pick;
}
```
Upvotes: 2
|
2018/03/17
| 718 | 1,512 |
<issue_start>username_0: ```
var a = "gsdgtrshghf";
function reverseString(strr){
if (!strr.length){
var result="";
for(var i=strr.length;i>0;i++){
var a=strr.chatAt(i);
result+=a;
}
}return result;
}
console.log(reverseString(a))
```
When I tried to run it it returned me "undefined". I wonder what's the problem here.<issue_comment>username_1: I ended up using `any` on the object that I manipulate and TypeScript is happy allowing that as a return value. [See it in action](https://www.typescriptlang.org/play/#src=function%20pluck%3CT%2C%20K%20extends%20keyof%20T%3E(obj%3A%20T%2C%20keys%3A%20K%5B%5D)%3A%20Pick%3CT%2C%20K%3E%20%7B%0A%20%20%20%20let%20ret%3A%20any%20%3D%20%7B%7D%3B%0A%20%20%20%20for%20(let%20key%20of%20keys)%20%7B%20%0A%20%20%20%20%20%20%20%20ret%5Bkey%5D%20%3D%20obj%5Bkey%5D%3B%0A%20%20%20%20%7D%0A%20%20%20%20return%20ret%3B%20%0A%7D%0A%0Aconst%20less%20%3D%20pluck(%7B%20a%3A%201%2C%20b%3A%20'2'%2C%20c%3A%20true%20%7D%2C%20%5B'a'%2C%20'c'%5D)%3B%0A%0A%0A%0A%0A)
```
function pluck(obj: T, keys: K[]): Pick {
const ret: any = {};
for (let key of keys) {
ret[key] = obj[key];
}
return ret;
}
const less = pluck({ a: 1, b: '2', c: true }, ['a', 'c']);
```
Upvotes: 3 <issue_comment>username_2: Here's an alternative option:
```
function pluck(objs: T, keys: K[]): Pick {
return keys.reduce((result, key) =>
Object.assign(result, {[key as string]: objs[key]}), {}) as Pick;
}
```
Upvotes: 2
|
2018/03/17
| 917 | 2,545 |
<issue_start>username_0: In the following JSON data, I want to access `'lon'` and `'lat'` in `'coord'`. I know `data.coord` would give me `[ 'lon', 'lat' ]`, but how can I get the values belonging to each?
Here's my JSON data:
```
var data = {
"coord": {
"lon": 159,
"lat": 35
},
...
};
```<issue_comment>username_1: You could accesss them like this:
```js
var data = { "coord":{ "lon":159, "lat":35 }, "weather":[ { "id":500, "main":"Rain", "description":"light rain", "icon":"https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F10n.png?1499366021399" } ], "base":"stations", "main":{ "temp":22.59, "pressure":1027.45, "humidity":100, "temp_min":22.59, "temp_max":22.59, "sea_level":1027.47, "grnd_level":1027.45 }, "wind":{ "speed":8.12, "deg":246.503 }, "rain":{ "3h":0.45 }, "clouds":{ "all":92 }, "dt":1499521932, "sys":{ "message":0.0034, "sunrise":1499451436, "sunset":1499503246 }, "id":0, "name":"", "cod":200 };
console.log('Lon',data.coord.lon);
console.log('Lat',data.coord.lat);
//Also you can do that using object destructuring in es6 like this:
var {lon,lat} = data.coord;
console.log('Lon',lon);
console.log('Lat',lat);
```
Checkout MDN for more about objects and properties:
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects>
Check out [Object destructuring](https://developer.mozilla.org/el/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
Upvotes: 2 [selected_answer]<issue_comment>username_2: `data.coord` won't give you `[ 'lon', 'lat' ]` array, rather it would give you `{ "lon": 159,"lat": 35 }` object.
You can get their values just like you would get value of any object like: `data.coord.lat` and `data.coord.lon`
So something like
`var latitude = data.coord.lat;
var longitude = data.coord.lon`
**EDIT:**
Similarly, for weather you can access weather using `data.weather`, however thing to note is that weather is an array. So, you can get hold of 1st element using index=0.
Effectively, you'll write, `var myWeatherObject = data.weather[0];` //0 is index of 1st element
Again, to access individual weather properties, you can use:
`myWeatherObject.id`, `myWeatherObject.main`, `myWeatherObject.description` and `myWeatherObject.icon`
Upvotes: 1 <issue_comment>username_3: You can also access the values with this syntax `data['coord']`.
With this syntax you can run through the json file searching for a corresponding key.
```
for(let key in json) {
if(key==='coord'){
//do stuff
}
}
```
Upvotes: 0
|
2018/03/17
| 724 | 2,664 |
<issue_start>username_0: I have 3 entities: Tutors, Students, Courses
Tutors teach many courses
Students can be assigned to many courses that are taught by many tutors
Tutors and students need to be able to log into the system
I would like to represent this design using the following tables:
```
users
- id
- username
- password
- first_name
- last_name
- email
- password
- phone
- role_id (Student or Tutor or Admin)
- created
- modified
roles (Student, Tutor)
- id
- name
- created
- modified
courses (The courses that Tutors can teach and that Students can be assigned to)
- id
- name
- created
- modified
users_courses
- id
- user_id
- course_id
- created
- modified
```
The problem I have with the above design (users\_courses table) is that, let's say we have Tutor A and Tutor B that teach Math. If student X is registered to that math course we can't know if student X is being tutored by Tutor A or Tutor B.
I would really like to be able to use a single users table to keep all the users to make things simple.
Any advice please?<issue_comment>username_1: The problem is that you want to handle students and teachers differently (students enroll in a course taught by a specific teacher) but you modeled them the same (they're just users).
Instead of `roles`, create subtypes of `users`. Create tables for `teachers` and `students` - you can reuse the primary keys from `users`, but you'll be able to handle subtype-specific attributes and relationships.
While it's possible to get away with only those entity sets, I suggest you add the concept of a section as well. It has different names in different systems or parts of the world, but most school systems I've seen have something like it to represent a partition of a course's students with an associated teacher.
```
users
- id PK
- username
- password
- first_name
- last_name
- email
- password
- phone
- created
- modified
students
- user_id PK FK
teachers
- user_id PK FK
courses
- id PK
- name
- created
- modified
sections
- section_id PK
- teacher_id FK
- course_id FK
- created
- modified
students_sections
- student_id PK FK
- section_id PK FK
- created
- modified
```
In a real world system, you'll also need to take time into account - students and teachers normally attend different courses in different years or semesters.
Upvotes: 2 <issue_comment>username_2: I would simply add the βtutorβ to the courses table since itβs essential element for a course to know whose is teaching it/tutor.
Then use either the users table or user\_courses to join/match and pull the info you want.
```
**Courses**
- id
- name
-tutorID
- created
- modified
```
Upvotes: 0
|
2018/03/17
| 407 | 1,472 |
<issue_start>username_0: We are having projects created with aws codestar. these were working fine. but from today we are facing following issue:
>
> Unable to upload artifact None referenced by CodeUri parameter of GetCompanyRecords resource.
>
>
> zip does not support timestamps before 1980
>
>
>
Now when i removed aws-sdk module again it works fine. but when i add it again build fails. i am pretty much worried about this. Here is my lambda function.
```
GetCompanyRecords:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs6.10
Role:
Fn::ImportValue:
!Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
Timeout: 10
Events:
PostEvent:
Type: Api
Properties:
Path: /getCompanyRecords
Method: post
```
thanks in advance<issue_comment>username_1: At the moment following patch fixed my issue:
I added following lines to buildspec.yml after 'npm install'
-ls $CODEBUILD\_SRC\_DIR
-find $CODEBUILD\_SRC\_DIR/node\_modules -mtime +10950 -exec touch {} ;
As i was having issue just by adding aws-sdk so i want aws to fix to this issue. I am really disappointed aws-sdk is not working with aws..
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have forgotten to initialize the codebase with git:). It means It's trying to create a zip from git's head but failing
```
rm -rf .git
git init
git add .
git commit -am 'First commit'
```
Upvotes: 1
|
2018/03/17
| 290 | 1,018 |
<issue_start>username_0: i have a list of names that return from my controler, this list return a array string from my mongodb database.I try pass this list to a list javascript.
My javascript code until now:
```html
var listNames = [];
@foreach(var itens in @Model.ListaNames){
listNames .push(itens.name);
}
```
But i can't access my listaNames inside this foreach.<issue_comment>username_1: At the moment following patch fixed my issue:
I added following lines to buildspec.yml after 'npm install'
-ls $CODEBUILD\_SRC\_DIR
-find $CODEBUILD\_SRC\_DIR/node\_modules -mtime +10950 -exec touch {} ;
As i was having issue just by adding aws-sdk so i want aws to fix to this issue. I am really disappointed aws-sdk is not working with aws..
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have forgotten to initialize the codebase with git:). It means It's trying to create a zip from git's head but failing
```
rm -rf .git
git init
git add .
git commit -am 'First commit'
```
Upvotes: 1
|
2018/03/17
| 2,000 | 7,972 |
<issue_start>username_0: I have done a javascript form validation using the following code.I'm not sure whether it is the correct way of validating form.
```
const signup=()=>{
let name=document.querySelector("#u_name").value;
let email=document.querySelector("#email_id").value;
let password=document.querySelector("#pwd").value;
let confirmPassword=document.querySelector("#confirm_pwd").value;
let i=0;
if((name==""||email=="")||(password==""||confirmPassword==""))
{
document.querySelector("#empty-field").innerHTML="*Fill all required fields";
i++;
}
else
{
if(name.length<3)
{
document.querySelector("#u_name").style.borderColor="red";
document.querySelector("#user-errmsg").innerHTML="*Enter valid user name";
i++;
}
else
{
document.querySelector("#u_name").style.borderColor="#ced4da";
document.querySelector("#user-errmsg").innerHTML="";
i;
}
if(email.length<6)
{
document.querySelector("#email_id").style.borderColor="red";
document.querySelector("#email-errmsg").innerHTML="*Enter valid email id";
i++;
}
else
{
document.querySelector("#email_id").style.borderColor="#ced4da";
document.querySelector("#email-errmsg").innerHTML="";
i;
}
if(password.length<6 && confirmPassword.length<6)
{
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Password must be atleast 6 digits long";
i++;
}
else if(password.length<6 && confirmPassword.length>=6)
{
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Password must be atleast 6 digits long";
i++;
}
else if(password.length>=6 && confirmPassword.length>=6)
{
if(password!= confirmPassword)
{
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Both fields must have the same password";
i++;
}
else
{
document.querySelector("#pwd").style.borderColor="#<PASSWORD>";
document.querySelector("#confirm_pwd").style.borderColor="#<PASSWORD>";
document.querySelector("#pwd-errmsg").innerHTML="";
i;
}
}
else
{
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Both fields must have the same password";
i++;
}
document.querySelector("#empty-field").innerHTML="";
}
if(i==0)
return true;
else
return false
}
```
Is it a good practice to write too many if else condition? If not, how can I rewrite it?
//ignore
Looks like stackoverflow doesn't allow posting this question with less details :/ So I have to add some more it seems.<issue_comment>username_1: Your concern about using too many if/else statements during the scope of a single method is a valid one. It is not wrong, but makes the code hard to read/understand and difficult to debug/troubleshoot if something goes wrong. Here are some advices to refactor this method:
1. It seems that it isn't doing a signup. You're validating input data so I would recommend to rename it to `validate` or something similar.
2. Method is doing too much. It's querying for the data, it's performing validations and also rendering messages and adapting styles. I advice to divide and conquer. Make this method just a validation one.
3. Create small functions that performs a single validation. As an example `validateEmailAddress()` or `validatePassword()`. Once you start moving pieces around, you will have less if/elseif statements.
There are more things you can do but the key is on decoupling responsibilities. If you try that I believe your if/elseif amount will decrease.
There is another strategy that I use all the time to remove if/else nesting levels which is commonly called as [early return](http://blog.timoxley.com/post/47041269194/avoid-else-return-early).
Upvotes: 1 <issue_comment>username_2: Your code would benefit from extracting everything into functions:
```
const get = selector => document.querySelector(selector);
const checker = (check, msg) => (el, error) => {
if(check(get(el).value)){
get(el).style.color = "green";
get(error).innerHTML = "";
return true;
} else {
get(el).style.color = "red";
get(error).innerHTML = msg;
}
};
const minLength = length => checker(
v => v.length >= length,
`Too short! You need at least ${length} chars`
);
const maxLength = length => checker(
v => v.length <= length,
`Too long! You need less than ${length} chars`
);
const equal = (a, b, err) => checker(v => v === get(b).value, "They must be equal")(a, err);
```
Seems quite long right? But now you can do:
```
return (
minLength(6)("#u_name", "#user-errmsg") &&
maxLength(12)("#u_name", "#user-errmsg") &&
minLength(6)("#email_id", "#email-errmsg") &&
equal("#confirm_pwd", "#pwd", "#pwd-errmsg")
)
```
Upvotes: 1 <issue_comment>username_3: use jquery plugin <https://jqueryvalidation.org/>
Below is the example to use:
```js
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "myform"
$("form[name='myform']").validate({
// Specify validation rules
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 8 characters long"
},
email: "Please enter a valid email"
},
submitHandler: function(form) {
form.submit();
}
});
});
```
```html
Sign Up
-------
First Name
Last Name
Email
Password
Submit
```
CSS to highlight error
```css
label.error {
color: red;
margin-top:-10px;
margin-bottom:15px;
}
```
Upvotes: 0 <issue_comment>username_4: You don't need any javascript validation or extra library, just use all the attributes that is needed on the fields and correct type. use "constraint validation". Only thing you need to check is if the password match (showing you how below)
Study the input attributes here: <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input>
```js
function validatePassword(){
const pwd1 = document.getElementById("pwd")
const pwd2 = document.getElementById("confirm_pwd")
pwd1.setCustomValidity(pwd1.value !== pwd2.value
? "Passwords Don't Match"
: ""
)
}
document.getElementById("pwd").oninput = validatePassword
document.getElementById("confirm_pwd").oninput = validatePassword
```
```css
input:not([type=submit]):valid {
border: 1px solid lime;
}
```
```html
name
email
pwd
repeat pwd
```
Personally I feel very tired off repeating my email and/or password. If i get it wrong i will do it over again or press that "forgot your password" link. I can see my email address and with the help of autocomplete it's a lower risk i get my email wrong. You don't need that b/c every other website dose it. if that is out of the way you don't need any javascript at all...
Upvotes: 0
|
2018/03/17
| 581 | 2,176 |
<issue_start>username_0: When I return encrypted or decrypted string in Base64 format it can`t resolve`BASE64Encoder()`and`BASE64Dencoder()`. How can I resolve it?
```
import javax.crypto.*;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
class DesEncrypter {
Cipher ecipher;
Cipher dcipher;
public DesEncrypter(SecretKey key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
public String encrypt(String str) throws UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
public String decrypt(String str) throws IOException, IllegalBlockSizeException, BadPaddingException {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}
```
}<issue_comment>username_1: try to use the java9 one, not the sun.misc...:
<https://docs.oracle.com/javase/9/docs/api/java/util/Base64.Decoder.html>
Upvotes: 2 <issue_comment>username_2: You should not use sun.misc in general. Those classes are internal to the JDK and may be removed with new versions of Java (as happened here).
I recommend using a third party library like Apache Codecs. There are a bunch of utility classes that would make it unneccessary to do any of the code you listed.
**Site**: <https://commons.apache.org/proper/commons-codec/>
**Documentation**: <https://commons.apache.org/proper/commons-codec/archives/1.11/apidocs/org/apache/commons/codec/binary/Base64.html>
Upvotes: 2 <issue_comment>username_3: I had the same problem today while I was running JDK 8 on Intellij and a maven task wouldn't compile the project properly, giving me the same error. Solution was: I had JDK10 folder setup on my Environment Variables... just changed to JDK8 and everything compiled just fine.
Upvotes: 2
|
2018/03/17
| 453 | 1,674 |
<issue_start>username_0: I'm trying to understand how the code below, which is from Redux examples [TODOMVC](https://github.com/reactjs/redux/blob/master/examples/todomvc/src/containers/App.js), can be written using the class notation.
The code is
```
const App = ({todos, actions}) => (
```
I tried the following but it doesn't work, I get `Warning: App(...): When calling super() in`App`, make sure to pass up the same props that your component's constructor was passed.`
```
class App extends React.Component {
constructor({todos, actions}) {
super({todos, actions});
this.todos = todos;
this.actions = actions;
}
render() {
return(
)
}
}
```<issue_comment>username_1: You can simply do what React asks, pass the whole props to the superclass and get out the properties you want explicitly
```js
class App extends React.Component {
constructor(props) {
super(props);
this.todos = props.todos;
this.actions = props.actions;
}
render() {
return(
Actions: {this.actions}
=======================
{/\*
\*/}
)
}
}
ReactDOM.render(, document.getElementById('app'))
```
```html
```
Upvotes: 0 <issue_comment>username_2: Whatever is passed to `App` is `props`. And `({ todos, actions })` is just destructuring from `props`. This should work:
```
class App extends React.Component {
render() {
const { todos, actions } = this.props;
return(
)
}
}
```
By setting `this.todo = todos` in constructor, you're setting an instance level property. Which means if the props changes later, `Header` and `MainSection` will not be updated.
Upvotes: 3 [selected_answer]
|
2018/03/17
| 418 | 1,733 |
<issue_start>username_0: I have a meteor project that runs a python script once a day to query an API and save the results to a JSON file in `private`. The meteor server watches that JSON file for changes. When the file changes, the server reads and parses the file and updates a collection accordingly.
The problem is that the assets in `private` are loaded at meteor startup and copied into a different asset folder as read-only, and thus the script can't make changes to the file.
I could maybe change the permissions on that asset destination folder but that seems hacky. I don't think assets in `private` are intended to be dynamic, anyways. Anybody know how I can accomplish this flow?
* Meteor server kicks off python script once per day
* Script queries API, saves results to JSON file on server
* Meteor server reads JSON file and updates collection<issue_comment>username_1: The simplest solution may be for the Python script to write its JSON to a Mongo database. Then Meteor can automatically subscribe to any changes made to that collection.
Upvotes: 2 <issue_comment>username_2: Here is what I ended up doing:
Instead of having the meteor app kick off the python script daily, I just put the python script on the host's file system (outside of the meteor app bundle) and created a cron job on the host to run it daily. The JSON output file was saved to the host's file system.
Then, in my meteor app, I created a file watch on the output JSON that triggered a file read.
I was running into some issues with Meteor Up (mup), so see my other answered question [here](https://stackoverflow.com/questions/49443065/how-do-i-read-a-file-from-the-local-file-system-from-inside-a-meteor-app).
Upvotes: 1 [selected_answer]
|
2018/03/17
| 673 | 2,290 |
<issue_start>username_0: Whenever I try to run my discord.js bot, my code editor says that it couldn't connect to discord via discord RPC. I've looked around and saw nothing that can help me. Can anyone help?<issue_comment>username_1: Discord just had an outage.
You can follow up Discord Updates [here](https://status.discordapp.com/).
If you wanna read why Discord was offline just now, [here](https://status.discordapp.com/incidents/2cb5jc53jq28) is the direct link, or here:
>
> **Monitoring**
>
> We've addressed the underlying issue and services are
> recovering. Everybody should be able to reconnect and use Discord
> normally, but some operations may be a little slow as the system fully
> recovers. The team is keeping an eye on things.
>
> *Posted less than a minute ago. Mar 17, 2018 - 13:12 PDT*
>
>
> **Identified**
>
> We've identified that
> a MongoDB database is performing badly. We're taking steps to reduce
> load against the cluster now.
>
> *Posted 21 minutes ago. Mar 17, 2018 - 12:51 PDT*
>
>
> **Investigating**
>
> We've become aware of an issue affecting
> connecting to Discord. We're looking into it now and will update as
> soon as we know more.
>
> *Posted 38 minutes ago. Mar 17, 2018 - 12:34 PDT*
>
>
>
Upvotes: 3 [selected_answer]<issue_comment>username_2: Just ran across this issue now. If you are using [discord-rich-presence](https://www.npmjs.com/package/discord-rich-presence), you can edit ipc.js under `discord-rpc/src/transports` in node-modules. Discord rich presence also installs discord-rpc with it.
The problem is that the package is throwing an error whenever you cannot connect. On line 32, inside of the else statement, there is this code.
`else {reject(new Error('Could not connect'));}`
As you can see, it is throwing an error when the connection is invalid. For some reason, a try, catch does not fix this. The best thing to do in this case would be to delete -
`reject(new Error('Could not connect'));`
After doing this, you can either log something inside of that else statement, or just leave it blank.This package is a very simple alternative to `discord-rpc`, but it has been inactive for a while now. So I doubt they will merge any new pull requests. Should work now ( :
Upvotes: 1
|
2018/03/17
| 794 | 2,854 |
<issue_start>username_0: hello i am trying to make a countdown which refreshes the page when the countdown finished
however the timer is not refreshing page when countdown ends it start more counting in clock wise
for example the timer has to reload the page after 3 , 2 ,1 , but it goes like 3, 2, 1 , 1, 2 ,3 and so on below is my code
```
php if (isset($alert)) { ?
$('#alert').modal('show');
php } ?
$("#DateCountdown").TimeCircles();
$("#CountDownTimer").TimeCircles({ time: { Days: { show: false }, Hours: { show: false } }});
$("#PageOpenTimer").TimeCircles();
var updateTime = function(){
var date = $("#date").val();
var time = $("#time").val();
var datetime = date + ' ' + time + ':00';
$("#DateCountdown").data('date', datetime).TimeCircles().start();
}
$("#date").change(updateTime).keyup(updateTime);
$("#time").change(updateTime).keyup(updateTime);
$(".startTimer").click(function() {
$("#CountDownTimer").TimeCircles().start();
});
$(".stopTimer").click(function() {
$("#CountDownTimer").TimeCircles().stop();
});
$(".fadeIn").click(function() {
$("#PageOpenTimer").fadeIn();
});
$(".fadeOut").click(function() {
$("#PageOpenTimer").fadeOut();
});
```<issue_comment>username_1: ```
setTimeout(function() {
window.location.reload();
}, 1500)
```
Swap out the 1500 for the time in ms that you want to pass before reloading the page.
Upvotes: 2 <issue_comment>username_2: Can't see timeout/interval routines in your code, so I'll show my example to do what you want:
```js
// your timeout in seconds
var timeSec = 10;
// fix countdown start time in seconds
var timeStart = parseInt((new Date()).getTime() / 1000);
// function to check if time is up
function TimeCheck() {
// get time left in seconds
var timeLeft = timeSec - (parseInt((new Date()).getTime() / 1000) - timeStart);
// checking if time is up
if(timeLeft > 0) {
// if time is not up yet
// ... do whatever you want to display / refresh time left to reload page ...
// set "check timeout" for next check
setTimeout(TimeCheck, 1000);
}
else {
// reload page and don't set "check timeout" again
window.location.reload();
}
}
// initial timeout start
cTimeout = setTimeout(TimeCheck, 1000);
```
Using `setTimeout()` instead of `setInterval()` prevents multiple instances of callback functions to stuff in execution queue.
Upvotes: 0 <issue_comment>username_2: Maybe you mean this code to solve the problem?
```
$("#CountDownTimer")
.TimeCircles({count_past_zero: false}) // prevent countdown below zero
.addListener(countdownComplete); // add "countdown complete listener"
function countdownComplete(unit, value, total){
if(total <= 0){
// ... make your page refresh ...
}
}
```
Upvotes: 0
|
2018/03/17
| 621 | 2,287 |
<issue_start>username_0: I'm wondering if this is a good or bad way of using pointers and new.
I don't want to store more than I need, so therefore I make a buffer of 50 and the user write their username, and I use strlen to count it and store the length + 1. Do I have to delete username afterwards? Should I do this different?
Without using string.
```
void Accounts::newUser()
{
char buffer[50]; char *username;
cout << "username: "; cin.getline(buffer, 50);
username = new char[strlen(buffer) + 1]; strcpy(username, buffer);
// User(char *username) <- parameter
accountList->add(new User(username));
}
```<issue_comment>username_1: ```
setTimeout(function() {
window.location.reload();
}, 1500)
```
Swap out the 1500 for the time in ms that you want to pass before reloading the page.
Upvotes: 2 <issue_comment>username_2: Can't see timeout/interval routines in your code, so I'll show my example to do what you want:
```js
// your timeout in seconds
var timeSec = 10;
// fix countdown start time in seconds
var timeStart = parseInt((new Date()).getTime() / 1000);
// function to check if time is up
function TimeCheck() {
// get time left in seconds
var timeLeft = timeSec - (parseInt((new Date()).getTime() / 1000) - timeStart);
// checking if time is up
if(timeLeft > 0) {
// if time is not up yet
// ... do whatever you want to display / refresh time left to reload page ...
// set "check timeout" for next check
setTimeout(TimeCheck, 1000);
}
else {
// reload page and don't set "check timeout" again
window.location.reload();
}
}
// initial timeout start
cTimeout = setTimeout(TimeCheck, 1000);
```
Using `setTimeout()` instead of `setInterval()` prevents multiple instances of callback functions to stuff in execution queue.
Upvotes: 0 <issue_comment>username_2: Maybe you mean this code to solve the problem?
```
$("#CountDownTimer")
.TimeCircles({count_past_zero: false}) // prevent countdown below zero
.addListener(countdownComplete); // add "countdown complete listener"
function countdownComplete(unit, value, total){
if(total <= 0){
// ... make your page refresh ...
}
}
```
Upvotes: 0
|
2018/03/17
| 924 | 3,097 |
<issue_start>username_0: I'm using <https://github.com/sloria/cookiecutter-flask> for a project and I'm trying to add a javascript function to a js file that's bundled by webpack and access it from the html. I think I'm missing something basic.
Source files for background:
* <https://github.com/sloria/cookiecutter-flask/blob/master/%7B%7Bcookiecutter.app_name%7D%7D/webpack.config.js>
* <https://github.com/sloria/cookiecutter-flask/blob/master/%7B%7Bcookiecutter.app_name%7D%7D/assets/js/plugins.js>
I'm adding the following code to plugins.js:
```
function foo () {
console.log('bar')
}
```
And trying to call it from an html document to test as follows
```
foo();
```
I can see that my function got bundled, but I can't access it.
[](https://i.stack.imgur.com/mqc4j.png)
And here's the error I get:
[](https://i.stack.imgur.com/Y59R3.png)
I already had to add expose-loader to my webpack.config.js to get jquery to work as per [this issue](https://github.com/sloria/cookiecutter-flask/issues/185):
[](https://i.stack.imgur.com/KoCFu.png)<issue_comment>username_1: In my experiene, when I am using Webpack, I am bundling code into modules, which encapsulates them to that module's scope. Code that I want to be available outside of the module I explicitly `export`, and then `import` or `require` it into the new scope where I want to access it.
It sounds like you are instead wishing for some of your code to be accessible in the *global* scope, to access it directly from your markup. To do this in the browser, your best bet is to attach it directly to the `Window` object. Probably first checking to make sure that you aren't overwriting something already at that namespace:
```
function foo() {
console.log('bar!');
}
if (!Window.foo) {
Window.foo = foo;
} else {
console.warn('Foo is already assigned!');
}
```
That said, I would recommend you avoid developing in this manner-- polluting the global namespace is usually not a great pattern, and leads to a lot of potential conflict. If you *must* work in this manner, at least assign an object to a namespace attached to `Window` where you can put your applications functionality without risking conflicting with other `Window` properties:
```
Window.myApp = {
foo: function () {
console.log('bar!');
}
}
Window.myApp.printGreeting = function () {
console.log('Hello!');
}
// ...etc
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I couldn't figure out how to get ES6 syntax to work in the file, kept running into this error:
[](https://i.stack.imgur.com/3ol7u.png)
Here's a workaround based on this [related question](https://stackoverflow.com/questions/12093192/how-to-create-a-jquery-function-a-new-jquery-method-or-plugin)
[](https://i.stack.imgur.com/7pE3f.png)
Upvotes: 0
|
2018/03/17
| 907 | 3,215 |
<issue_start>username_0: Right now, I'm working with several lines that follow a format of [longitude, latitude] date time text and I'm not sure how to pull just the latitude and just the longitude.
What I tried doing was splitting the overall file into lines (this part worked fine), then splitting the lines into words (which worked), but now I'm unable to pull longitude as a float as I'm getting a Traceback ValueError where it's saying that it can't convert a string to a float.
At first I thought the problem was that words (in this case, WordZ) line looked something like `"['45.696179999999998,', '-122.51231420000001]', '3', '2011-09-01', '17:06:53',[...]"` and so logically trying to pull the long as a float by making `long = float(WordZ[0])` was impossible because WordZ ended with a comma.
So I tried doing `#long = float(WordZ[0].rstrip(","))`. But I'm still getting the same can't convert string to float error.
And to make matters worse, I have no idea why this is happening because the comma is for sure getting removed as per the output box:
```
Traceback (most recent call last):
File "C:/Users/claym/Desktop/Assignment3/assign3.py", line 28, in
long = float(WordZ[0].rstrip(","))
.ValueError: could not convert string to float:
41.29866963
Process finished with exit code 1
```
What do I need to do to fix this problem?<issue_comment>username_1: In my experiene, when I am using Webpack, I am bundling code into modules, which encapsulates them to that module's scope. Code that I want to be available outside of the module I explicitly `export`, and then `import` or `require` it into the new scope where I want to access it.
It sounds like you are instead wishing for some of your code to be accessible in the *global* scope, to access it directly from your markup. To do this in the browser, your best bet is to attach it directly to the `Window` object. Probably first checking to make sure that you aren't overwriting something already at that namespace:
```
function foo() {
console.log('bar!');
}
if (!Window.foo) {
Window.foo = foo;
} else {
console.warn('Foo is already assigned!');
}
```
That said, I would recommend you avoid developing in this manner-- polluting the global namespace is usually not a great pattern, and leads to a lot of potential conflict. If you *must* work in this manner, at least assign an object to a namespace attached to `Window` where you can put your applications functionality without risking conflicting with other `Window` properties:
```
Window.myApp = {
foo: function () {
console.log('bar!');
}
}
Window.myApp.printGreeting = function () {
console.log('Hello!');
}
// ...etc
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I couldn't figure out how to get ES6 syntax to work in the file, kept running into this error:
[](https://i.stack.imgur.com/3ol7u.png)
Here's a workaround based on this [related question](https://stackoverflow.com/questions/12093192/how-to-create-a-jquery-function-a-new-jquery-method-or-plugin)
[](https://i.stack.imgur.com/7pE3f.png)
Upvotes: 0
|
2018/03/17
| 780 | 2,352 |
<issue_start>username_0: I am trying to test if my API routes are working using nock.js to mock url requests.
My routing file routes according to the following logic:
```
app.get('/api/study/load/:id', abc.loadStudy );
```
'loadStudy' method in 'abc.js' is used to handle the below particular GET request. Hence, any GET request from a browser has a 'params' key with 'id' parameter that replaces ':id' in the URL. However, when I try to mock this GET request using nock.js I'm not able to pass this 'id' parameter in the request.
```
var abc = require('G:\\project\\abc.js');
var nock = require('nock');
var api = nock("http://localhost:3002")
.get("/api/test/load/1")
.reply(200, abc.loadStudy);
request({ url : 'http://localhost:3002/api/study/load/1', method: 'GET', params: {id : 1}}, function(error, response, body) { console.log(body);} );
```
My method makes use of 'params' key that is sent with request which I'm not able to mock. Printing *'req'* in the below code just gives *'/api/test/load/1'* . How can I add *'params'* to the GET request?
```
loadStudy = function(req, res) {
console.log(req);
var id = req.params.id;
};
```<issue_comment>username_1: As per the [official docs](https://github.com/node-nock/nock#specifying-request-query-string), you can specify querystring by
```
var api = nock("http://localhost:3002")
.get("/api/test/load/1")
.query({params: {id : 1}})
.reply(200, abc.loadStudy);
```
Hope it helps.
Revert in case of any doubts.
Upvotes: 4 <issue_comment>username_2: I just ran into a similar problem, and tried Sunil's answer. As it turns out, all you have to do is provide a query object you want to match, not an object with params property.
I am using nock version 11.7.2
```js
const scope = nock(urls.baseURL)
.get(routes.someRoute)
.query({ hello: 'world' })
.reply(200);
```
Upvotes: 3 <issue_comment>username_3: Another way to solve this for a generic url, is to use regex:
```
// For:
app.get('/api/study/load/:id', handler);
// You can mock:
nock(baseURL).get(/\/api\/study\/load\/[a-zA-Z0-9\-]*/g)
// For a more complex example:
app.get('/api/study/load/:some-guid?param1=val1¶m2=val2', handler);
// You can mock:
nock(baseURL).get(/\/api\/study\/load\/[a-zA-Z0-9\-]*\?param1=val1¶m2=val2/g)
```
Upvotes: 2
|
2018/03/17
| 1,326 | 4,846 |
<issue_start>username_0: I have a .NET Core 2.0 website, running on Linux, listening on port 5000, behind an NGinX reverse proxy, which is listening on port 80 and 442. NGinX is configured to redirect HTTP traffic to HTTPS, and handle all communication over HTTPS. The NGinx Reverse Proxy and Asp.Net Core app are within their own docker containers, on a shared network.
This setup is currently working as described.
However, I would now like to Authenticate my users against our Azure Active Directory. I have run into a problem and don't know where to go from here.
First, let me show you how I have most of this configured, and then I'll explain my error.
**NGinx (nginx.conf)**
```
worker_processes 2;
events { worker_connections 1024; }
http {
sendfile on;
upstream docker-dotnet {
server mycomp_prod:5000;
}
server {
listen 80;
server_name sales.mycompany.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name sales.mycompany.com;
ssl_certificate /etc/nginx/ssl/combined.crt;
ssl_certificate_key /etc/nginx/ssl/salesmycompany.key;
location / {
proxy_pass http://docker-dotnet;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}
}
```
**Dotnet:Startup.cs ConfigureServices()**
```
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAd(options => Configuration.Bind("AzureAd", options))
.AddCookie();
```
**Dotnet:Startup.cs Configure()**
```
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseAuthentication();
```
**Dotnet: appsettings.json**
```
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "mycompany.com",
"TenantId": "my-tenant-id",
"ClientId": "my-client-id",
"CallbackPath": "/signin-oidc"
},
```
**In My Azure Active Directory Tentant**
I have configured 2 "Reply URLs"
* <https://sales.mycompany.com/signin-oidc>
* <https://sales.mycompany.com>
**Now for the error / My Question**
When I hit the site, I sign in. Afterward signing in, and choosing whether or not to "Stay signed in", I'm taken to a page with an error.
[](https://i.stack.imgur.com/neJID.jpg)
You can see in the error, that the Reply Address that is attempting to be redirected to, is HTTP, not HTTPS. I think this is coming from the line in appsettings.json that says:
```
"CallbackPath": "/signin-oidc"
```
And since my .NET Core Site (via Kestrel on port 5000) is not on HTTPS, it's trying to load <http://example.com>**/signin-oidc**, instead of HTTPS. Remember that my .NET Core Site is behind an NGinX reverse Proxy, which is configured to handle traffic on 443.
Thank you,<issue_comment>username_1: You should check out the documentation on [Hosting on Linux](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-nginx?tabs=aspnetcore2x#configure-a-reverse-proxy-server).
Make sure you use `UseForwardedHeaders` in the middleware pipeline before `UseAuthentication`:
```
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseAuthentication();
```
Nginx will assign a header for the protocol used before it forwarded the call to Kestrel (among other things).
This middleware will then check those headers to set the right protocol.
Upvotes: 1 <issue_comment>username_2: In startup.cs, you can try to force hostname and schema. The following code could help. Important: place it **before** setting authentication.
```
app.Use((context, next) =>
{
context.Request.Host = new HostString(hostname + (port.HasValue ? ":" + port : null));
context.Request.Scheme = protocol;
return next();
});
```
Upvotes: 0 <issue_comment>username_3: I saw this and was able to get it working: <https://github.com/aspnet/Security/issues/1702>
```
var fordwardedHeaderOptions = new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
};
fordwardedHeaderOptions.KnownNetworks.Clear();
fordwardedHeaderOptions.KnownProxies.Clear();
app.UseForwardedHeaders(fordwardedHeaderOptions);
```
Upvotes: 3
|
2018/03/17
| 1,789 | 5,962 |
<issue_start>username_0: I recentley started coding in C++ and I can't seem to understand how to ruturn the 2d array
>
> GridArray
>
>
>
Is the problem somewhere in the type of the method because I can't seem to resolve it. Any help would be much appriciated!
```
static int GridArray [15][20];
int MapEditor::updateGrid(int *xCursor,int *yCursor){`
int width=16;
if(input.getInput()==psxUp){
VGA.drawRect((*xCursor)*16,(*yCursor)*16,(*xCursor)*16+width,(*yCursor)*16+width,255 );
(*yCursor)--;
if((*yCursor)<=0){
(*yCursor)=15;
}
VGA.drawRect((*xCursor)*16,(*yCursor)*16,(*xCursor)*16+width,(*yCursor)*16+width,224 );
}
if(input.getInput()==psxLeft){
VGA.drawRect((*xCursor)*16,(*yCursor)*16,(*xCursor)*16+width,(*yCursor)*16+width,255 );
(*xCursor)--;
if((*xCursor)<=0){
(*xCursor)=20;
}
VGA.drawRect((*xCursor)*16,(*yCursor)*16,(*xCursor)*16+width,(*yCursor)*16+width,224 );
}
if(input.getInput()==psxRight){
VGA.drawRect((*xCursor)*16,(*yCursor)*16,(*xCursor)*16+width,(*yCursor)*16+width,255 );
(*xCursor)++;
if((*xCursor)>=20){
(*xCursor)=0;
}
VGA.drawRect((*xCursor)*16,(*yCursor)*16,(*xCursor)*16+width,(*yCursor)*16+width,224 );
}
if(input.getInput()==psxDown){
VGA.drawRect((*xCursor)*16,(*yCursor)*16,(*xCursor)*16+width,(*yCursor)*16+width,255 );
(*yCursor)++;
if((*yCursor)>=15){
(*yCursor)=0;
}
VGA.drawRect((*xCursor)*16,(*yCursor)*16,(*xCursor)*16+width,(*yCursor)*16+width,224 );
}
if(input.getInput()==psxSqu){
spriteSelector.setSprite(bricks_destructive,bricks_destructive_palette);
spriteSelector.drawAtPosition((*xCursor)*16,(*yCursor)*16);
spriteSelector.update();
GridArray[(*yCursor)][(*xCursor)]=1;
Serial.println(GridArray[(*yCursor)][(*xCursor)]);
}
delay(120);
if(input.getInput()==psxSlct){
Serial.println(GridArray);
return GridArray;
}
}
```<issue_comment>username_1: In C++ you cannot return plain arrays (neither 1D ones nor 2D ones or higher). One could return a reference to such an array, and it would even be possible to encapsulate such arrays in a `struct`-object (which then could be returned).
However, these solutions are probably a work around of what is actually intended.
As you start coding C++ you might start with abandoning "old fashioned C style" and make use of the C++ concepts like standard library and its containers, e.g. with `std::array`. With that, you' code above example differently:
```
#include
typedef std::array,20> GridArray;
GridArray initGrid() {
GridArray ga = { { 0 } };
ga[0][0] = 15;
ga[0][1] = 30;
return ga;
}
int main() {
GridArray g = initGrid();
for(auto row : g) {
for (auto column : row) {
cout << column << " ";
}
cout << endl;
}
}
```
Note that there are other variants as well (e.g. passing arrays in as input parameters to functions which then alter them rather then creating and returning them in the function. But actually I think that the `std::array`-approach comes closest to that what you need.
Upvotes: 2 <issue_comment>username_2: I assume you are getting compile errors?
You have 2 problems:
1. The return type of your function is `int` but you are trying to return `int
[15][20]`
2. You aren't allowed to return an array from a function
3. Not all code paths return a value, your `return GridArray` needs to be outside the if statement.
you probably want something like this:
```
typedef int ArrayType[15][20];
static ArrayType GridArray;
ArrayType& f()
{
...
return GridArray;
}
```
Or even better use std::vector or std::array
Upvotes: 1 <issue_comment>username_3: Here is another solution, and it gets overlooked for more "technical" solutions, but this solution is rather simple.
This solution doesn't require intimate knowledge of pointers or references, doesn't require knowledge or usage of STL, doesn't require features or libraries that exist in standard C++ that may not exist on some platforms, should be very lightweight, and should be easily understandable by even beginner C++ programmers. However there is some code you would need to change to apply this technique.
The solution is this: simply wrap the 2-dimensional array inside a `struct` and pass / return the `struct`. That's it.
Since a `struct` is copyable and assignable (and arrays are neither one), then it is simply a matter of wrapping the array inside a struct and use that as a poor-man's container (even though it just works). Copies work, assignments work, passing to and from functions work, etc.
```
struct Array2D
{
int GridArray [15][20];
};
```
Then you simply pass and return `Array2D`'s around. No pointers are necessary.
```
static Array2D theGrid;
Array2D& SomeFunction()
{
...
theGrid.GridArray[(*yCursor)][(*xCursor)]=1;
return theGrid;
}
```
The above returns a reference to the `Array2D` that was declared static. But you also get a choice of returning a copy of the results is so desired.
```
Array2D SomeFunction2()
{
...
theGrid.GridArray[(*yCursor)][(*xCursor)]=1;
return theGrid;
}
```
The above takes the `static Array2D` that was declared and returns a copy of it.
You then have the power to do things like:
```
Array2D tempGrid = theGrid; // get a copy of the original
//..
tempGrid.GridArray[0][0] = 1; // changes the copy but not the original
```
No need for `for` loops or `memcpy`'s to assign one array to the other -- let the `struct` do that work automatically and easily for you since assignment and copy is built-in with structs and classes.
But again please note that you will need to change some code around to append `xyz.` to your current code that refers to `GridArray`, where `xyz` is the name of the `Array2D` instance.
Upvotes: 1
|
2018/03/17
| 1,513 | 4,192 |
<issue_start>username_0: I have created a container from httpd docker image via Dockerfile:
```
FROM httpd:2.4
COPY ./public-html/ /usr/local/apache2/htdocs/
```
The public-html file contains just a simple html file:
```
# cat public-html/index.html
Simple Page
```
Then I created the container:
```
# docker build -t apachehttpd .
```
And started:
```
docker run -dit -p 8080:80 apachehttpd
```
The container is up and running:
```
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0912f4f7d1a8 apachehttpd "httpd-foreground" 19 hours ago Up 19 hours 0.0.0.0:8080->80/tcp keen_almeida
```
Netstat says that it's really listening:
```
tcp6 0 0 :::8080 :::* LISTEN
```
However the website is not reachable via browser nor cURL. But with telnet I am able to connect to the socket, but with GET it returns "Bad Request":
```
# curl -v telnet://localhost:8080
* About to connect() to localhost port 8080 (#0)
* Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
GET /
HTTP/1.1 400 Bad Request
Date: Sat, 17 Mar 2018 19:28:45 GMT
Server: Apache/2.4.29 (Unix)
Content-Length: 226
Connection: close
Content-Type: text/html; charset=iso-8859-1
400 Bad Request
Bad Request
===========
Your browser sent a request that this server could not understand.
* Closing connection 0
```
And I can see my requests in logs:
```
# docker logs 0912f4f7d1a8
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
[Sat Mar 17 00:32:09.681368 2018] [mpm_event:notice] [pid 1:tid 139650427893632] AH00489: Apache/2.4.29 (Unix) configured -- resuming normal operations
[Sat Mar 17 00:32:09.681422 2018] [core:notice] [pid 1:tid 139650427893632] AH00094: Command line: 'httpd -D FOREGROUND'
172.17.0.1 - - [17/Mar/2018:18:52:41 +0000] "GET /" 400 226
172.17.0.1 - - [17/Mar/2018:19:21:56 +0000] "GET /index.html" 400 226
172.17.0.1 - - [17/Mar/2018:19:28:45 +0000] "GET /" 400 226
```
Could you please support me, why the page is not accessible via browser?<issue_comment>username_1: The only thing you missing is to create the user and set permissions. due to not any permission cause to kill container and through error.
Here is my docker file with little modification.
```
FROM httpd:2.4
COPY index.html /usr/local/apache2/htdocs/index.html
RUN mkdir -p /run/apache2/ && \
chown www-data:www-data /run/apache2/ && \
chmod 777 /run/apache2/
EXPOSE 80 443
```
my `index.html`
```
Welcome to docker :)
=======================
```
And here wo go :)
[](https://i.stack.imgur.com/4yEz8.png)
Upvotes: 1 <issue_comment>username_2: 1) Open Kinematic and go check whether container is ruining or not .
2) Click on highlighted arrow it will open link in new browser .
[](https://i.stack.imgur.com/LvFe2.png)
[](https://i.stack.imgur.com/nIXNk.png)
[](https://i.stack.imgur.com/8Ori6.png)
Upvotes: 0 <issue_comment>username_3: I tried everything of this answer [Permission issues with Apache inside Docker](https://stackoverflow.com/questions/23836416/permission-issues-with-apache-inside-docker) unlucky
Just this worked for me:
`RUN chown www-data:www-data /usr/local/apache2/htdocs/ -R`
Here my complete Dockerfile
```
FROM httpd:2.4
WORKDIR /usr/local/apache2/htdocs/
RUN chmod -R 755 /usr/local/apache2/htdocs/
COPY ./index.html /usr/local/apache2/htdocs/
RUN chown www-data:www-data /usr/local/apache2/htdocs/ -R
```
If don't work, put the `chmod` sentence inside of container using the `ENTRYPOINT ["entrypoint.sh"]`
Upvotes: 1
|
2018/03/17
| 416 | 1,346 |
<issue_start>username_0: I have some variables that are not part of the model attributes. for instance: my Model does have a function that generates a list of `decimal`.
```
List CreateValues();
```
and I would like to render it as currency.
```
@{
var vals = Model.CreateValues();
}
@for (var i = 0; i < vals .Count ; i++)
{
Year @i: @val[i]
}
```
this way it is rendered as decimal.
How can I tell to the render engine that those values should be rendered as currency? without using `.ToString("C")`<issue_comment>username_1: try `@string.Format("{0:C}", val);`
Upvotes: 0 <issue_comment>username_2: I see no reason, why you shouldn't use `.ToString('C')`.
Another way would be `@Html.DisplayFor(e => val[i])` using the [Display Template](http://www.growingwiththeweb.com/2012/12/aspnet-mvc-display-and-editor-templates.html) `Decimal.cshtml`.
---
You could also create an Display Template for your whole List. But you need to refactor your ViewModel:
```
[UiHint("DecimalYearList")]
List MyList { get; set; }
```
And in your `~Views/DisplayTemplates/DecimalYearList.cshtml`:
```
@model List
@for (var i = 0; i < Model.Count; i++)
{
Year @i: @Model[i].ToString("C")
}
```
And in your View, it is as simple as calling
```
@Html.DisplayFor(e => e.MyList)
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 668 | 2,537 |
<issue_start>username_0: I'm using ASP.Net MVC with EF6, I want to enable user to send email for list of students by click on send button in View then the message will sent to each student in the list (students email address are stored in the list ).
the user will enter his name, email and message,
How to call Contact method from controller for each student when the user click send in View?
```
public ActionResult Project(int? id)
{
mytable s = new mytable()
{
//this student list contains student information (name, email .. )
Student = (from ss in db.Student
join sp in db.Stu_Projects on ss.studentId equals
sp.StuId
where sp.PId == id
select ss).ToList()
};
return View(s);
}
//I want to call this method for each student in the list when the user click send button in the view
[HttpPost]
[ValidateAntiForgeryToken]
public async Task ContactAsync(String FromName, String FromEmail, String Message,String to)
{
if (ModelState.IsValid)
{
var body = ".....";
var message = new MailMessage();
message.To.Add(new MailAddress(to)); // receiver (each student in the list)
message.Subject = "Testing";
message.Body = string.Format(body, FromName, FromEmail, Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(message);
}
}
}
```
```html
@model --------
@{
/**/
ViewBag.Title = "Project";}
Email
Subject
Message
Send message
```<issue_comment>username_1: try `@string.Format("{0:C}", val);`
Upvotes: 0 <issue_comment>username_2: I see no reason, why you shouldn't use `.ToString('C')`.
Another way would be `@Html.DisplayFor(e => val[i])` using the [Display Template](http://www.growingwiththeweb.com/2012/12/aspnet-mvc-display-and-editor-templates.html) `Decimal.cshtml`.
---
You could also create an Display Template for your whole List. But you need to refactor your ViewModel:
```
[UiHint("DecimalYearList")]
List MyList { get; set; }
```
And in your `~Views/DisplayTemplates/DecimalYearList.cshtml`:
```
@model List
@for (var i = 0; i < Model.Count; i++)
{
Year @i: @Model[i].ToString("C")
}
```
And in your View, it is as simple as calling
```
@Html.DisplayFor(e => e.MyList)
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 823 | 3,115 |
<issue_start>username_0: Completely rewriting this question yet again to hopefully put the focus on the issue I'm trying to solve.
We have the following class that, due to an external framework outside of our control, requires us to implement `ObjCProtocolRequiringBla`, like so...
```
class FooBase : NSObject, ObjCProtocolRequiringBla {
class var possibleValues:[String] {
// Note: Use preconditionFailure, not fatalError for things like this.
// At runtime, they both halt execution, but precondition(Failure)
// only logs the message for debug builds. Additionally,
// in debug builds it pauses in a debuggable state rather than crash.
preconditionFailure("You must override possibleValues")
}
// This satisfies the objective-c protocol requirement
final func getBla() -> Bla {
let subclassSpecificValues = type(of:self).possibleValues
return Bla(withValues:subclassSpecificValues)
}
}
class FooA : FooBase
override class var possibleValues:[String] {
return [
"Value A1",
"Value A2",
"Value A3"
]
}
}
class FooB : FooBase
override class var possibleValues:[String] {
return [
"Value B1",
"Value B2",
"Value B3",
"Value B4"
]
}
}
```
As you can see, `possibleValues` is used in the implementation of `getBla()`. Additionally, it has to be common to all instances of that particular subclass, hence being a class variable and not an instance variable. This is because in another place in the code, we have to retrieve all possible values across all subclasses, like so...
```
static func getAllPossibleValues:[String] {
return [
FooA.possibleValues,
FooB.possibleValues
].flatMap { $0 }
}
```
What I'm trying to figure out how to do is make the compiler complain if a subclass of `FooBase` does not implement `possibleValues`.
In other words, how can we make this report a compile-time error:
```
class FooC : FooBase
// Doesn't override class var possibleValues
}
```
Currently the only way I know of is the above, defining it in the base class with a `preconditionFailure` or similar, but that's a runtime check, not compile-time so it's not the best solution.<issue_comment>username_1: try `@string.Format("{0:C}", val);`
Upvotes: 0 <issue_comment>username_2: I see no reason, why you shouldn't use `.ToString('C')`.
Another way would be `@Html.DisplayFor(e => val[i])` using the [Display Template](http://www.growingwiththeweb.com/2012/12/aspnet-mvc-display-and-editor-templates.html) `Decimal.cshtml`.
---
You could also create an Display Template for your whole List. But you need to refactor your ViewModel:
```
[UiHint("DecimalYearList")]
List MyList { get; set; }
```
And in your `~Views/DisplayTemplates/DecimalYearList.cshtml`:
```
@model List
@for (var i = 0; i < Model.Count; i++)
{
Year @i: @Model[i].ToString("C")
}
```
And in your View, it is as simple as calling
```
@Html.DisplayFor(e => e.MyList)
```
Upvotes: 2 [selected_answer]
|
2018/03/17
| 914 | 3,237 |
<issue_start>username_0: I have three HTML form field values (name, saywords, mail) that I try to concat in php and write into one single txt file on my server:
Each value should be on a new line in the txt field, as is why I added the "\n" in the array .... where's my error?
Thanks a lot for any help!
```
$name = $_POST['name'];
$saywords = $_POST['saywords'];
$mail = $_POST['mail'];
$data = array($name, . "\n" $mail, . "\n" $saywords);
file_put_contents("$t.$ip.txt",$data); // Will put the text to file
```<issue_comment>username_1: i don't see the use of `array` , you can concatenate them just like :
```
$data = $name . "\n" . $mail . "\n" . $saywords ;
```
Upvotes: 2 <issue_comment>username_2: You have two problems:
* `$data` should be a string not an array
* `.` concatenates the left hand side and the right hand side: `"abc" . "def"` becomes `"abcdef"`.
+ putting the dot first like in `. "\n"` or even `. "\n" $mail` doesn't make sense in PHP so you'll get a parse error.
Replace your `$data =` line with `$data = $name . "\n" . $mail . "\n" . $saywords;` and you'll be good to go.
Upvotes: 3 [selected_answer]<issue_comment>username_3: Use as you use html code
Upvotes: -1 <issue_comment>username_4: It depends with the operating system of the server.
Try `"\r\n"` instead of `"\n"`
Upvotes: 1 <issue_comment>username_5: Okay, so here is my shot.
```
/*first of all, you should always check if posted vars are actually set
and not empty. for that, you can use an universal function "empty", which
checks if the variable is set / not null / not an empty string / not 0.
In such way you will avoid PHP warnings, when some of these variables
will not be set*/
$name = !empty($_POST['name']) ? $_POST['name'] : '';
$saywords = !empty($_POST['saywords']) ? : $_POST['saywords'] : '';;
$mail = !empty($_POST['mail']) ? $_POST['mail'] : '';
/*Secondly, do not use \n, \r, \r\n, because these are platform specific.
Use PHP_EOL constant, it will do the job perfectly, by choosing
what type of line-break to use best.
As others mentioned - in your scenario, the string would be better solution.
Add everything into string, and then put its contents into file. Avoid using
double quotes, when you define PHP strings, and use single quotes instead - for
performance and cleaner code.
*/
$data = 'Name: '.$name.PHP_EOL.'E-Mail: '.$mail.PHP_EOL.'Message: '.$saywords.PHP_EOL.PHP_EOL;
file_put_contents($t.$ip.'.txt', $data); // Will put the text to file
```
By the way, I strongly suggest to also add some extra validation, before saving data to that txt file. With this code somebody can easily mess up contents of your txt file, by posting huge amounts of data with no limits.
Tips:
1) Accept only Names with limited lengths and charaters (do not allow to use special symbols or line breaks - you can also filter them out, before saving)
2) Validate e-mail which has been entered - if it is in correct format, does mx records exists for the domain of e-mail address, and so on...
3) Accept "saywords" with limited length, and if needed - deny or filter out special characters.
You will get much cleaner submissions by doing this way.
Upvotes: 0
|
2018/03/17
| 934 | 3,337 |
<issue_start>username_0: I wish prefill textarea field with my contents from the controller. It's work if I do :
```
{% for i in contents %}
{{ i }}
{% endfor %}
```
But I don't know how to do with :
```
$form = $this->createFormBuilder()
->add('textarea', TextareaType::class,[
'data' => // $contents (it's an array)
```
I don't work with entities, $contents is an array fill with :
```
file = fopen($newFile, "r+");
$contents = [] ;
while (($content = fgets($file)) !== false) {
array_push($contents, $content);
}
fclose($file);
```
Any ideas mates ? TY :D<issue_comment>username_1: i don't see the use of `array` , you can concatenate them just like :
```
$data = $name . "\n" . $mail . "\n" . $saywords ;
```
Upvotes: 2 <issue_comment>username_2: You have two problems:
* `$data` should be a string not an array
* `.` concatenates the left hand side and the right hand side: `"abc" . "def"` becomes `"abcdef"`.
+ putting the dot first like in `. "\n"` or even `. "\n" $mail` doesn't make sense in PHP so you'll get a parse error.
Replace your `$data =` line with `$data = $name . "\n" . $mail . "\n" . $saywords;` and you'll be good to go.
Upvotes: 3 [selected_answer]<issue_comment>username_3: Use as you use html code
Upvotes: -1 <issue_comment>username_4: It depends with the operating system of the server.
Try `"\r\n"` instead of `"\n"`
Upvotes: 1 <issue_comment>username_5: Okay, so here is my shot.
```
/*first of all, you should always check if posted vars are actually set
and not empty. for that, you can use an universal function "empty", which
checks if the variable is set / not null / not an empty string / not 0.
In such way you will avoid PHP warnings, when some of these variables
will not be set*/
$name = !empty($_POST['name']) ? $_POST['name'] : '';
$saywords = !empty($_POST['saywords']) ? : $_POST['saywords'] : '';;
$mail = !empty($_POST['mail']) ? $_POST['mail'] : '';
/*Secondly, do not use \n, \r, \r\n, because these are platform specific.
Use PHP_EOL constant, it will do the job perfectly, by choosing
what type of line-break to use best.
As others mentioned - in your scenario, the string would be better solution.
Add everything into string, and then put its contents into file. Avoid using
double quotes, when you define PHP strings, and use single quotes instead - for
performance and cleaner code.
*/
$data = 'Name: '.$name.PHP_EOL.'E-Mail: '.$mail.PHP_EOL.'Message: '.$saywords.PHP_EOL.PHP_EOL;
file_put_contents($t.$ip.'.txt', $data); // Will put the text to file
```
By the way, I strongly suggest to also add some extra validation, before saving data to that txt file. With this code somebody can easily mess up contents of your txt file, by posting huge amounts of data with no limits.
Tips:
1) Accept only Names with limited lengths and charaters (do not allow to use special symbols or line breaks - you can also filter them out, before saving)
2) Validate e-mail which has been entered - if it is in correct format, does mx records exists for the domain of e-mail address, and so on...
3) Accept "saywords" with limited length, and if needed - deny or filter out special characters.
You will get much cleaner submissions by doing this way.
Upvotes: 0
|
2018/03/17
| 1,468 | 4,756 |
<issue_start>username_0: I need to read a file and put that data inside to different arrays.
My .txt file looks like:
```
w1;
1 2 3
w2;
3 4 5
w3;
4 5 6
```
I tried something like the following:
```
int[] w1 = new int [3];
int[] w2 = new int [3];
int[] w3 = new int [3];
string v = "w1:|w2:|w3:";
foreach (string line in File.ReadAllLines(@"D:\\Data.txt"))
{
string[] parts = Regex.Split(line, v);
```
I got that string but I have no idea how to cut every element of it to arrays showed above.<issue_comment>username_1: Your RegEx doesn't actually do anything, you already have an array with each line separated. What you want to do is just ignore the lines that aren't data:
```
var lines = File.ReadAllLines(@"D:\\Data.txt");
for (int i = 1; i < lines.Length; i += 2) // i.e indexes 1, 3 and 5
{
string[] numbers = lines[i].Split(' ');
}
```
Or, you could just assign given that you know the order:
```
w1 = lines[1].Split(' ');
w2 = lines[3].Split(' ');
w3 = lines[5].Split(' ');
```
Upvotes: 2 <issue_comment>username_2: Rather than parsing the file and putting the arrays into three hardcoded variables corresponding to hardcoded names `w1`, `w2` and `w3`, I would remove the hardcoding and parse the file into a `Dictionary` like so:
```
public static class DataFileExtensions
{
public static Dictionary ParseDataFile(string fileName)
{
var separators = new [] { ' ' };
var query = from pair in File.ReadLines(fileName).Chunk(2)
let key = pair[0].TrimEnd(';')
let value = (pair.Count < 2 ? "" : pair[1]).Split(separators, StringSplitOptions.RemoveEmptyEntries).Select(s => int.Parse(s, NumberFormatInfo.InvariantInfo)).ToArray()
select new { key, value };
return query.ToDictionary(p => p.key, p => p.value);
}
}
public static class EnumerableExtensions
{
// Adapted from the answer to "Split List into Sublists with LINQ" by casperOne
// https://stackoverflow.com/questions/419019/split-list-into-sublists-with-linq/
// https://stackoverflow.com/a/419058
// https://stackoverflow.com/users/50776/casperone
public static IEnumerable> Chunk(this IEnumerable enumerable, int groupSize)
{
// The list to return.
List list = new List(groupSize);
// Cycle through all of the items.
foreach (T item in enumerable)
{
// Add the item.
list.Add(item);
// If the list has the number of elements, return that.
if (list.Count == groupSize)
{
// Return the list.
yield return list;
// Set the list to a new list.
list = new List(groupSize);
}
}
// Return the remainder if there is any,
if (list.Count != 0)
{
// Return the list.
yield return list;
}
}
}
```
And you would use it as follows:
```
var dictionary = DataFileExtensions.ParseDataFile(fileName);
Console.WriteLine("Result of parsing {0}, encountered {1} data arrays:", fileName, dictionary.Count);
foreach (var pair in dictionary)
{
var name = pair.Key;
var data = pair.Value;
Console.WriteLine(" Data row name = {0}, values = [{1}]", name, string.Join(",", data));
}
```
Which outputs:
```
Result of parsing Question49341548.txt, encountered 3 data arrays:
Data row name = w1, values = [1,2,3]
Data row name = w2, values = [3,4,5]
Data row name = w3, values = [4,5,6]
```
Notes:
* I parse the integer values using [`NumberFormatInfo.InvariantInfo`](https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.invariantinfo.aspx) to ensure consistency of parsing in all locales.
* I break the lines of the file into chunks of two by using a lightly modified version of the method from [this answer](https://stackoverflow.com/a/419058) to *[Split List into Sublists with LINQ](https://stackoverflow.com/questions/419019/split-list-into-sublists-with-linq/)* by [casperOne](https://stackoverflow.com/users/50776/casperone).
* After breaking the file into chunks of pairs of lines, I trim the `;` from the first line in each pair and use that as the dictionary key. The second line in each pair gets parsed into an array of integer values.
* If the names `w1`, `w2` and so on are not unique, you could deserialize instead into a [`Lookup`](https://msdn.microsoft.com/en-us/library/bb460184.aspx) by replacing [`ToDictionary()`](https://msdn.microsoft.com/en-us/library/bb548657.aspx) with [`ToLookup()`](https://msdn.microsoft.com/en-us/library/bb549211.aspx).
* Rather than loading the entire file into memory upfront using [`File.ReadAllLines()`](https://msdn.microsoft.com/en-us/library/s2tte0y1.aspx), I enumerate though it sequentially using [`File.ReadLines()`](https://msdn.microsoft.com/en-us/library/dd383503.aspx). This should reduce memory usage without any additional complexity.
Sample working [.Net fiddle](https://dotnetfiddle.net/YPg4kC).
Upvotes: 3 [selected_answer]
|
2018/03/17
| 1,276 | 4,151 |
<issue_start>username_0: Let's say I have a sorted array with [1,2,3,4,5], it should become a binary search tree with this array as its output: [4,2,5,1,3] (the brackets below represent the indices)
```
4 (0)
/ \
2 (1) 5 (2)
/ \
1 (3) 3 (4)
```
While doing some research online, I found a link on this site that I could use to get this: [Insert sorted array into binary search tree](https://stackoverflow.com/questions/19399747/insert-sorted-array-into-binary-search-tree)
I wanted to convert this to Python 3 without the use of any classes. This is what I have so far, but I'm stuck.
```
def bstlist(arr,start,end):
newlst = []
#start = arr[0]
#end = arr[-1]
if start > end:
return [] #null
mid = start + (end - start) / 2
newlst = arr[mid]
```
I'm particularly confused about how to implement three lines of code in the Java implementation in Python:
```
TreeNode node = new TreeNode(arr[mid]);
node.left = sortedArrayToBST(arr, start, mid-1);
node.right = sortedArrayToBST(arr, mid+1, end);
```
How would I go about implementing them in Python ? And is there any other way to solve this in Python than the one listed in the link?<issue_comment>username_1: You really should use classes but if you don't want to you could use dictionaries instead.
```
def list_to_bst(l):
if len(l) == 0:
return None
mid = len(l) // 2
return {
"value": l[mid],
"left": list_to_bst(l[:mid]),
"right": list_to_bst(l[mid+1:])
}
```
you can then use it like so
```
list_to_bst([1, 2, 3, 4, 5])
```
Upvotes: 0 <issue_comment>username_2: The traditional functional way to represent trees is to use lists or tuples for the nodes. Each node is just a value, a left tree, and a right tree (and a tree is just a node, the root of the tree, or `None`).
Use lists if you want to mutate trees in-place; use tuples if you want to build a persistent tree where you generate new subnodes instead and the old ones are never mutated. Since the Java code you're looking at is mutating nodes, let's go with lists.
You can of course make this fancier by using a `namedtuple` in place of `tuple` or a `dataclass` (or use `attrs` off PyPI if you're not using Python 3.7+ and don't want to wait for a backport to your Python version) in place of `list`. (Or even just a `dict`.) This allows you to have nice names like `.left` (or `['left']`) in place of sequence operations like `[1]`, but it doesn't actually change the functionality. Since we've decided to go with mutable, and we probably don't want to require Python 3.7 in early 2018βand besides, you said you don't want any classesβI'll stick with `list`.
```
# TreeNode node = new TreeNode(arr[mid]);
node = [arr[mid], None, None]
# node.left = sortedArrayToBST(arr, start, mid-1);
node[1] = sortedArrayToBST(arr, start, mid-1)
# node.right = sortedArrayToBST(arr, mid+1, end);
node[2] = sortedArrayToBST(arr, mid+1, end)
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: You can complete your bstlist function using list:
```
def bstlist(arr, st, end):
newlst = []
if st > end:
return []
mid = st + (end-st)/2
# adding the root list
root = [arr[mid]]
# getting the left list
left = bstlist(arr, st, mid-1)
# getting the right list
right = bstlist(arr, mid+1, end)
newlst = root + left+ right
return newlst
```
calling the bstlist function will return you list, which is the **order in which you should insert the number to get a balanced tree**.
**Example:**
>
> arr = [1,2,3,4,5]
>
>
> bstarr = bstlist(arr, 0, len(arr)-1)
>
>
>
you will get bstarr as
>
> **[3, 1, 2, 4, 5]**
>
>
>
it means you have to insert **3** first then **1** and so on.
The tree will look like this:
```
3
/ \
1 4
\ \
2 5
```
To get the output as **[3, 1, 4, 2, 5]** you have to do level order traversal on the above formed binary search tree.
Upvotes: 0
|
2018/03/17
| 216 | 691 |
<issue_start>username_0: ```
Select *
from [User]
where [Date1] - [Date2] < 7
```
SQL Server 2017.
I want to select rows where *[Date1] - [Date2] less than 7 days*.
Dates are in format YYYY-MM-DD (object).<issue_comment>username_1: I would recommend doing something like this:
```
select u.*
from user u
where date1 >= date2 and
date1 < date2 + interval '7 day';
```
Note that date arithmetic is often specific to databases. This is ANSI-standard syntax, but other databases have similar functionality.
Upvotes: 0 <issue_comment>username_2: You can use the `Datediff` function
```
Select * from [User]
where datediff(dd, date2, date1) < 7
```
Upvotes: 3 [selected_answer]
|
2018/03/17
| 1,074 | 2,747 |
<issue_start>username_0: I have been tasked with converting a a worksheet from standard Excel into PowerPivot. However, I have hit a roadblock with the PERCENTRANK.INC function which is not available in DAX. I have come close to replicating it using a formula, but there are definite differences in the calculation.
Does anyone know how Excel calculates PERCENTRANK.INC()?
```
Formula in cell D2: =(COUNT($A$2:$A$10)-B2)/(COUNT($A$2:$A$10)-1)
Formula in cell B2: =RANK.EQ(A2,$A$2:$A$10,0)
Formula in cell C2: =PERCENTRANK.INC($A$2:$A$10,A2)
```
[](https://i.stack.imgur.com/kuqe3.png)<issue_comment>username_1: Edit:
-----
It's seems strange to me that there are so many "standard" ways to calculate `PERCENTRANK` that has have slightly different results.
Using your example of your 9-number set of `1,2,3,4,4,6,7,8,9`, depending on which "authority" I used, the *third* value (`3`) had a Percent Rank of `25.0%, 27.0%, 27.8% or 30.0%`.
Obviously we'll go with the one that gives your desired result, matching `PERCENTRANK.INC`.
>
> βββ*`PERCENTRANK.INC` is calculated as:*
> ----------------------------------------
>
>
> ββββββββββ[count of values lower than the given value]
> ------------------------------------------------------
>
>
> βββββββββββββββββββββββββββββΓ·
> ------------------------------
>
>
> βββ [count of all values in the set excluding the given value]
> --------------------------------------------------------------
>
>
>
so, if our range of `1,2,3,4,4,6,7,8,9`is in `A1:A9`, we could use this formula in `B1`:
```
=COUNTIF($A$1:$A$9,"<"&A1)/(COUNT($A$1:$A$9)-1)
```
...and copy or "fill" it down for results:
```
0.0%, 12.5%, 25.0%, 37.5%, 37.5%, 62.5%, 75.0%, 87.5%, 100.0%
```
---
Original Answer
---------------
>
> I think you just want to calculate the `PERCENTRANK` for current row
> value. Based on the logic for `PERCENTRANK`, we can add a `RANK` column in
> table and achieve same logic based on this column.
>
>
> 
>
>
> **Create a `Rank` column.**
>
>
>
> ```
> Rank = RANKX(Table6,Table6[Value])
>
> ```
>
> Then **create the `PctRank` based on the `Rank` column.**
>
>
>
> ```
> PctRank = (COUNTA(Table6[Name])-Table6[Rank])/(COUNTA(Table6[Name])-1)
>
> ```
>
> 
>
>
>
([Source](https://community.powerbi.com/t5/Desktop/PERCENTRANK-Inclusive/m-p/81208))
Upvotes: 3 [selected_answer]<issue_comment>username_2: For reference here is the DAX formula based off username_1's answer which includes ignoring cells with no values in them.
```
=ROUNDDOWN(COUNTROWS(FILTER('Lookup_Query','Lookup_Query'[Entrances]
```
Upvotes: 1
|
2018/03/17
| 1,089 | 2,854 |
<issue_start>username_0: I want to memoize a function with mutable parameters (Pandas Series objects). Is there any way to accomplish this?
Here's a simple Fibonacci example, the parameter is a Pandas Series where the first element represents the sequence's index.
Example:
```
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n.iloc[0] == 1 or n.iloc[0] == 2:
return 1
min1 = n.copy()
min1.iloc[0] -=1
min2 = n.copy()
min2.iloc[0] -= 2
return fib(min1) + fib(min2)
```
Call function:
```
fib(pd.Series([15,0]))
```
Result:
```
TypeError: 'Series' objects are mutable, thus they cannot be hashed
```
The intended use is more complex, so I posted this useless but simple example.<issue_comment>username_1: Edit:
-----
It's seems strange to me that there are so many "standard" ways to calculate `PERCENTRANK` that has have slightly different results.
Using your example of your 9-number set of `1,2,3,4,4,6,7,8,9`, depending on which "authority" I used, the *third* value (`3`) had a Percent Rank of `25.0%, 27.0%, 27.8% or 30.0%`.
Obviously we'll go with the one that gives your desired result, matching `PERCENTRANK.INC`.
>
> βββ*`PERCENTRANK.INC` is calculated as:*
> ----------------------------------------
>
>
> ββββββββββ[count of values lower than the given value]
> ------------------------------------------------------
>
>
> βββββββββββββββββββββββββββββΓ·
> ------------------------------
>
>
> βββ [count of all values in the set excluding the given value]
> --------------------------------------------------------------
>
>
>
so, if our range of `1,2,3,4,4,6,7,8,9`is in `A1:A9`, we could use this formula in `B1`:
```
=COUNTIF($A$1:$A$9,"<"&A1)/(COUNT($A$1:$A$9)-1)
```
...and copy or "fill" it down for results:
```
0.0%, 12.5%, 25.0%, 37.5%, 37.5%, 62.5%, 75.0%, 87.5%, 100.0%
```
---
Original Answer
---------------
>
> I think you just want to calculate the `PERCENTRANK` for current row
> value. Based on the logic for `PERCENTRANK`, we can add a `RANK` column in
> table and achieve same logic based on this column.
>
>
> 
>
>
> **Create a `Rank` column.**
>
>
>
> ```
> Rank = RANKX(Table6,Table6[Value])
>
> ```
>
> Then **create the `PctRank` based on the `Rank` column.**
>
>
>
> ```
> PctRank = (COUNTA(Table6[Name])-Table6[Rank])/(COUNTA(Table6[Name])-1)
>
> ```
>
> 
>
>
>
([Source](https://community.powerbi.com/t5/Desktop/PERCENTRANK-Inclusive/m-p/81208))
Upvotes: 3 [selected_answer]<issue_comment>username_2: For reference here is the DAX formula based off username_1's answer which includes ignoring cells with no values in them.
```
=ROUNDDOWN(COUNTROWS(FILTER('Lookup_Query','Lookup_Query'[Entrances]
```
Upvotes: 1
|
2018/03/17
| 1,104 | 3,327 |
<issue_start>username_0: ```
[
'one/two' => 3,
'one/four/0' => 5,
'one/four/1' => 6,
'one/four/2' => 7,
'eight/nine/ten' => 11
]
```
I am attempting to build the above array based on $json\_str:
```
$json_str = '{
"one":
{
"two": 3,
"four": [ 5,6,7]
},
"eight":
{
"nine":
{
"ten":11
}
}
}';
```
I built a recursive function that loops thru this $json\_str but so far I can only get strings to output.
How would I build an array instead echoing a string?
Also, how would I get only index values that belong in the associative index to be there.
Currently I can only get all keys to print:
```
one/two => 3
one/two/four/0 => 5
one/two/four/0/1 => 6
one/two/four/0/1/2 => 7
one/eight/nine/ten => 11
```
---
Below is what I have so far:
```
php
function printAll($a, $prefix = '') {
if (!is_array($a) && !is_object($a)) {
$prefix = rtrim($prefix, '/');
echo $prefix . ' = ' . $a, "\n";
return;
}
foreach($a as $k => $v) {
$prefix .= $k . "/";
printAll($v, $prefix);
}
}
$json_str = '{
"one":
{
"two": 3,
"four": [ 5,6,7]
},
"eight":
{
"nine":
{
"ten":11
}
}
}';
$object = json_decode($json_str);
printAll($object);
```<issue_comment>username_1: You could use an array to hold the keys of object, instead of using a string, and `array_pop()` to remove the last one at the end of the loop. So you have a *stack* of the keys which can be used to get the breadcrumb of the JSON data.
```
function printAll(&$out = [], $a, $prefix = []) {
foreach ($a as $key => $value) {
$prefix[] = $key; // add the key to "prefix"
if (is_array($value) || is_object($value)) {
printAll($out, $value, $prefix);
}else{
$out[implode('/', $prefix)] = $value;
}
// remove current key because we are no more inside it.
array_pop($prefix);
}
}
$json_str = '{"one": {"two": 3, "four": [ 5,6,7] }, "eight": {"nine": {"ten":11 } } }';
$object = json_decode($json_str);
$data = [];
printAll($data, $object);
print_r($data);
```
Outputs:
```
Array
(
[one/two] => 3
[one/four/0] => 5
[one/four/1] => 6
[one/four/2] => 7
[eight/nine/ten] => 11
)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You modify `$prefix` inside the foreach loop. Therefore the changes will be there in each subsequent iteration of the loop. You should be fine if you cache your output in a temporary variable:
```
foreach($a as $k => $v) {
$tmp = $prefix;
$tmp .= $k . "/";
printAll($v, $tmp);
}
```
Now if you want to build an array instead of echoing you can simply pass the array by reference, and build it:
```
function printAll($a, &$output, $prefix = '') {
if (!is_array($a) && !is_object($a)) {
$prefix = rtrim($prefix, '/');
$output[]= $prefix . ' => ' . $a. "\n";
return;
}
foreach($a as $k => $v) {
$tmp = $prefix;
$tmp .= $k . "/";
printAll($v, $output, $tmp);
}
}
```
I put a demo here: <https://3v4l.org/LSvZN>
Upvotes: 1
|
2018/03/17
| 1,019 | 3,057 |
<issue_start>username_0: I'm trying to extract the latitude and longitude fields stored in this address JSON:
```
{
"city": "Hamilton",
"name": "<NAME>",
"type": "address",
"value": "22 Fake Road, Hamilton, Ontario, Canada",
"latlng": {"lat": 42.2526, "lng": -69.8549},
"country": "Canada",
"postcode": "L3Q 2W1",
"countryCode": "ca",
"administrative": "Ontario"
}
```
I'm trying to pull the name, latitude, and longitude for a map dashboard. I've tried both an eloquent query, and a raw SQL query:
```
$mapmarkerscalc = DB::table('potentialcustomers')->select('name', 'address->latlng->lat', 'address->latlng->lng')->get();
$mapmarkers = collect($mapmarkerscalc);
$mapmarkerscalc2 = DB::raw("SELECT (name, JSON_EXTRACT(`address` , '$.latlng.lat'), JSON_EXTRACT(`address` , '$.latlng.lng')) FROM potentialcustomers");
$mapmarkers2 = collect($mapmarkerscalc2);
```
They both get pretty close, but return a bunch of unneeded data in the `"lat"` and `"lng"` field:
```
{
"name":"<NAME>",
"`address`->'$.\"latlng\".\"lat\"'":"43.1526",
"`address`->'$.\"latlng\".\"lng\"'":"-79.8559"
}
```
How can I get rid of `"`address`->'$.\"latlng\".\"lng\"'":"`??<issue_comment>username_1: You could use an array to hold the keys of object, instead of using a string, and `array_pop()` to remove the last one at the end of the loop. So you have a *stack* of the keys which can be used to get the breadcrumb of the JSON data.
```
function printAll(&$out = [], $a, $prefix = []) {
foreach ($a as $key => $value) {
$prefix[] = $key; // add the key to "prefix"
if (is_array($value) || is_object($value)) {
printAll($out, $value, $prefix);
}else{
$out[implode('/', $prefix)] = $value;
}
// remove current key because we are no more inside it.
array_pop($prefix);
}
}
$json_str = '{"one": {"two": 3, "four": [ 5,6,7] }, "eight": {"nine": {"ten":11 } } }';
$object = json_decode($json_str);
$data = [];
printAll($data, $object);
print_r($data);
```
Outputs:
```
Array
(
[one/two] => 3
[one/four/0] => 5
[one/four/1] => 6
[one/four/2] => 7
[eight/nine/ten] => 11
)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You modify `$prefix` inside the foreach loop. Therefore the changes will be there in each subsequent iteration of the loop. You should be fine if you cache your output in a temporary variable:
```
foreach($a as $k => $v) {
$tmp = $prefix;
$tmp .= $k . "/";
printAll($v, $tmp);
}
```
Now if you want to build an array instead of echoing you can simply pass the array by reference, and build it:
```
function printAll($a, &$output, $prefix = '') {
if (!is_array($a) && !is_object($a)) {
$prefix = rtrim($prefix, '/');
$output[]= $prefix . ' => ' . $a. "\n";
return;
}
foreach($a as $k => $v) {
$tmp = $prefix;
$tmp .= $k . "/";
printAll($v, $output, $tmp);
}
}
```
I put a demo here: <https://3v4l.org/LSvZN>
Upvotes: 1
|
2018/03/17
| 634 | 2,137 |
<issue_start>username_0: I'm creating a program that searches if a word is in the file and then prints it.
```
FILE* fp = fopen("test.cfg", "rt");
if (fp)
{
char szFileName[256];
char country[4 + 1];
char line[256];
if (fgets(line, sizeof(line) - 1, fp)) {
sprintf(country);
}
fclose(fp);
}
```
What's wrong? Sorry for a newbie question.<issue_comment>username_1: Your program looks like a C program. So here's one way to look for a string, say `country`, in the input file and print whether the string exists in the file:
```
#include
#include
int main()
{
FILE\* fp = fopen("test.cfg", "r");
if (fp) {
char country[] = "canada";
char line[256];
while (fgets(line, sizeof(line), fp) != NULL) {
if (strstr(line, country) != NULL) {
printf("String '%s' is present in file\n", country);
break;
}
}
fclose(fp);
}
return 0;
}
```
In this code example, if `test.cfg` contains the string stored in `country`, then the code prints a string indicating this and breaks out of the while loop. If the string does not exist in the file, nothing is printed.
Note: As others have pointed out, `rt` is not a standard `fopen` mode. Also, if you are indeed planning on searching `country` in the file, then you need to initialize it first before using it.
Upvotes: 0 <issue_comment>username_2: There are a lot of issues in your program (uninitialized variables, wrong number of arguments to `sprintf`), and it does not even reflect what you actually want (searching for a word, for example).
In C++, you might use streams instead of the `FILE`-approach. Thereby you can make use of dynamic data structures like `std::string` that prevents you from having to know the maximum line size in advance. See the following code, which shows that the task is rather easy:
```
#include
#include
#include
int main() {
std::ifstream is("somefile.txt");
if (is.is\_open()) {
std::string line;
while (std::getline(is, line)) {
if (line.find("wordtosearchfor") != std::string::npos) {
std::cout << line << std::endl;
}
}
}
else {
cout << "could not open file." << endl;
}
}
```
Upvotes: 2
|
2018/03/17
| 1,017 | 3,699 |
<issue_start>username_0: I have an image. I want to upload it to S3 using aws-amplify. All the Storage class upload examples are using text documents; however, I would like to upload an image. I am using expo which does not have support from react-native-fetch-blob, and react native does not have blob support... yet.
So my options seem to be:
1. Create a node service via lambda.
2. Upload only the base64 info to S3 and not a blob.
`const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status === 'granted') {
const image = await ImagePicker.launchImageLibraryAsync({
quality: 0.5,
base64: true
});
const { base64 } = image;
Storage.put(`${username}-profileImage.jpeg`, base64);
}`
Is this Correct?<issue_comment>username_1: **EDIT FOR UPDATED ANSWER WITH RN BLOB SUPPORT VERSION:** I have been able to solve this now that React Native has announced blob support and now we only need the uri. See the following example:
```
uploadImage = async uri => {
const response = await fetch(uri);
const blob = await response.blob();
const fileName = 'profileImage.jpeg';
await Storage.put(fileName, blob, {
contentType: 'image/jpeg',
level: 'private'
}).then(data => console.log(data))
.catch(err => console.log(err))
}
```
**Old Answer**
For all you get to this. I ended up using <https://github.com/benjreinhart/react-native-aws3> This worked perfectly! But not the preferred solution as I would like to use aws-amplify.
Upvotes: 5 [selected_answer]<issue_comment>username_2: You can pass file object to .put method
```
Storage.put('test.png', file, { contentType: 'image/png' })
.then (result => console.log(result))
.catch(err => console.log(err));
```
Upvotes: -1 <issue_comment>username_3: I would like to add a more complete answer to this question.
The below code allows to pick images from the mobile device library using **ImagePicker** from Expo and store the images in S3 using **Storage** from **AWS** **Amplify**.
```
import React from 'react';
import { StyleSheet, ScrollView, Image, Dimensions } from 'react-native'
import { withAuthenticator } from 'aws-amplify-react-native'
import { ImagePicker, Permissions } from 'expo'
import { Icon } from 'native-base'
import Amplify from '@aws-amplify/core'
import Storage from '@aws-amplify/storage'
import config from './aws-exports'
Amplify.configure(config)
class App extends React.Component {
state = {
image: null,
}
// permission to access the user's phone library
askPermissionsAsync = async () => {
await Permissions.askAsync(Permissions.CAMERA_ROLL);
}
useLibraryHandler = async () => {
await this.askPermissionsAsync()
let result = await ImagePicker.launchImageLibraryAsync(
{
allowsEditing: false,
aspect: [4, 3],
}
)
console.log(result);
if (!result.cancelled) {
this.setState({ image: result.uri })
this.uploadImage(this.state.image)
}
}
uploadImage = async uri => {
const response = await fetch(uri);
const blob = await response.blob();
const fileName = 'dog77.jpeg';
await Storage.put(fileName, blob, {
contentType: 'image/jpeg',
level: 'public'
}).then(data => console.log(data))
.catch(err => console.log(err))
}
render() {
let { image } = this.state
let {height, width} = Dimensions.get('window')
return (
{image &&
}
);
}
}
export default withAuthenticator(App, { includeGreetings: true })
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
buttonStyle: {
fontSize: 45,
color: '#4286f4'
}
});
```
Upvotes: 2
|
2018/03/17
| 279 | 967 |
<issue_start>username_0: Where shall I add my custom js file in Understrap (WP)?
js/
or
src/js/
Also, I assume then I need to load it from inc/enqueue.php and modify gulpfile.js to compile it.
Is this correct?<issue_comment>username_1: You can use the folder named "JS" which is included on Understrap theme. However , you could include your javascript files on any folder.
```html
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri() . '/js/custom-site.js', array(), null, true );
```
Regards.
Upvotes: 3 [selected_answer]<issue_comment>username_2: For this purpose we add an empty js file to UnderStrap. Available since the latest 0.8.2 release.
You can find it in src/js/custom-javascript.js
It is part of the compiling gulp task "gulp scripts".
So you JS will be added to the minified theme.min.js at the end and you donΒ΄t have to enqueue an extra gile anymore.
If you keep the file empty nothing will be added to the theme.min.js.
Upvotes: 3
|
2018/03/17
| 405 | 1,519 |
<issue_start>username_0: Kotlin comes with the powerful feature for view binding using import `kotlinx.android.synthetic.main.activity_main.*`. I also know that Android Studio is powerful and flexible for customization.
[](https://i.stack.imgur.com/rxmq7.png)
In order to use view binding, we need to include `kotlinx.android.synthetic.main.activity_xxx.*` manually after creating the activity.
Is there any way / customization option in Android Studio so that whenever a new activity is created, it imports respective `kotlinx.android.synthetic.main.activity_xxx.*` automatically? For example, if I am creating `NewActivity` it should already have `kotlinx.android.synthetic.main.activity_new.*`.<issue_comment>username_1: You can use the folder named "JS" which is included on Understrap theme. However , you could include your javascript files on any folder.
```html
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri() . '/js/custom-site.js', array(), null, true );
```
Regards.
Upvotes: 3 [selected_answer]<issue_comment>username_2: For this purpose we add an empty js file to UnderStrap. Available since the latest 0.8.2 release.
You can find it in src/js/custom-javascript.js
It is part of the compiling gulp task "gulp scripts".
So you JS will be added to the minified theme.min.js at the end and you donΒ΄t have to enqueue an extra gile anymore.
If you keep the file empty nothing will be added to the theme.min.js.
Upvotes: 3
|
2018/03/17
| 339 | 1,144 |
<issue_start>username_0: I'm wanting to execute a function after an Array is completely set. I tried to implement didSet in the declaration of the array, but the code inside of it is called each time an element is added to the array. Is there any way to do what I want?
Here is some of my code:
```
var arrayScore = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] {
didSet {
for i in 0..
```<issue_comment>username_1: You can use the folder named "JS" which is included on Understrap theme. However , you could include your javascript files on any folder.
```html
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri() . '/js/custom-site.js', array(), null, true );
```
Regards.
Upvotes: 3 [selected_answer]<issue_comment>username_2: For this purpose we add an empty js file to UnderStrap. Available since the latest 0.8.2 release.
You can find it in src/js/custom-javascript.js
It is part of the compiling gulp task "gulp scripts".
So you JS will be added to the minified theme.min.js at the end and you donΒ΄t have to enqueue an extra gile anymore.
If you keep the file empty nothing will be added to the theme.min.js.
Upvotes: 3
|
2018/03/17
| 759 | 2,002 |
<issue_start>username_0: We stored the date as `VARCHAR2` in our database table
* REGDATE - `VARCHAR2`, Format `YYYY-MM-DD hh24:mi:ss.f`
Sample data:
```
2018-01-31 23:47:35.0
2018-01-01 00:00:48.0
2018-01-01 06:54:36.0
```
I'm trying to insert this data into a new table `TABLEB` with the correct `DATE` format. I tried a few solutions like below one's and i usually get `ORA-01821: date format not recognized`
```
SELECT
TO_DATE(REGDATE, 'YYYY-MM-DD HH24:MI:SS.F')
FROM
TABLEA
WHERE
REGDATE LIKE '2018-03-16%'
```
Can someone please assist me?<issue_comment>username_1: To use fractional seconds, you need to convert to a `timestamp`, so:
```
SELECT TO_TIMESTAMP(REGDATE,'YYYY-MM-DD HH24:MI:SS.FF')
FROM TABLEA
WHERE REGDATE LIKE '2018-03-16%';
```
If you need this as a `date`, convert afterwards:
```
SELECT CAST(TO_TIMESTAMP(REGDATE,'YYYY-MM-DD HH24:MI:SS.FF') as DATE)
FROM TABLEA
WHERE REGDATE LIKE '2018-03-16%';
```
Upvotes: 2 <issue_comment>username_2: **Update**
You're right, Oracle does not support fractional seconds with the DATE format. This is also written on the linked website of the original answer... oops.
>
> The following datetime format elements can be used in timestamp and interval format models, but not in the original DATE format model: FF, TZD, TZH, TZM, and TZR.
>
>
>
This should work though:
```
SELECT CAST(TO_TIMESTAMP(REGDATE,'YYYY-MM-DD HH24:MI:SS.FF1') AS DATE) FROM TABLEA WHERE REGDATE LIKE '2018-03-16%'
```
**Original answer**
Try to use
```
SELECT TO_DATE(REGDATE,'YYYY-MM-DD HH24:MI:SS.FF1') FROM TABLEA WHERE REGDATE LIKE '2018-03-16%'
```
as found as explanation for element *FF* at the table *Table 2-15 Datetime Format Elements* on the website <https://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements004.htm#i34924>
Upvotes: 3 [selected_answer]<issue_comment>username_3: ```
SELECT TO_TIMESTAMP(REGDATE,'YYYY-MM-DD HH24:MI:SS.FF')
FROM TABLEA WHERE REGDATE LIKE '2018-03-16%'
```
Upvotes: 0
|
2018/03/17
| 1,137 | 3,112 |
<issue_start>username_0: Hi I was trying to come up with a function to return a fibonacci sequence, that is an array not the usual last n-th fibonacci number.
```
function fib(n,arr=[0]) {
if (n===0||n===1) {
arr.push(n)
return arr;
}
let arr2 = fib(n-2);
let arr1 = fib(n-1);
arr1.push(arr2[arr2.length-1]+arr1[arr1.length-1]);
return arr1;
}
```
it works fine but I am not happy with the hard coded arr=[0] here. I tried to put arr=[] instead but the sequence I ended up getting excluded the first 0 entries in the array which should've been there.
I am sure there's better approaches to solve this.
P.S: I want to solve this using a recursive approach and I know it has a poor exponential time complexity but I just wanted to pratice my recursive programming skills.<issue_comment>username_1: ```
let arr2 = fib(n-2);
let arr1 = fib(n-1);
```
You build up two arrays for each step, so you build up n! arrays... Instead just use one recursive call, e.g.:
```
function fibonacci(n){
if(n <= 2)
return [0, 1].slice(0, n);
const res = fibonacci(n - 1);
res.push(res[res.length - 1] + res[res.length - 2])
return res;
}
```
---
But do you really need recursion?:
```
function fibonacci(n){
const arr = [0, 1].slice(0 , n);
for(let i = 2; i < n; i++)
arr[i] = arr[i - 1] + arr[i - 2];
return arr;
}
```
Upvotes: 3 <issue_comment>username_2: ```js
var fib = function(n) {
if (n === 1) {
return [0, 1];
} else {
var arr = fib(n - 1);
arr.push(arr[arr.length - 1] + arr[arr.length - 2]);
return arr;
}
};
console.log(fib(8));
```
Upvotes: -1 <issue_comment>username_3: Not my proudest code, but has array+recursion. Works fine with n>=2 (will not return `[1]`):
```js
function fibo(n){
var ret=[1,1];
function recurs(n){
if(!ret[n-1])recurs(n-1);
//if(!ret[n-2])recurs(n-2); // it is not necessary in fact
ret[n]=ret[n-1]+ret[n-2];
}
if(n>2)recurs(n-1);
return ret;
}
console.log(fibo(2).join());
console.log(fibo(15).join());
```
Upvotes: 0 <issue_comment>username_4: A recursive fibonacci is easy, but how about making it *tail-recursive*?
```
let fib = n => fib2(2, n, [0, 1]);
let fib2 = (k, n, a) => k >= n ? a :
fib2(k + 1, n, a.concat(a[k - 1] + a[k - 2]));
```
If you're a happy user of the Safari browser, whose JS engine already implements the ES6 tail call spec, you can test it with this snippet (warning: might take significant time or exhaust the memory!)
```js
'use strict';
const BIG = 1e5;
let fibNaive = n => {
if (n <= 2)
return [0, 1].slice(0, n);
const res = fibNaive(n - 1);
res.push(res[res.length - 1] + res[res.length - 2])
return res;
};
try {
console.log('naive', fibNaive(BIG).slice(0, 100));
} catch(e) {
console.log('naive', e.message) // RangeError: Maximum call stack size exceeded.
}
let fibCool = n => fib2(2, n, [0, 1]);
let fib2 = (k, n, a) => k >= n ? a :
fib2(k + 1, n, a.concat(a[k - 1] + a[k - 2]));
console.log('cool', fibCool(BIG).slice(0, 100)) // works!
```
Upvotes: 0
|
2018/03/17
| 1,067 | 2,487 |
<issue_start>username_0: I have a table `time_period`,
```
CREATE TABLE `time_period` (
`id` int(11) NOT NULL,
`time` time NOT NULL,
`slots` int(11) NOT NULL
) ;
```
The data in the table is basically time period in a 24 hour clock at the interval of 5 minutes. Something like this:
```
INSERT INTO `time_period` (`id`, `time`, `slots`) VALUES
(1, '00:00:00', 3),
(2, '00:05:00', 3),
(3, '00:10:00', 3),
(289, '24:00:00', 3);
```
Live test: <http://rextester.com/live/UXPV82172>
What I am trying to achieve is, get an hour of time between min\_time and max\_time (I am concatenating same date as date given in min\_time and max\_time) ,given that the current\_time (actual current date and time).
EDIT: updated the greater than less than sign, had an error here there (sorry)
------------------------------------------------------------------------------
```
SELECT
t0_.id AS id_0,
t0_.time AS time_1,
t0_.slots AS slots_2
FROM time_period t0_ WHERE
'2018-03-18' + t0_.time >= '2018-03-18 19:09' AND # :min_time
'2018-03-18' + t0_.time <= '2018-03-18 20:09' AND # :max_time
'2018-03-18' + t0_.time >= '2018-03-17 21:05' # :current_time
ORDER BY t0_.time ASC LIMIT 20
```
Looked pretty straight forward but for some reason all I get is:
>
> `1,00:00:00, 3`
>
>
>
EDIT
----
Expected output must be same as when running sql:
```
SELECT
t0_.id AS id_0,
t0_.time AS time_1,
t0_.slots AS slots_2
FROM time_period t0_ WHERE
t0_.time >= '19:09:00' AND
t0_.time <= '20:09:00';
```
i.e.
>
> `1 245 19:10:00 3`
>
>
> `2 246 19:15:00 3`
>
>
> `3 247 19:20:00 3`... and so on
>
>
>
Could someone help me explain this please.<issue_comment>username_1: You need to build them into datetimes if you want to compare them.
```
CONVERT(DATE, '2018-03-18') +
t0_.time >= CONVERT(DATETIME,
'2018-03-18 19:09') AND # :min_time
#etc
```
Upvotes: 1 <issue_comment>username_2: Apparently I just had to concatenate my date and time field to get datetime field for comparison.
```
SELECT
t0_.id AS id_0,
t0_.time AS time_1,
t0_.slots AS slots_2,
concat('2018-03-18', " ", t0_.time) as x
FROM time_period t0_ WHERE
concat('2018-03-18', " ", t0_.time) >= '2018-03-18 19:09:00'
AND
concat('2018-03-18', " ", t0_.time) <= '2018-03-18 20:09:00'
AND
concat('2018-03-18', " ", t0_.time) >= '2018-03-17 21:05'
ORDER BY t0_.time ASC LIMIT 50
```
Upvotes: 1 [selected_answer]
|
2018/03/17
| 731 | 2,651 |
<issue_start>username_0: Trying to set up a database connection between a Linux/Ubuntu server (client) and a Windows server (host) using the code below, but it fails for some reason. The ip address is ok (pinged it ok), port 3050 is open and username and password are also correct, so what can be the problem? The code below returns "Connection failed!!!". And yes, the php/interbase library is installed.
```
$db_path = '192.*.*.*:C:\folder\DBFILE.IB';
$username = 'USER';
$password = '<PASSWORD>';
$dbh = ibase_connect($db_path, $username, $password) or die('Connection failed!!!');
```
Just an update. It turned out that the connection is ok, and the problem has to do with the username and/or password. The following error is returned by `ibase_errmsg()`
"*Your user name and password are not defined. Ask your database administrator to set up a Firebird login.*" However, the username and password has be triple checked several times over and should be ok.<issue_comment>username_1: Could it possibly be that the backslashes need to be escaped into C:\\folder\\DBFILE.IB and that otherwise the C:\folder\DBFILE.IB is translated to garbage path, which IBASE doesn't find and gives the rather imprecise error msg?
Upvotes: 0 <issue_comment>username_2: I got the same error while trying to connect to interbase XE7(V12) using php ibase\_connect.My interbase server was hosted in a windows 10 machine.
Make sure the php/interbase library is installed and listed in result of `get_loaded_extensions()`.
For my case the problem was in the interbase password digest. For older interbase it uses 'des-crypt' digest and for newer version it uses 'sha-1' digest. I just changed the password digest to 'des-crypt' then it worked.
Here is the steps to change the password digest for interbase using isql.exe .
Find the admib.ib in here `C:\ProgramData\Application Data\Embarcadero\InterBase\gds_db` or under c:\program files then follow the instructions
```
1. SQL> CONNECT "C:\Program Files (x86)\borland\interbase\admin.ib" (hit enter)
2.CON> user 'SYSDBA' password '<PASSWORD>';
3.SQL> ALTER DATABASE SET PASSWORD DIGEST '<PASSWORD>';
4.SQL> UPDATE USERS SET PASSWORD_DIGEST = '<PASSWORD>' WHERE USER_NAME='sitesync';
5.SQL> COMMIT;
```
Then open gsec.exe and type these command
```
gsec -user sysdba -password masterkey (hit enter)
modify sitesync -pw newpassword (hit enter and password changed)
```
Back to sha-1 again
```
6. SQL> ALTER DATABASE SET PASSWORD DIGEST '<PASSWORD>';
7 commit;
```
And that's it. Please be noted I worked for the first time with php and interbase. Please pardon me for any missing details or typos.
Upvotes: 1
|
2018/03/17
| 961 | 2,880 |
<issue_start>username_0: Having trouble figuring out how to lemmatize words from a txt file. I've gotten as far as listing the words, but I'm not sure how to lemmatize them after the fact.
Here's what I have:
```
import nltk, re
nltk.download('wordnet')
from nltk.stem.wordnet import WordNetLemmatizer
def lemfile():
f = open('1865-Lincoln.txt', 'r')
text = f.read().lower()
f.close()
text = re.sub('[^a-z\ \']+', " ", text)
words = list(text.split())
```<issue_comment>username_1: Initialise a `WordNetLemmatizer` object, and lemmatize each word in your lines. You can perform inplace file I/O using the `fileinput` module.
```
# https://stackoverflow.com/a/5463419/4909087
import fileinput
lemmatizer = WordNetLemmatizer()
for line in fileinput.input('1865-Lincoln.txt', inplace=True, backup='.bak'):
line = ' '.join(
[lemmatizer.lemmatize(w) for w in line.rstrip().split()]
)
# overwrites current `line` in file
print(line)
```
`fileinput.input` redirects stdout to the open file when it is in use.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can also try a wrapper around the NLTK's`WordNetLemmatizer` in the `pywsd` package, specifically, <https://github.com/alvations/pywsd/blob/master/pywsd/utils.py#L129>
Install:
```
pip install -U nltk
python -m nltk.downloader popular
pip install -U pywsd
```
Code:
```
>>> from pywsd.utils import lemmatize_sentence
>>> lemmatize_sentence('These are foo bar sentences.')
['these', 'be', 'foo', 'bar', 'sentence', '.']
>>> lemmatize_sentence('These are foo bar sentences running.')
['these', 'be', 'foo', 'bar', 'sentence', 'run', '.']
```
Specifically to your question:
```
from __future__ import print_function
from pywsd.util import lemmatize_sentence
with open('file.txt') as fin, open('outputfile.txt', 'w') as fout
for line in fin:
print(' '.join(lemmatize_sentence(line.strip()), file=fout, end='\n')
```
Upvotes: 0 <issue_comment>username_3: Lemmatizing txt file and replacing only lemmatized words can be done as --`
```
import nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from pywsd.utils import lemmatize_sentence
lmm = WordNetLemmatizer()
ps = PorterStemmer()
new_data= []
with open('/home/rahul/Desktop/align.txt','r') as f:
f1 = f.read()
f2 = f1.split()
en_stops = set(stopwords.words('english'))
hu_stops = set(stopwords.words('hungarian'))
all_words = f2
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~[]'''
#if lemmatization of one string is required then uncomment below line
#data='this is coming rahul schooling met happiness making'
print ()
for line in all\_words:
new\_data=' '.join(lemmatize\_sentence(line))
print (new\_data)
```
---
PS- Do identation as per your need.
Hope this helps!!!
Upvotes: 0
|
2018/03/17
| 908 | 2,749 |
<issue_start>username_0: I am trying to apply `linear-gradient` to html progress bar but it's not applying the gradient
```js
var customColor = '#cf014d';
ReactDOM.render(React.createElement("progress", { max: "100", value: "80",
style: { color: "linear-gradient(to left, #fff, #fff)" } }), document.getElementById('root'));
```
```html
```<issue_comment>username_1: Initialise a `WordNetLemmatizer` object, and lemmatize each word in your lines. You can perform inplace file I/O using the `fileinput` module.
```
# https://stackoverflow.com/a/5463419/4909087
import fileinput
lemmatizer = WordNetLemmatizer()
for line in fileinput.input('1865-Lincoln.txt', inplace=True, backup='.bak'):
line = ' '.join(
[lemmatizer.lemmatize(w) for w in line.rstrip().split()]
)
# overwrites current `line` in file
print(line)
```
`fileinput.input` redirects stdout to the open file when it is in use.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can also try a wrapper around the NLTK's`WordNetLemmatizer` in the `pywsd` package, specifically, <https://github.com/alvations/pywsd/blob/master/pywsd/utils.py#L129>
Install:
```
pip install -U nltk
python -m nltk.downloader popular
pip install -U pywsd
```
Code:
```
>>> from pywsd.utils import lemmatize_sentence
>>> lemmatize_sentence('These are foo bar sentences.')
['these', 'be', 'foo', 'bar', 'sentence', '.']
>>> lemmatize_sentence('These are foo bar sentences running.')
['these', 'be', 'foo', 'bar', 'sentence', 'run', '.']
```
Specifically to your question:
```
from __future__ import print_function
from pywsd.util import lemmatize_sentence
with open('file.txt') as fin, open('outputfile.txt', 'w') as fout
for line in fin:
print(' '.join(lemmatize_sentence(line.strip()), file=fout, end='\n')
```
Upvotes: 0 <issue_comment>username_3: Lemmatizing txt file and replacing only lemmatized words can be done as --`
```
import nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from pywsd.utils import lemmatize_sentence
lmm = WordNetLemmatizer()
ps = PorterStemmer()
new_data= []
with open('/home/rahul/Desktop/align.txt','r') as f:
f1 = f.read()
f2 = f1.split()
en_stops = set(stopwords.words('english'))
hu_stops = set(stopwords.words('hungarian'))
all_words = f2
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~[]'''
#if lemmatization of one string is required then uncomment below line
#data='this is coming rahul schooling met happiness making'
print ()
for line in all\_words:
new\_data=' '.join(lemmatize\_sentence(line))
print (new\_data)
```
---
PS- Do identation as per your need.
Hope this helps!!!
Upvotes: 0
|
2018/03/17
| 1,710 | 5,489 |
<issue_start>username_0: I am using vee validate for form validation. i am using vue transition on displaying validations errors like this:
```
{{ errors.first('name') }}
```
Css:
```
.slide-fade-enter-active {
transition: all .3s ease;
}
.slide-fade-leave-active {
transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter, .slide-fade-leave-to
/* .slide-fade-leave-active below version 2.1.8 */ {
transform: translateX(10px);
opacity: 0;
}
```
Now, when an error is entering the transition is working but when the error is disappearing transition is not working.
why is this happening?<issue_comment>username_1: The transition is working. You see it suddenly blank because there's no `errors.first('name')` to show anymore.
When you add some other string along `errors.first('name')`, say `Error:`, it becomes clear.
```js
Vue.use(VeeValidate);
new Vue({
el: '#demo'
})
```
```css
.slide-fade-enter-active {
transition: all .3s ease;
}
.slide-fade-leave-active {
transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter, .slide-fade-leave-to
/* .slide-fade-leave-active below version 2.1.8 */ {
transform: translateX(10px);
opacity: 0;
}
```
```html
Type something and then erase. And then type again.
Errors: {{ errors.first('name') }}
```
If you really must...
=====================
Consider the amount of additional code, but if you really must do it, you would have to add a **watch** to the `input`'s value and **record the first error** when it happens.
vee-validate does not provide listeners to erros, so this is as good as it currently gets. See demo below.
```js
Vue.use(VeeValidate);
new Vue({
el: '#demo',
data: {
name: "<NAME>",
nameError: ""
},
watch: {
name() {
// two ticks at least, because vee-validate takes one tick to validate
Vue.nextTick().then(Vue.nextTick()).then(() => {
if (this.errors.has('name')) { this.nameError = this.errors.first('name'); }
});
}
}
})
```
```css
.slide-fade-enter-active {
transition: all .3s ease;
}
.slide-fade-leave-active {
transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter, .slide-fade-leave-to
/* .slide-fade-leave-active below version 2.1.8 */ {
transform: translateX(10px);
opacity: 0;
}
```
```html
Erase and error will appear. Type again and error will leave.
Errors: {{ nameError }}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: This is kinda' an old topic, but I figured out a much more easier solution that will work with a minimal amount of code, for everybody who's still searching for one.
What this does, is checking for the error message every time you press a key in the input (the `@keypress` event), saves it into a variable, which is displayed alongside the actual error message in the div, using a OR, making sure that the `error.message` variable never gets `undefined`. That OR guarantees that there will be something displayed, even if the actual error (the one given by VeeValidate) isn't available, up until the animation is finished.
```js
Vue.use(VeeValidate);
new Vue({
el: '#demo',
data() {
return {
error: {
name: null,
},
}
},
methods: {
updateError() {
const message = this.errors.first('name');
if (message) { // check if message isn't undefined
this.error.name = message;
}
},
},
});
```
```css
.slide-fade-enter-active {
transition: all .3s ease;
}
.slide-fade-leave-active {
transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter,
.slide-fade-leave-to {
transform: translateX(10px);
opacity: 0;
}
```
```html
Type something and then erase. And then type again.
Errors: {{ errors.first('name') || error.name }}
```
And if you have multiple inputs you can do this: pass the '$event' variable in the `updateError()` function (becoming `updateError($event)`), and accept it in the declaration. Then, use `srcElement` to get the source element that started that keypress event (in our case an input), and fetch its name/class/id/whatever; depending on that, you can modify its respective variable (in our case `error.name` and `error.email`). The rest is straight forward.
```js
Vue.use(VeeValidate);
new Vue({
el: '#demo',
data() {
return {
error: {
name: null,
email: null,
},
}
},
methods: {
updateError(e) {
const input = e.srcElement.name;
const message = this.errors.first(input);
if (message) { // check if message isn't undefined
if (input === 'name') {
this.error.name = message;
} else if (input === 'email') {
this.error.email = message;
}
}
},
},
});
```
```css
.row {
display: flex;
flex-wrap: wrap;
}
.col {
flex: 0 0 45%;
max-width: 45%;
}
.slide-fade-enter-active {
transition: all .3s ease;
}
.slide-fade-leave-active {
transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter,
.slide-fade-leave-to {
transform: translateX(10px);
opacity: 0;
}
```
```html
Type a name and then erase. And then type again.
Errors: {{ errors.first('name') || error.name }}
Type an email and then erase. And then type again.
Errors: {{ errors.first('email') || error.email }}
```
I hope this helped you!
Upvotes: 1
|
2018/03/17
| 741 | 2,497 |
<issue_start>username_0: I'm having trouble reading a JSON list of numbers into a c# int[] array.
I've tried several suggestions from SO, but none have worked.
How would I go about this using JSON.net?
Extract from JSON file:
```
{
"course": "Norsk",
"grades": [6, 3, 5, 6, 2, 8]
}
```
What I've tried in c#:
```
// Reads the JSON file into a single string
string json = File.ReadAllText(jfile);
Console.WriteLine(json);
// Parsing the information to a format json.net can work with
JObject data = JObject.Parse(json);
JToken jToken = data.GetValue("grades");
jGrades = jToken.Values().ToArray();
```
and:
```
// Reads the JSON file into a single string
string json = File.ReadAllText(jfile);
Console.WriteLine(json);
// Parsing the information to a format json.net can work with
JObject data = JObject.Parse(json);
for (int o = 0; o < 6; o++) {
var grades = from p in data["Info"[i]] select (int)p["grades"[o]];
jGrades.Add(Convert.ToInt32(grades));
}
```
As you can see from the c# extracts, I've tried with both arrays and lists, but I can't get it to work.
With the first example (with an array) I get a **System.NullRefrenceException**, while with the List example, I get several errors, such as **Unable to cast object of type 'whereselectlistiterator'2 [Newtonsoft.JSON] to type 'system.iconvertible'**
Any help of tips are appreciated.<issue_comment>username_1: `JObject.Parse(json)` is your root object
`JObject.Parse(json)["grades"]` is the list/array
All you have to do is : converting the items to appropriate type
```
var list = JObject.Parse(json)["grades"].Select(x => (int)x).ToArray();
```
You can also declare a class
```
public class RootObject
{
public string course { get; set; }
public List grades { get; set; }
}
```
and deserialize whole object as
```
var myobj = JsonConvert.DeserializeObject(json);
var grade = myobj.grades[0];
```
Upvotes: 3 <issue_comment>username_2: I would typically define a class with the relevant properties and simply convert the object.
```
public class CourseReport
{
public string Course { get; set; }
public ICollection Grades { get; set; }
}
// Reads the JSON file into a single string
string json = File.ReadAllText(jfile);
Console.WriteLine(json);
// Parsing the information to a format json.net can work with
var courseReport = JsonConvert.DeserializeObject(json);
foreach (var grade in courseReport.Grades)
{
Console.WriteLine(grade);
}
```
Upvotes: 2
|
2018/03/17
| 642 | 3,029 |
<issue_start>username_0: I'm making a social media app using Android Studio. The problem I'm facing is that whenever pressing the login button and getting a "login successful" message, the app does not immediately open a new activity. I should click it again for it to do so. Here's my OnPostExecute code:
```
protected void onPostExecute(JSONObject result) {
Button button = (Button) findViewById(R.id.btnSignIn);
try {
if (result != null) {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), educationalActivity.class);
startActivityForResult(intent, 0);
}
});
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
```<issue_comment>username_1: Why you set the onClickListener again?
after the "login successful" you can open target activity directly,
you shouldn't set onClickListener (if you set it again it means you should click it again)
change your code as below :
```
protected void onPostExecute(JSONObject result) {
try {
if (result != null) {
Intent intent = new Intent(view.getContext(), educationalActivity.class);
startActivityForResult(intent, 0);
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
```
Upvotes: 1 <issue_comment>username_2: The **AsyncTask** should be call on the `onClick()` event of button, you have called the button `onClick()` on the AsyncTask completion, which is **wrong logic**. For you, the `onClickListner()` is set the first time. The next time you click after the AsyncTask is complete, the intent is fired which takes you to next **Activity**.
Upvotes: 1 <issue_comment>username_3: As the other answers stated, setting an `onClick()` event will require the user to press again in order to open the new activity. I found that declaring a View variable and referencing it to the login button solved the problem:
```
View view = findViewById(R.id.btnSignIn);
try {
if (result != null) {
Intent intent = new Intent(view.getContext(), educationalActivity.class);
startActivityForResult(intent, 0);
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
}
```
Upvotes: 0
|
2018/03/17
| 622 | 2,692 |
<issue_start>username_0: When a user fills the form data which has one input in the name of 'uname' , after submitting the form, the form data is send to the server using socket.io and the user is directed to '/website.html' and the form data is appended to the url like <http://localhost:3000/website.html?uname=rohan>.
In '/website.html', there are some buttons which all directs to some other html files and when we click on the buttons a new socket connection is made.
I just want that when we click on the buttons in '/website.html', server sends the 'uname' value appended in <http://localhost:3000/website.html?uname=rohan> to the client.
P.S. i know a different socket is connection is made on clicking the buttons in '/website.html' different to the socket connection which was made after submitting the form to send the form data to server.<issue_comment>username_1: Why you set the onClickListener again?
after the "login successful" you can open target activity directly,
you shouldn't set onClickListener (if you set it again it means you should click it again)
change your code as below :
```
protected void onPostExecute(JSONObject result) {
try {
if (result != null) {
Intent intent = new Intent(view.getContext(), educationalActivity.class);
startActivityForResult(intent, 0);
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
```
Upvotes: 1 <issue_comment>username_2: The **AsyncTask** should be call on the `onClick()` event of button, you have called the button `onClick()` on the AsyncTask completion, which is **wrong logic**. For you, the `onClickListner()` is set the first time. The next time you click after the AsyncTask is complete, the intent is fired which takes you to next **Activity**.
Upvotes: 1 <issue_comment>username_3: As the other answers stated, setting an `onClick()` event will require the user to press again in order to open the new activity. I found that declaring a View variable and referencing it to the login button solved the problem:
```
View view = findViewById(R.id.btnSignIn);
try {
if (result != null) {
Intent intent = new Intent(view.getContext(), educationalActivity.class);
startActivityForResult(intent, 0);
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
}
```
Upvotes: 0
|
2018/03/17
| 2,287 | 4,361 |
<issue_start>username_0: I would like to pass an unquoted variable name `x` to a `left_join` function. The output I expect is the same as if I ran:
`left_join(mtcars, mtcars, by = c('mpg' = 'mpg'))`
I'm trying this:
```
ff <- function(x) {
x <- enquo(x)
left_join(mtcars, mtcars, by = c(x = x))
}
ff(mpg)
```
>
> Error in match(x, table, nomatch = 0L) : 'match' requires vector
> arguments
>
>
><issue_comment>username_1: You need strings as input for `by` therefore you need to use `quo_name` break a `quosure` and return a string.
```
library(rlang)
library(tidyverse)
ff <- function(x) {
x <- enquo(x)
left_join(mtcars, mtcars, by = quo_name(x))
}
head(ff(mpg))
#> mpg cyl.x disp.x hp.x drat.x wt.x qsec.x vs.x am.x gear.x carb.x cyl.y
#> 1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 6
#> 2 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 6
#> 3 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 6
#> 4 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 6
#> 5 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 4
#> 6 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 4
#> disp.y hp.y drat.y wt.y qsec.y vs.y am.y gear.y carb.y
#> 1 160.0 110 3.90 2.620 16.46 0 1 4 4
#> 2 160.0 110 3.90 2.875 17.02 0 1 4 4
#> 3 160.0 110 3.90 2.620 16.46 0 1 4 4
#> 4 160.0 110 3.90 2.875 17.02 0 1 4 4
#> 5 108.0 93 3.85 2.320 18.61 1 1 4 1
#> 6 140.8 95 3.92 3.150 22.90 1 0 4 2
```
To use `x` for both LHS & RHS of `by`, we need to use `set_names`
Credit to this [answer](https://stackoverflow.com/a/48450170/786542)
```
ff2 <- function(x) {
x <- enquo(x)
by = set_names(quo_name(x), quo_name(x))
left_join(mtcars, mtcars, by = by)
}
head(ff2(mpg))
#> mpg cyl.x disp.x hp.x drat.x wt.x qsec.x vs.x am.x gear.x carb.x cyl.y
#> 1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 6
#> 2 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 6
#> 3 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 6
#> 4 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 6
#> 5 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 4
#> 6 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 4
#> disp.y hp.y drat.y wt.y qsec.y vs.y am.y gear.y carb.y
#> 1 160.0 110 3.90 2.620 16.46 0 1 4 4
#> 2 160.0 110 3.90 2.875 17.02 0 1 4 4
#> 3 160.0 110 3.90 2.620 16.46 0 1 4 4
#> 4 160.0 110 3.90 2.875 17.02 0 1 4 4
#> 5 108.0 93 3.85 2.320 18.61 1 1 4 1
#> 6 140.8 95 3.92 3.150 22.90 1 0 4 2
```
Upvotes: 3 <issue_comment>username_2: Another way of passing a column into a function where the join happens with `"LHS" = "RHS"` could look like this:
```
data("mtcars")
library(tidyverse)
function_left_join <- function(x) {
mtcars %>%
left_join(mtcars, by = names(select(., {{x}})))
}
head(function_left_join(mpg))
#> mpg cyl.x disp.x hp.x drat.x wt.x qsec.x vs.x am.x gear.x carb.x cyl.y
#> 1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 6
#> 2 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 6
#> 3 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 6
#> 4 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 6
#> 5 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 4
#> 6 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 4
#> disp.y hp.y drat.y wt.y qsec.y vs.y am.y gear.y carb.y
#> 1 160.0 110 3.90 2.620 16.46 0 1 4 4
#> 2 160.0 110 3.90 2.875 17.02 0 1 4 4
#> 3 160.0 110 3.90 2.620 16.46 0 1 4 4
#> 4 160.0 110 3.90 2.875 17.02 0 1 4 4
#> 5 108.0 93 3.85 2.320 18.61 1 1 4 1
#> 6 140.8 95 3.92 3.150 22.90 1 0 4 2
```
You can also potentially pass more columns to the `select()` function, in order join on multiple keys
Upvotes: 2
|
2018/03/17
| 673 | 2,401 |
<issue_start>username_0: The `*id` value is initially `0000-0000:c29302`. Once it gets send through the `split` function its value changes to `0000-0000`. I think this has to do with it modifying the original value instead of modifying a temporary value. I want the `*id` value to stay the same. Thanks.
```
typedef struct node {
char *id;
char *clientid;
char *token;
struct node * next;
} credentials;
void split(credentials * head, char delim[]);
int main()
{
credentials * head = NULL;
head = malloc(sizeof(credentials));
head->id = strdup("0000-0000:c29302");
head->clientid = NULL;
head->token = NULL;
head->next = NULL;
split(head, ":");
print_list(head);
}
void split(credentials * head, char *delim)
{
char *token;
char *temp;
credentials * current = head;
while (current != NULL) {
temp = current->id;
int tempNum = 0;
token = strtok(temp, delim);
current->clientid = token;
while(token != NULL)
{
if(tempNum == 0)
{
current->clientid = token;
} else {
current->token = token;
}
token = strtok(NULL, delim);
tempNum++;
}
current = current->next;
}
}
```<issue_comment>username_1: From `man strtok`:
>
> If a delimiter byte is found, it is overwritten with a null byte to terminate the current token, [...]
>
>
>
If you do not want your string to be modified you need to either write your own string-tokenizing function or to work with a copy of your string.
---
Note that if you do continue to use `strtok` (with a copy of your string), remember that the tokens returned by `strtok` are not new strings. They are pointers to points within the string you're working with. That means that when you free that string, all the tokens get freed at the same time.
Upvotes: 2 <issue_comment>username_2: You can use this instead of **strtok**.
```
void strsplit(const char* str, const char d, char** into)
{
if(str != NULL && into != NULL)
{
int n = 0;
int c = 0;
for(int i = 0; str[c] != '\0'; i++,c++)
{
into[n][i] = str[c];
if(str[c] == d)
{
into[n][i] = '\0';
i = -1;
++n;
}
}
}
}
```
Upvotes: 0
|
2018/03/17
| 595 | 2,663 |
<issue_start>username_0: I have the following Play for Scala controller that wraps Spark. At the end of the method I close the context to avoid the problem of having more than one context active in the same JVM:
```
class Test4 extends Controller {
def test4 = Action.async { request =>
val conf = new SparkConf().setAppName("AppTest").setMaster("local[2]").
set("spark.executor.memory","1g");
val sc = new SparkContext(conf)
val rawData = sc.textFile("c:\\spark\\data.csv")
val data = rawData.map(line => line.split(',').map(_.toDouble))
val str = "count: " + data.count()
sc.close
Future { Ok(str) }
}
}
```
The problem that I have is that I don't know how to make this code multi-threaded as two users may access the same controller method at the same time.
**UPDATE**
What I'm thinking is to have N Scala programs receive messages through JMS (using ActiveMQ). Each Scala program would have a Spark session and receive messages from Play. The Scala programs will process requests sequentially as they read the queues. Does this make sense? Are there any other best practices to integrate Play and Spark?<issue_comment>username_1: Its better just move spark context move to new object
```
object SparkContext{
val conf = new SparkConf().setAppName("AppTest").setMaster("local[2]").
set("spark.executor.memory","1g");
val sc = new SparkContext(conf)
}
```
Otherwise for every request new spark context is created according to your design and new JVM is started for each new spark context.
If we talk about best practices its really not good idea to use spark inside play project more better way is to create a micro service which have spark application and play application call this micro service these type of architecture is more flexible, scalable, robust.
Upvotes: 1 <issue_comment>username_2: I don't think is a good idea to execute Spark jobs from a REST api, if you just want to parallelize in your local JVM it doesn't make sense to use Spark since it is designed for distributed computing. It is also not design to be an operational database and it won't scale well when you execute several concurrent queries in the same cluster.
Anyway if you still want to execute concurrent spark queries from the same JVM you should probably use client mode to run the query in a external cluster. It is not possible to launch more than one session per JVM so I would suggest that you share the session in your service, close it just when you are finishing the service.
Upvotes: 0
|
2018/03/17
| 1,575 | 5,316 |
<issue_start>username_0: I am trying to pass in the channel configuration transaction artifact to the order-er using the command:
```
peer channel create -o orderer.example.com:7050 -c $CHANNEL_NAME -f ./channel-artifacts/channel.tx --tls --cafile
/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
```
But I get an error:
```
2018-03-17 20:55:21.380 GMT [main] main -> ERRO 001 Fatal error
when initializing core config : error when reading core
config file: Unsupported Config Type ""
```
What does this error mean? and how can I fix it?
Using `docker ps -a`
```
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5c27fce33911 hyperledger/fabric-tools:latest "/bin/bash" 3 minutes ago Up 3 minutes cli
aabf72f81352 hyperledger/fabric-peer:latest "peer node start" 3 minutes ago Up 3 minutes 0.0.0.0:7051->7051/tcp, 0.0.0.0:7053->7053/tcp peer0.org1.example.com
73ddcafb5ce6 hyperledger/fabric-orderer:latest "orderer" 3 minutes ago Up 3 minutes 0.0.0.0:7050->7050/tcp orderer.example.com
205448f5479a hyperledger/fabric-peer:latest "peer node start" 3 minutes ago Up 3 minutes 0.0.0.0:8051->7051/tcp, 0.0.0.0:8053->7053/tcp peer1.org1.example.com
4e5ba2999f54 hyperledger/fabric-peer:latest "peer node start" 3 minutes ago Up 3 minutes 0.0.0.0:9051->7051/tcp, 0.0.0.0:9053->7053/tcp peer0.org2.example.com
fcc6b25b6422 hyperledger/fabric-peer:latest "peer node start" 3 minutes ago Up 3 minutes 0.0.0.0:10051->7051/tcp, 0.0.0.0:10053->7053/tcp peer1.org2.example.com
2f1536ffe265 dev-peer0.org1.example.com-fabcar-1.0-5c906e402ed29f20260ae42283216aa75549c571e2e380f3615826365d8269ba "chaincode -peer.addβ¦" 24 hours ago Exited (255) 3 minutes ago dev-peer0.org1.example.com-fabcar-1.0
6ae48101bc34 hyperledger/fabric-ca "sh -c 'fabric-ca-seβ¦" 24 hours ago Exited (255) 3 minutes ago 0.0.0.0:7054->7054/tcp ca.example.com
dc9e5bb3cc8e hyperledger/fabric-couchdb "tini -- /docker-entβ¦" 24 hours ago Exited (255) 3 minutes ago 4369/tcp, 9100/tcp, 0.0.0.0:5984->5984/tcp couchdb
```
this is the log of orderer.example.com
[](https://i.stack.imgur.com/2uFeA.png)<issue_comment>username_1: export `FABRIC_CFG_PATH=$PWD`. it will resolve this issue.
Upvotes: 2 <issue_comment>username_2: Can you try running this command: echo $FABRIC\_CFG\_PATH
Whatever value you get, can you navigate to that directory and confirm if you can see the configtx.yaml file in there.
From the docs [here](https://hyperledger-fabric.readthedocs.io/en/release-1.1/build_network.html), it says the error is as a result of inappropriately setting the value of that variable.
Upvotes: 2 <issue_comment>username_3: You should be inside the CLI container to execute the `peer channel create` command.
You will enter the CLI container using the `docker exec` command:
>
> docker exec -it cli bash
>
>
>
If successful you should see the following:
>
> root@0<PASSWORD>300d:/opt/gopath/src/github.com/hyperledger/fabric/peer#
>
>
>
Over there, you should run the `peer channel create` command like this:
>
> root@0<PASSWORD>d:/opt/gopath/src/github.com/hyperledger/fabric/peer# peer channel create -o orderer.example.com:7050 -c $CHANNEL\_NAME -f ./channel-artifacts/channel.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
>
>
>
Before running this command, please note that you should also run commands for creating environment variables for CHANNEL\_NAME and other Environment variables for PEER0 **within this CLI Container**.
Upvotes: 4 [selected_answer]<issue_comment>username_4: This is the error you get when the core.yaml is not found. Like the Mukesh mentioned above, running command within the CLI Container will not throw the Error.
See [this link](https://jira.hyperledger.org/browse/FAB-10523) for more detail.
Upvotes: 2
|
2018/03/17
| 766 | 2,680 |
<issue_start>username_0: I'm trying to map the maximal amount of days without rain using the TRMM dataset in Google Earth Engine. I'm doing this by iterating over the collection and if no rain has fallen, one gets added to the cell (code below). When rain has fallen the value gets multiplied by 0 so the "counter" is reset. Then I would like to store each result of each iteration in a Image collection and then select the maximum value to get the longest consecutive dry period.
But that is the theory. When I put this in a script I get an error while adding the image of one iteration to a list. Does anyone know why this is and how this can be solved?
**Code:**
```
var list = [];
function drylength(current, previous){
var mask = current.remap([0], [1], 0,"precipitation").rename('precipitation');
var sum = mask.add(previous).multiply(mask);
list.push(sum);
return sum;
}
var dataset = TRMM
.filterDate("2015-01-01","2015-02-01")
.sort('system:time_start:');
var totalPrecipitation = dataset.iterate(drylength, dataset.max()
.remap([0], [0], 0, "precipitation")
.rename('precipitation'));
print(list);
print(totalPrecipitation);
Map.addLayer(ee.Image(totalPrecipitation), imageVisParam);
```
Furthermore it appears only 3 items are stored in the list which makes me assume the iteration is more complex than a literal iteration where all images are calculated one by one? Here is an image of the error:
[](https://i.stack.imgur.com/vqeyj.jpg)
Errors written if image is not visible or for search engines:
```
Failed to decode JSON.
Error: Field 'value' of object '{"type":"ArgumentRef","value":null}' is missing or null.
Object: {"type":"ArgumentRef","value":null}.
```
and:
```
Unknown variable references: [_MAPPING_VAR_0_0, _MAPPING_VAR_0_1].
```<issue_comment>username_1: The iterate() function runs on the server, but the list you're attempting to push into is a client-side list; that can't work. If you make it an ee.List, you might be able to get it to work, but you'll have to put it into the previous result (use previous as a dictionary to hold both).
Upvotes: 1 <issue_comment>username_1: Something like this to use a multi-value result:
```
function drylength(current, previous) {
previous = ee.Dictionary(previous)
var mask = current.remap([0], [1], 0,"precipitation").rename('precipitation');
var sum = mask.add(previous.get('sum')).multiply(mask);
var list = previous.get('list')
list = list.push(sum);
return ee.Dictionary({sum: sum, list: list})
}
...
var totalPrecipitation = dataset.iterate(drylength, {sum: max, list: ee.List([])})
```
Upvotes: 2
|
2018/03/17
| 904 | 3,328 |
<issue_start>username_0: I have a Flutter TextField which gets covered by the soft keyboard when the field is selected. I need to scroll the field up and out of the way when the keyboard is displayed. This is a pretty common problem and a solution is presented in this [StackOverflow post](https://stackoverflow.com/questions/47338714/flutter-texteditingcontroller-does-not-scroll-above-keyboard/49341655#49341655).
I think I have the **ScrollController** part figured out but how do I detect when the **TextField** has been selected? There doesn't appear to be any event method (e.g. onFocus(), onSelected(), onTap(), etc).
I tried wrapping the TextField in a **GestureDetector** but that didn't work either -- apparently the event was never captured.
```
new GestureDetector(
child: new TextField(
decoration: const InputDecoration(labelText: 'City'),
),
onTap: () => print('Text Selected'),
),
```
This is such a basic requirement that I know there must be an easy solution.<issue_comment>username_1: I suppose you are looking for [`FocusNode`](https://docs.flutter.io/flutter/widgets/FocusNode-class.html).
To listen to focus change, you can add a listner to the `FocusNode` and specify the `focusNode` to `TextField`.
Example:
```
class TextFieldFocus extends StatefulWidget {
@override
_TextFieldFocusState createState() => _TextFieldFocusState();
}
class _TextFieldFocusState extends State {
FocusNode \_focus = FocusNode();
TextEditingController \_controller = TextEditingController();
@override
void initState() {
super.initState();
\_focus.addListener(\_onFocusChange);
}
@override
void dispose() {
super.dispose();
\_focus.removeListener(\_onFocusChange);
\_focus.dispose();
}
void \_onFocusChange() {
debugPrint("Focus: ${\_focus.hasFocus.toString()}");
}
@override
Widget build(BuildContext context) {
return new Container(
color: Colors.white,
child: new TextField(
focusNode: \_focus,
),
);
}
}
```
[This](https://gist.github.com/collinjackson/50172e3547e959cba77e2938f2fe5ff5) gist represents how to ensure a focused node to be visible on the ui.
Upvotes: 8 [selected_answer]<issue_comment>username_2: The easiest and simplest solution is to add the onTap method on TextField.
```
TextField(
onTap: () {
print('Editing stated $widget');
},
)
```
Upvotes: 5 <issue_comment>username_3: To be notified about a focus event, you can avoid manually managing widget's state, by using the utility classes `FocusScope`, `Focus`.
From the docs (<https://api.flutter.dev/flutter/widgets/FocusNode-class.html>):
>
> Please see the Focus and FocusScope widgets, which are utility widgets that manage their own FocusNodes and FocusScopeNodes, respectively. If they aren't appropriate, FocusNodes can be managed directly.
>
>
>
Here is a simple example:
```
FocusScope(
child: Focus(
onFocusChange: (focus) => print("focus: $focus"),
child: TextField(
decoration: const InputDecoration(labelText: 'City'),
)
)
)
```
Upvotes: 6 <issue_comment>username_4: There is another way if your textfield needs to be disabled for some purpose like mine. for that case, you can wrap your textField with `InkWell` like this,
```
InkWell(
onTap: () {
print('clicked');
},
child: TextField(
enabled: false,
),
);
```
Upvotes: 2
|
2018/03/17
| 820 | 3,001 |
<issue_start>username_0: I'm having trouble creating a stored procedure with one IN and three OUT parameters. Basically I have three queries which I want to put in a stored procedure.
How can I relate the OUT paramters with each of the queries?
```
CREATE OR REPLACE PROCEDURE 'SP_NAME'(
@phone_number IN VARCHAR2
REG OUT INTEGER
EMAIL OUT VARCHAR2
VALID OUT INTEGER )
AS
BEGIN
--I just need 1 or 0 to valid if exists on the table
SELECT COUNT (phone_number) FROM users
WHERE phone_number = @phone_number
-- this should bring me the email a different table
SELECT email FROM details_users
WHERE phone_number = @phone_number
-- and this bring if exists in oooother table
SELECT count(phone_number) FROM suscribers
WHERE phone_number = @phone_number
END;
```<issue_comment>username_1: You may use below queries then assign the result to each of the out parameters. I notice that 1st and 3rd query are the same. Is it copy/paste error? Or you mean phone number is valid or not?
```
SELECT COUNT (phone_number) INTO REG FROM users
WHERE phone_number = @phone_number;
SELECT email INTO EMAIL FROM users
WHERE phone_number = @phone_number;
REG := VALID;
```
Upvotes: 0 <issue_comment>username_2: Your revised business logic features three tables. In the absence of any indication that the tables contents are related it's better to keep them as separate queries.
Here is my solution (featuring valid Oracle syntax).
```
CREATE OR REPLACE PROCEDURE SP_NAME (
p_phone_number IN VARCHAR2
, p_REG OUT INTEGER
, p_EMAIL OUT VARCHAR2
, p_VALID OUT INTEGER )
AS
l_usr_cnt pls_integer;
l_email details_users.email%type;
l_sub_cnt pls_integer;
BEGIN
SELECT COUNT (*) into l_usr_cnt
FROM users u
WHERE u.phone_number = p_phone_number;
begin
select du.email into l_email
from details_users du
where du.phone_number = p_phone_number;
exception
when others then
l_email := null;
end;
SELECT COUNT (*) into l_sub_cnt
FROM suscribers s -- probably a typo :-/
WHERE s.phone_number = p_phone_number;
if l_usr_cnt != 0 then
p_reg := 1; -- "true"
else
p_reg := 0; -- "false"
end if;
p_email := l_email;
if l_sub_cnt != 0 then
p_valid := 1;
else
p_valid := 0;
end if;
END;
```
Note it is permitted to populate an OUT parameter directly from a query, like this:
```
SELECT COUNT (*)
into p_reg
FROM users u
WHERE u.phone_number = p_phone_number;
```
However, it is accepted good practice to work with local variables and only assign OUT parameters at the end of the procedure. This is to ensure consistent state is passed to the calling program, (which matters particularly if the called procedure throws an exception).
Also, I prefixed all the parameter names with `p_`. This is also optional but good practice. Having distinct namespaces is always safer, but it especially matters when the parameter names would otherwise match table column names (i.e. `phone_number`).
Upvotes: 1
|
2018/03/17
| 737 | 2,852 |
<issue_start>username_0: I created an SPA with Laravel 5.6, Vue 2.5 and Laravel Passport which is working quite well. I really love Laravel and Vue as they make building SPAs with APIs very easy and a lot of fun.
After setting up Laravel Passport as described in [the docs](https://laravel.com/docs/5.6/passport#consuming-your-api-with-javascript) the login as well as calls to the API are working as expected based on the 'laravel\_token' which is correctly returned and stored in the cookie.
However, my problem is that my users are using the app for a pretty long time, without reloading the page but only performing calls against the API with axios. Somehow Laravel does not refresh the 'laravel\_token' (and the corresponding cookie) in API calls (it does so, when I call a 'web' route). Consequently, the 'laravel\_token' expires t some point and the user needs to log in again.
How can I force Laravel to refresh the 'laravel\_token' (and thereby prolong its validity) with every call of an API route from axios?
Any help is very much appreciated!<issue_comment>username_1: I solved a similar issues in the past by creating a simple route (in the `web` middleware group) to keep the session alive for as long as the browser tab is open.
In **routes/web.php**:
```php
Route::get('/keep-alive', function () {
return response()->json(['ok' => true]);
})->middleware('auth');
```
And then ping this route periodically with javascript:
```js
setInterval(() => {
axios.get('/keep-alive')
.then(() => {})
.catch(() => {})
}, 600000)
```
I go into a little more detail here: <https://stackoverflow.com/a/57290268/6038111>
Upvotes: 2 <issue_comment>username_2: Axios has a way to "intercept" / see if a call failed. Inside the error callback I am seeing if it was an unauthenticated error and simply reloading the page.
Admittedly, I would love to be able to write another Axios call inside the error caught block to grab another session token "laravel\_token", but have yet to find a way to do it. Reloading the page will refresh the laravel\_token though, so it solves my problem for now. Β―\\_(γ)\_/Β―
After-thought: I'm actually thinking you probably couldn't refresh the laravel\_token through an Axios call because you'e already dropped the session. I'm guessing you have to do it this way.
```
// Refresh Laravel Session for Axios
window.axios.interceptors.response.use(
function(response) {
// Call was successful, don't do anything special.
return response;
},
function(error) {
if (error.response.status === 401) {
// Reload the page to refresh the laravel_token cookie.
location.reload();
}
// If the error is not related to being Unauthorized, reject the promise.
return Promise.reject(error);
}
);
```
Upvotes: 0
|
2018/03/17
| 606 | 2,316 |
<issue_start>username_0: I'm trying to understand what the formal names are for the pieces of text that make up running something from the terminal/command line. Take the following example:
`npm install lodash --save`
What are `npm`, `install`, `lodash`, and `--save` named if you were to break them down one by one? Was thinking the below, but not sure and am curious to find out. Also wondering what you would call the whole piece of text.
* npm = program?
* install = command?
* lodash = argument?
* --save = option?<issue_comment>username_1: I solved a similar issues in the past by creating a simple route (in the `web` middleware group) to keep the session alive for as long as the browser tab is open.
In **routes/web.php**:
```php
Route::get('/keep-alive', function () {
return response()->json(['ok' => true]);
})->middleware('auth');
```
And then ping this route periodically with javascript:
```js
setInterval(() => {
axios.get('/keep-alive')
.then(() => {})
.catch(() => {})
}, 600000)
```
I go into a little more detail here: <https://stackoverflow.com/a/57290268/6038111>
Upvotes: 2 <issue_comment>username_2: Axios has a way to "intercept" / see if a call failed. Inside the error callback I am seeing if it was an unauthenticated error and simply reloading the page.
Admittedly, I would love to be able to write another Axios call inside the error caught block to grab another session token "laravel\_token", but have yet to find a way to do it. Reloading the page will refresh the laravel\_token though, so it solves my problem for now. Β―\\_(γ)\_/Β―
After-thought: I'm actually thinking you probably couldn't refresh the laravel\_token through an Axios call because you'e already dropped the session. I'm guessing you have to do it this way.
```
// Refresh Laravel Session for Axios
window.axios.interceptors.response.use(
function(response) {
// Call was successful, don't do anything special.
return response;
},
function(error) {
if (error.response.status === 401) {
// Reload the page to refresh the laravel_token cookie.
location.reload();
}
// If the error is not related to being Unauthorized, reject the promise.
return Promise.reject(error);
}
);
```
Upvotes: 0
|
2018/03/17
| 563 | 2,104 |
<issue_start>username_0: Is there a way I can address legend items individually?
I'd like to style them, make some appear smaller, some disabled, stuff like that.
If I were to define a module/plugin, how would I manipulate the array of items?
```js
legend: {
item: {
rules: []
}
}
```
doesn't work.<issue_comment>username_1: I solved a similar issues in the past by creating a simple route (in the `web` middleware group) to keep the session alive for as long as the browser tab is open.
In **routes/web.php**:
```php
Route::get('/keep-alive', function () {
return response()->json(['ok' => true]);
})->middleware('auth');
```
And then ping this route periodically with javascript:
```js
setInterval(() => {
axios.get('/keep-alive')
.then(() => {})
.catch(() => {})
}, 600000)
```
I go into a little more detail here: <https://stackoverflow.com/a/57290268/6038111>
Upvotes: 2 <issue_comment>username_2: Axios has a way to "intercept" / see if a call failed. Inside the error callback I am seeing if it was an unauthenticated error and simply reloading the page.
Admittedly, I would love to be able to write another Axios call inside the error caught block to grab another session token "laravel\_token", but have yet to find a way to do it. Reloading the page will refresh the laravel\_token though, so it solves my problem for now. Β―\\_(γ)\_/Β―
After-thought: I'm actually thinking you probably couldn't refresh the laravel\_token through an Axios call because you'e already dropped the session. I'm guessing you have to do it this way.
```
// Refresh Laravel Session for Axios
window.axios.interceptors.response.use(
function(response) {
// Call was successful, don't do anything special.
return response;
},
function(error) {
if (error.response.status === 401) {
// Reload the page to refresh the laravel_token cookie.
location.reload();
}
// If the error is not related to being Unauthorized, reject the promise.
return Promise.reject(error);
}
);
```
Upvotes: 0
|
2018/03/17
| 787 | 2,164 |
<issue_start>username_0: I'm trying to `scale` my `data` and add it to my original data with a new name. I was wondering though why my scaled data does not get the new name assigned to it?
Here is what I tried:
```
data <- mtcars["wt"]
d <- scale(data)
data[, paste0(names(data), ".bbb") ] <- d
data
wt wt ## HERE 2nd column name has not changed I expect it to be "wt.bbb"
Mazda RX4 2.620 -0.610399567
Mazda RX4 Wag 2.875 -0.349785269
```<issue_comment>username_1: Because `d` is a matrix with a column already having a name, and it happens that this name wins. Few minimal changes to your approach to fix that would be:
```
data[, paste0(names(data), ".bbb") ] <- d[, 1]
data[, paste0(names(data), ".bbb") ] <- as.numeric(d)
data[, paste0(names(data), ".bbb") ] <- as.vector(d)
data[, paste0(names(data), ".bbb") ] <- c(d)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Go take a look at ?scale() - you'll see that what you return is not just a vector of numbers, but actually a matrix. Therefore, you'll need a little more noodling to get what you want.
```
data <- mtcars["wt"]
scaled_matrix <- scale(data)
class(scaled_matrix)
scaled_values <- scaled_matrix[1:32]
class(scaled_values)
```
dplyr version
```
data %>%
mutate(your_name_here = d)
```
non-dplyr version
```
df <- cbind(data, "your_name_here" = scaled_values)
```
Upvotes: 0 <issue_comment>username_3: Why not just do
```
df <- mtcars
df$wt.bbb <- scale(df$wt)
```
Upvotes: 1 <issue_comment>username_4: >
> I was wondering though why my scaled data does not get the new name assigned to it?
>
>
>
It is because
```
class(d)
#R> [1] "matrix"
colnames(d)
#R> [1] "wt"
```
Thus, you could do
```
data <- mtcars["wt"]
data[paste0(names(data), ".bbb")] <- unname(scale(data))
data
#R> wt wt.bbb
#R>Mazda RX4 2.620 -0.61040
#R>Mazda RX4 Wag 2.875 -0.34979
#R>Datsun 710 2.320 -0.91700
#R>Hornet 4 Drive 3.215 -0.00230
#C> [output abbreviated]
```
See `help("print.data.frame")` and call `format` with a matrix which has column names.
Upvotes: 0
|
2018/03/17
| 1,073 | 4,063 |
<issue_start>username_0: I need a way to visually represent a random web page on the internet.
Let's say for example [this](https://www.reddit.com/r/food/comments/85rm0d/homemade_chocolate_banana_bread_with_nuts/) web page.
Currently, these are the standard assets I can use:
* **Favicon**: Too small, too abstract.
* **Title**: Very specific but poor visual aesthetics.
* **URL**: Nobody cares to read.
* **Icon**: Too abstract.
* **Thumbnail**: Hard to get, too ugly (many elements crammed in a small space).
I need to visually represent a random website in a way that is very meaningful and inviting for others to click on it.
I need something like what Facebook does when you share a link:
[](https://i.stack.imgur.com/wTxYB.png)
It scraps the link for images and then creates a beautiful meaningful tile which is inviting to click on.
[](https://i.stack.imgur.com/RtM4Q.png)
Any way I can scrape the images and text from websites? I'm primarily interested in a Objective-C/JavaScript combo but anything will do and will be selected as an approved answer.
Edit: Re-wrote the post and changed the title.<issue_comment>username_1: You can develop your own **Link Preview plugin** or use existing third party available plugins.
Posting example here is not possible. But i can URL of popular Link Preview plugins. Which may free or paid.
* **[Link Preview](https://github.com/LeonardoCardoso/Link-Preview)**
* **[jQuery Preview](https://github.com/embedly/jquery-preview)**:
You can check your url demo [here](http://embed.ly/docs/explore/oembed?url=https%3A%2F%2Fwww.reddit.com%2Fr%2Ffood%2Fcomments%2F85rm0d%2Fhomemade_chocolate_banana_bread_with_nuts%2F) , Which gives response in **JSON** and **Raw** Data
You can use API also.
Hope it helps.
Upvotes: 1 <issue_comment>username_2: This is what the OpenGraph standard is for. For instance, if you go to the Reddit post in the example, you can view the page information provided by HTML tags (all the ones with names starting with 'og'):
[](https://i.stack.imgur.com/mI9wT.png)
However, it is not possible for you to get the data from inside a web browser; CORS prevents the request to the URL. In fact, what Facebook seems to do is send the URL to their servers and have them perform a request to get the required information, and sending it back.
Upvotes: 2 <issue_comment>username_3: Websites will often provide meta information for user friendly social media sharing, such as [Open Graph protocol tags](http://ogp.me/). In fact, in your own example, the reddit page has Open Graph tags which make up the information in the Link Preview (look for meta tags with **og:** properties).
A fallback approach would be to implement site specific parsing code for most popular websites that don't already conform to a [standardized format](https://www.w3.org/TR/xhtml-rdfa-primer/) or to try and generically guess what the most prominent content on a given website is (for example, biggest image above the fold, first few sentences of the first paragraph, text in heading elements etc).
Problem with the former approach is that you you have to maintain the parsers as those websites change and evolve and with the latter that you simply cannot reliably predict what's important on a page and you can't expect to always find what you're looking for either (images for the thumbnail, for example).
Since you will never be able to generate meaningful previews for a 100% of the websites, it boils down to a simple question. What's an acceptable rate of successful link previews? If it's close to what you can get parsing standard meta information, I'd stick with that and save myself a lot of headache. If not, alternatively to the libraries shared above, you can also have a look at paid services/APIs which will likely cover more use cases than you could on your own.
Upvotes: 4 [selected_answer]
|
2018/03/17
| 3,951 | 10,757 |
<issue_start>username_0: I want to convert this nested loops in recursion. How do I achieve this?
```
for(let i = 0; i < 5; i++) {
for(let j = 0; j < 5; j++) {
console.log(i,j);
}
}
```<issue_comment>username_1: This is an alternative.
This approach uses param initialization with comma operator *(just to make the code shorter)*.
Additionally, an operator param (callback) to execute any logic for each iteration.
```js
function loop(n, operator, i = 0, j = 0) { // Param initialization.
if (j === n) (j = 0, i++); // Comma operator.
if (i === n) return;
operator(i, j);
loop(n, operator, i, ++j);
}
loop(5, (i, j) => console.log(i, j));
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 1 <issue_comment>username_2: You could recurse by taking a depth and the values to iterate:
```
function loop(start, end, depth, exit, ...args){
for(let i = start; i < end; i++)
depth ? loop(start, end, depth - 1, exit, ...args, i) : exit(...args, i);
}
```
Usable as:
```
loop(0, 5, 1, (i, j) => console.log(i, j))
```
The only real usecase would be deeper loops, e.g. [this one](http://jsbin.com/zopuhusice/edit?console)
---
If you want it completely without for:
```
const range = (start, end, cb) =>
(cb(start), start + 1 >= end || range (start + 1, end, cb));
function loop(start, end, depth, exit, ...args){
range(start, end, i =>
depth ? loop(start, end, depth - 1, exit, ...args, i) : exit(...args, i));
}
```
[Try it](http://jsbin.com/xohiselohi/1/edit?console)
Upvotes: 1 <issue_comment>username_3: I don't recommend this but you can do following(as it is difficult to read, for readability and understandability your code is best).
```js
function forLoop(i,j){
if(j===0){
if(i!==0)
forLoop(i-1,4);
console.log(i,j);
}
else{
forLoop(i,j-1);
console.log(i,j);
}
}
forLoop(4,4);
```
Upvotes: 1 <issue_comment>username_4: Here another example of this recursion:
```
function loop(i,j,limitI,limitJ){
if(i>=limitI) return;
if(j>=limitJ) loop(i+1,0,limitI,limitJ);
else{
console.log(i,j);
loop(i,j+1,limitI,limitJ)
}
}
loop(0,0,4,4);
```
Upvotes: 2 <issue_comment>username_5: Here's my rendition:
```js
function nested(i, j, maxI, maxJ) {
if (i == maxI) return
console.log(i, j)
if (i < maxI) {
++j < maxJ ? nested(i, j, maxI, maxJ) : nested(++i, 0, maxI, maxJ)
}
}
nested(0, 0, 5, 5)
```
Upvotes: 1 <issue_comment>username_6: suggested solution
```
function recurse(arg1=0, arg2=0, cb) {
if ( arg2 <= 5 ) {
let _l = arg2++;
if ( arg1 === 5 )
return ;
if ( ++_l === 6 ) {
arg2 = 0;
cb(arg1++, arg2);
recurse(arg1, arg2, cb);
} else {
cb(arg1, arg2 - 1);
recurse(arg1, arg2, cb);
}
}
}
recurse( 0 , 0 , (i,j) => console.log(i,j));
```
Upvotes: 0 <issue_comment>username_7: You could use an array for limit and values. The order is reversed, because of the incrementing of the lowest index first.
This works for an arbitrary count of nested loops and it allowes to use an arbitrary limit of the max values.
```js
function iter(limit, values = limit.map(_ => 0)) {
console.log(values.join(' '));
values = values.reduce((r, v, i) => {
r[i] = (r[i] || 0) + v;
if (r[i] >= limit[i]) {
r[i] = 0;
r[i + 1] = (r[i + 1] || 0) + 1;
}
return r;
}, [1]);
if (values.length > limit.length) {
return;
}
iter(limit, values);
}
iter([2, 3]);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 1 <issue_comment>username_8: Generic function `product` calculates the [Cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) of its inputs - You can polyfill [Array.prototype.flatMap](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) if it's not already in your environment
```js
Array.prototype.flatMap = function (f, context)
{
return this.reduce ((acc, x) => acc.concat (f (x)), [])
}
const product = (first = [], ...rest) =>
{
const loop = (comb, first, ...rest) =>
rest.length === 0
? first.map (x => [ ...comb, x ])
: first.flatMap (x => loop ([ ...comb, x ], ...rest))
return loop ([], first, ...rest)
}
const suits =
['β€', 'β‘', 'β§', 'β’']
const ranks =
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
for (const card of product (ranks, suits))
console.log (card)
// [ 'A', 'β€' ]
// [ 'A', 'β‘' ]
// [ 'A', 'β§' ]
// [ 'A', 'β’' ]
// [ '2', 'β€' ]
// ...
// [ 'Q', 'β§' ]
// [ 'K', 'β€' ]
// [ 'K', 'β‘' ]
// [ 'K', 'β§' ]
// [ 'K', 'β’' ]
```
`product` is a variadic function (by use of a [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters)) which accepts 1 or more inputs
```
const range = (min = 0, max = 0) =>
max < min
? []
: [ min, ...range (min + 1, max) ]
const r =
range (0, 2)
for (const comb of product (r, r, r))
console.log (comb)
// [ 0, 0, 0 ]
// [ 0, 0, 1 ]
// [ 0, 0, 2 ]
// [ 0, 1, 0 ]
// ...
// [ 2, 1, 2 ]
// [ 2, 2, 0 ]
// [ 2, 2, 1 ]
// [ 2, 2, 2 ]
```
Using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), you can effectively create nested loops
```
for (const [ i, j ] of product (range (0, 5), range (0, 5)))
console.log ("i %d, j %d", i, j)
// i 0, j 0
// i 0, j 1
// i 0, j 2
// i 0, j 3
// i 0, j 4
// i 0, j 5
// i 1, j 0
// ...
// i 4, j 5
// i 5, j 0
// i 5, j 1
// i 5, j 2
// i 5, j 3
// i 5, j 4
// i 5, j 5
```
`product` can also be written using [generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function%2A) - below, we find all perfect [Pythagorean triples](https://en.wikipedia.org/wiki/Pythagorean_triple) under 20
```js
const product = function* (first, ...rest)
{
const loop = function* (comb, first, ...rest)
{
if (rest.length === 0)
for (const x of first)
yield [ ...comb, x ]
else
for (const x of first)
yield* loop ([ ...comb, x ], ...rest)
}
yield* loop ([], first, ...rest)
}
const range = (min = 0, max = 0) =>
max < min
? []
: [ min, ...range (min + 1, max) ]
const pythagTriple = (x, y, z) =>
(x * x) + (y * y) === (z * z)
const solver = function* (max = 20)
{
const N = range (1, max)
for (const [ x, y, z ] of product (N, N, N))
if (pythagTriple (x, y, z))
yield [ x, y, z ]
}
console.log ('solutions:', Array.from (solver (20)))
// solutions:
// [ [ 3, 4, 5 ]
// , [ 4, 3, 5 ]
// , [ 5, 12, 13 ]
// , [ 6, 8, 10 ]
// , [ 8, 6, 10 ]
// , [ 8, 15, 17 ]
// , [ 9, 12, 15 ]
// , [ 12, 5, 13 ]
// , [ 12, 9, 15 ]
// , [ 12, 16, 20 ]
// , [ 15, 8, 17 ]
// , [ 16, 12, 20 ]
// ]
```
>
> I think using `map` (and `reduce`), while it allows for more complex recursive structures as you demonstrate, is actually an implicit `for` loop, which does not really answer the question on how to convert one into a recurrence. However, if you also defined a recursive `map` and `reduce`, then it would be OK :) - username_9
>
>
>
Your wish is my command :D
```js
const Empty =
Symbol ()
const concat = (xs, ys) =>
xs.concat (ys)
const append = (xs, x) =>
concat (xs, [ x ])
const reduce = (f, acc = null, [ x = Empty, ...xs ]) =>
x === Empty
? acc
: reduce (f, f (acc, x), xs)
const mapReduce = (m, r) =>
(acc, x) => r (acc, m (x))
const map = (f, xs = []) =>
reduce (mapReduce (f, append), [], xs)
const flatMap = (f, xs = []) =>
reduce (mapReduce (f, concat), [], xs)
const product = (first = [], ...rest) =>
{
const loop = (comb, first, ...rest) =>
rest.length === 0
? map (x => append (comb, x), first)
: flatMap (x => loop (append (comb, x), ...rest), first)
return loop ([], first, ...rest)
}
const suits =
['β€', 'β‘', 'β§', 'β’']
const ranks =
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
for (const card of product (ranks, suits))
console.log (card)
// same output as above
```
Upvotes: 2 <issue_comment>username_9: Here's an outline of a "[recurrence relation](https://en.wikipedia.org/wiki/Recurrence_relation)," where "each further term of the sequence ... is defined as a function of the preceding terms."
As you are probably aware, recursive functions usually have at least one base case, terminating the recursion, and at least one recursive call. To find a pattern, let's examine the sequence:
```
0,0
0,1
0,2
0,3
0,4
1,0
1,2
...
```
Our base case, where the call to a preceding parameter terminates, seems to be `0,0`. But this is also where the console logs begin, which means we first have to call all the way back to the base case. For convenience, let's assume the function expects positive parameters:
```
function f(i, j){
if (i == 0 && j == 0){
console.log(i,j);
return;
}
}
```
We can also notice that the outer loop, the `i`, stays constant for each cycle of `j`s:
```
function f(i, j){
if (i == 0 && j == 0){
console.log(i,j);
return;
}
if (j == 0)
// ... what happens here?
}
```
but here we get stuck. When `j` is greater than zero, we can determine that the current term came from `f(i, j - 1)`, but if `j` is zero in the current term, we have no way of formulating what it was in the preceding term. We need one more parameter:
```js
function f(i, j, jj){
if (i == 0 && j == 0){
console.log(i,j);
return;
}
if (j == 0)
f(i - 1, jj, jj);
else
f(i, j - 1, jj);
console.log(i,j);
}
f(4,4,4);
```
Upvotes: 1 <issue_comment>username_10: Transforming a nested for loop into its recursive counterpart is surprisingly hard. Good question!
You can transform every loop (without a stack) into a tail recursive algorithm. So this rule should hold for a nested loop too.
I think we need two distinct functions to get something equivalent to your two nested loops:
```js
const loop = ([i, j], [k, l]) => {
const loop_ = (k_, l_) => {
if (k_ >= l_) return;
else {
console.log(i, k_);
loop_(k_ + 1, l_);
}
};
if (i >= j) return;
else {
loop_(k, l);
loop([i + 1, j], [k, l]);
}
};
loop([0, 5], [0, 5]);
```
You have to pass ranges for both the out and the inner loop.
As you can see both recursive calls are in tail position. I think this is the closest equivalent we can get.
Upvotes: 1
|
2018/03/17
| 2,417 | 9,907 |
<issue_start>username_0: ### Question
What is the benefit of applying locks to the below statement?
Similarly, what issue would we see if we didn't include these hints? i.e. Do they prevent a race condition, improve performance, or maybe something else? Asking as perhaps they're included to prevent some issue I've not considered rather than the race condition I'd assumed.
NB: This is an overflow from a question asked here: [SQL Threadsafe UPDATE TOP 1 for FIFO Queue](https://stackoverflow.com/questions/49338306/sql-threadsafe-update-top-1-for-fifo-queue)
### The Statement In Question
```
WITH nextRecordToProcess AS
(
SELECT TOP(1) Id, StatusId
FROM DemoQueue
WHERE StatusId = 1 --Ready for processing
ORDER BY DateSubmitted, Id
)
UPDATE nextRecordToProcess
SET StatusId = 2 --Processing
OUTPUT Inserted.Id
```
### Requirement
* The SQL is used to retrieve an unprocessed record from a queue.
* The record to be obtained should be the first record in the queue with status Ready (StatusId = 1).
* There may be multiple workers/sessions processing messages from this queue.
* We want to ensure that each record in the queue is only picked up once (i.e. by a single worker), and that each worker processes messages in the order in which they appear in the queue.
* It's OK for one worker to work faster than another (i.e. if Worker A picks up record 1 then Worker B picks up record 2 it's OK if worker B completes the processing of record 2 before Worker A has finished processing record 1). We're only concerned within the context of picking up the record.
* There's no ongoing transaction; i.e. we just want to pick up the record from the queue; we don't need to keep it locked until we come back to progress the status from `Processing` to `Processed`.
### Additional SQL for Context:
```
CREATE TABLE Statuses
(
Id SMALLINT NOT NULL PRIMARY KEY CLUSTERED
, Name NVARCHAR(32) NOT NULL UNIQUE
)
GO
INSERT Statuses (Id, Name)
VALUES (0,'Draft')
, (1,'Ready')
, (2,'Processing')
, (3,'Processed')
, (4,'Error')
GO
CREATE TABLE DemoQueue
(
Id BIGINT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED
, StatusId SMALLINT NOT NULL FOREIGN KEY REFERENCES Statuses(Id)
, DateSubmitted DATETIME --will be null for all records with status 'Draft'
)
GO
```
### Suggested Statement
In the various blogs discussing queues, and in the question which caused this discussion, it's suggested that the above statement be changed to include lock hints as below:
```
WITH nextRecordToProcess AS
(
SELECT TOP(1) Id, StatusId
FROM DemoQueue WITH (UPDLOCK, ROWLOCK, READPAST)
WHERE StatusId = 1 --Ready for processing
ORDER BY DateSubmitted, Id
)
UPDATE nextRecordToProcess
SET StatusId = 2 --Processing
OUTPUT Inserted.Id
```
### My Understanding
I understand that were locking required the benefits of these hints would be:
* UPDLOCK: Because we're selecting the record to update it's status we need to ensure that any other sessions reading this record after we've read it but before we've updated it won't be able to read the record with the intent to update it (or rather, such a statement would have to wait until we've performed our update and released the lock before the other session could see our record with its new value).
* ROWLOCK: Whilst we're locking the record, we want to ensure that our lock only impacts the row we're locking; i.e. as we don't need to lock many resources / we don't want to impact other processes / we want other sessions to be able to read the next available item in the queue even if that item's in the same page as our locked record.
* READPAST: If another session is already reading an item from the queue, rather than waiting for that session to release it's lock, our session should pick the next available (not locked) record in the queue.
i.e. Were we running the below code I think this would make sense:
```
DECLARE @nextRecordToProcess BIGINT
BEGIN TRANSACTION
SELECT TOP (1) @nextRecordToProcess = Id
FROM DemoQueue WITH (UPDLOCK, ROWLOCK, READPAST)
WHERE StatusId = 1 --Ready for processing
ORDER BY DateSubmitted, Id
--and then in a separate statement
UPDATE DemoQueue
SET StatusId = 2 --Processing
WHERE Id = @nextRecordToProcess
COMMIT TRANSACTION
--@nextRecordToProcess is then returned either as an out parameter or by including a `select @nextRecordToProcess Id`
```
However when the select and update occur in the same statement I'd have assumed that no other session could read the same record between our session's read & update; so there'd be no need for explicit lock hints.
Have I misunderstood something fundamentally with how locks work; or is the suggestion for these hints related to some other similar but different use case?<issue_comment>username_1: tl;dr
=====
They're for performance optimisation in a high concurrency dedicated queue table scenario.
Verbose
=======
I think I've found the answer by finding a [related SO answer](https://stackoverflow.com/a/3643282/361842) by [this quoted blog's](http://rusanu.com/2010/03/26/using-tables-as-queues/) author.
It seems that this advice is for a very specific scenario; where the table being used as the queue is **dedicated** as a queue; i.e. the table is not used for any other purpose. In such a scenario the lock hints make sense. They have nothing to do with preventing a race condition; they're to improve performance in high concurrency scenarios by avoiding (very short term) blocking.
* The `ReadPast` lock improves the performance in high concurrency scenarios; there's no waiting for the currently read record to be released; the only thing locking it will be another "Queue Worker" process, so we can safely skip knowing that that worker's dealing with this record.
* The `RowLock` ensures that we don't lock more than one row at a time, so the next worker to request a message will get the next record rather than skipping several records because they're in a locked record's page.
* The `UpdLock` is used to get a lock; i.e. `RowLock` says what to lock but doesn't say that there must be a lock, and `ReadPast` determines the behaviour when encountering other locked records, so again doesn't cause a lock on the current record. I suspect this is not explicitly needed as SQL would acquire it in the background anyway (in fact, in the linked SO answer only `ReadPast` is specified); but was included in the block post for completeness / to explicitly show the lock which SQL would be implicitly causing in the background anyway.
**However** that post is written for a **dedicated queue table**. Where the table is used for other things (e.g. in [the original question](https://stackoverflow.com/questions/49338306/sql-threadsafe-update-top-1-for-fifo-queue) it was a table holding invoice data, which happened to have a column used to track what had been printed), that advice may not be desirable. i.e. By using a `ReadPast` lock you're jumping over all locked records; and there's no guarantee that those records are locked by another worker processing your queue; they may be locked for some completely unrelated purpose. That will then break the FIFO requirement.
Given this, I think [my answer](https://stackoverflow.com/a/49340199/361842) on the linked question stands. i.e. Either create a dedicated table to handle the queue scenario, or consider the other options and their pros and cons in the context or your scenario.
Upvotes: 1 <issue_comment>username_2: John is right in as these are optimizations, but in SQL world these optimizations can mean the difference between 'fast' vs. 'unbearable size-of-data slow' and/or the difference between 'works' vs. 'unusable deadlock mess'.
The readpast hint is clear. For the other two, I feel I need to add a bit more context:
* ROWLOCK hint is to prevent page lock granularity scans. The lock granularity (row vs. page) is decided upfront when the query starts and is based on an estimate of the number pages that the query will scan (the third granularity, table, will only be used in special cases and does not apply here). Normally dequeue operations should never have to scan so many pages so that page granularity is considered by the engine. But I've seen 'in the wild' cases when the engine decided to use page lock granularity, and this leads to blocking and deadlocks in dequeue
* UPDLOCK is needed to prevent the upgrade lock deadlock scenario. The UPDATE statement is logically split into a search for the rows that need to be updated and then update the rows. The search needs to lock the rows it evaluates. If the row qualifies (meets the WHERE condition) then the row is updated, and update is always an exclusive lock. So the question is how do you lock the rows during the search? If you use a shared lock then two UPDATE will look at the same row (they can, since the shared lock allows them), both decide the row qualifies and both try to upgrade the lock to exclusive -> deadlock. If you use exclusive locks during the search the deadlock cannot happen, but then UPDATE will conflict on all rows evaluated with any other read, even if the row does not qualifies (not to mention that Exclusive locks cannot be released early w/o breaking [two-phase-locking](https://en.wikipedia.org/wiki/Two-phase_locking)). This is why there is an U mode lock, one that is compatible with Shared (so that UPDATE evaluation of candidate rows does not block reads) but is incompatible with another U (so that two UPDATEs do not deadlock). There are two reasons why the typical CTE based dequeue needs this hint:
1. because is a CTE the query processing does not understand always that the SELECT inside the CTE is the target of an UPDATE and should use U mode locks and
2. the dequeue operation will always go after the same rows to update (the rows being 'dequeued') so deadlocks are frequent.
Upvotes: 3 [selected_answer]
|
2018/03/17
| 1,658 | 6,744 |
<issue_start>username_0: I have been trying to retrieve only the username data saved in firebase and have it displayed in a text view on navigation drawer but I either keep getting errors and app crashes or nothing gets displayed in the text view and app doesn't crash. app doesn't crash with this code.

This is my database

Data Model
```
public class users {
private String userID;
private String userEmail;
private String userName;
private String userUsername;
public users() {
}
public users(String userID, String userEmail, String userName, String userUsername) {
this.userID = userID;
this.userEmail = userEmail;
this.userName = userName;
this.userUsername = userUsername;
}
public String getUserID() {
return userID;
}
public String getUserEmail() {
return userEmail;
}
public String getUserName() {
return userName;
}
public String getUserUsername() {
return userUsername;
}
public void setUserID(String userID) {
this.userID = userID;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setUserUsername(String userUsername) {
this.userUsername = userUsername;
}
}
```
Main Activity
```
//ASSIGNING FIREBASE OBJECTS.
mAuth = FirebaseAuth.getInstance();
mFire = FirebaseDatabase.getInstance();
user = mAuth.getCurrentUser();
userID = user.getUid();
mDatabase = mFire.getReference("users");
usernameRef = mDatabase.child(userID);
//METHODS
checkIfUserSignedIN();
InitImgLoader();
setProfileImg();
//NAVIGATION LAYOUT.
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//HEADER VIEW LAYOUT.
username = findViewById(R.id.Username_onDrawer);
View headView = navigationView.getHeaderView(0);
ImageView pp = headView.findViewById(R.id.profile_image);
pp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(i);
}
});
usernameRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.child("userUsername").getChildren()){
users usernamE = new users();
usernamE.setUserUsername(ds.child(userID).getValue(users.class).getUserUsername());
username.setText(usernamE.getUserUsername());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
```
[I'm trying to set username below this image view](https://i.stack.imgur.com/yWUnt.jpg)
\*\*UPDATE!\*\*\*strong text\*\*\*\*\*
It only seems to work if I have the database like this with the following code..
```
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String UserUserName = String.valueOf(dataSnapshot.child("userUsername").getValue());
username.setText(UserUserName);
}
```
[database with No user id](https://i.stack.imgur.com/7Uk1L.png)
This is how i saved the data to firebase
```
//USER SIGNUP INFORMATION METHOD.
private void push(){
String Email = email.getText().toString().trim();
String Name = name.getText().toString().trim();
String Username = userName.getText().toString().trim();
String id = mDatabase.push().getKey();
users Users = new users(id, Email, Name, Username);
mDatabase.child(id).setValue(Users);
```<issue_comment>username_1: If you are getting the username, you can do this:
```
usernameRef = mDatabase.child(userID);
usernameRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String names=dataSnapshot.child("userUsername").getValue().toString();
username.setText(names);
}
```
the snapshot would be the `userid`, and then you do not need to iterate, can just access it since its a direct child.
Upvotes: 0 <issue_comment>username_2: If I were you, I have used the `uid` as the unique identified and not the pushed key generated by the `push()` method. So for that, change the following lines of code:
```
String id = mDatabase.push().getKey();
users Users = new users(id, Email, Name, Username);
mDatabase.child(id).setValue(Users);
```
with:
```
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
users Users = new users(uid, Email, Name, Username);
mDatabase.child(uid).setValue(Users);
```
To get the data from the databse, please use the following code using the String class:
```
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userEmail = dataSnapshot.child("userEmail").getValue(String.class);
String userID = dataSnapshot.child("userID").getValue(String.class);
String userName = dataSnapshot.child("userName").getValue(String.class);
String userUsername = dataSnapshot.child("userUsername").getValue(String.class);
Log.d("TAG", userEmail + " / " + userID + " / " + userName + " / " + userUsername);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
```
If you want to use the model class, please use the following code:
```
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
users u = dataSnapshot.getValue(users.class);
String userEmail = u.getUserEmail();
String userID = u.getUserID();
String userName = u.getUserName();
String userUsername = u.getUserUsername();
Log.d("TAG", userEmail + " / " + userID + " / " + userName + " / " + userUsername);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
```
In both cases, delete all the data that you and add fresh one.
Upvotes: 2 [selected_answer]
|
2018/03/17
| 969 | 3,451 |
<issue_start>username_0: I'm using the [Alfresco Rest Api](https://api-explorer.alfresco.com/api-explorer/) but I can't find any option that would return the whole tree with all sub-folders.
I want to go down to the last file even if it's 'wrapped' in 3 sub folders.
Any ideas ?<issue_comment>username_1: I don't think you can.
You could execute a PATH query though, since it can be written in a way to return all children, too.
For example:
```
var folder = search.luceneSearch("+PATH:\"/app:company_home/cm:Test_x0020_Folder//*\" AND (TYPE:\"cm:content\" OR TYPE:\"cm:folder\")");
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Create a java baked webscript which will return the node of below object.
```
public class ReportNode {
private NodeRef currentNode;
private List children;
private Map properties = new HashMap<>();
private boolean isFolder;
private String name;
private String type;
private List aspects;
//Getter Setters
}
```
In above structure
**currentNode** represents the current nodered in list
**children** represents the children of a node
Other things are well understood.
Fill up the data in above linked list structure by node crawling.
For displaying the crawled data.You can use the below freemarker template.
```
<#macro recurse_macro nodeRef>
* <@print\_properties reportNode=nodeRef/>
<#macro print_properties reportNode>
* Properties
<#list reportNode.properties?keys as key>
+ ${key} : ${reportNode.properties[key]}
<@recurse_macro nodeRef=nodeRef/>
```
where noderef is root node of the linked list which is created by crawling the nodes.
Upvotes: 1 <issue_comment>username_3: Please refer `categoryService` to list all files in any nested sub folders. Here
`nodeRef` is parent folder's noderef
Using categoryService it is also possible to list all the children of a folder.
```
Collection children = categoryService.getChildren(new NodeRef(nodeRef), CategoryService.Mode.ALL, CategoryService.Depth.ANY);
```
Upvotes: 2 <issue_comment>username_4: To retrieve all documents you can use this service
[http://localhost:8080/share/service/components/documentlibrary/data/doclist/all/site/XXXX/documentLibrary?filter=all&noCache=1521477198549](http://localhost:8080/share/service/components/documentlibrary/data/doclist/all/site/averroes/documentLibrary?filter=all&noCache=1521477198549)
Or you can create your custom webscript and get nodes recursively like that for example:
```
/**
*
* @param type
* @param nodeRef
* @return true if node type equals or inherit from type `type`
*/
protected boolean hasSubType(QName type, NodeRef nodeRef) {
List subTypes = new ArrayList<>();
subTypes.addAll(dictionaryService.getSubTypes(type, true));
QName nodeType = nodeService.getType(nodeRef);
return nodeType.equals(type) || subTypes.contains(nodeType);
}
private void getNodesRecursive(NodeRef node, List documents) {
if (hasSubType(ContentModel.TYPE\_FOLDER, node)) {
List children = nodeService.getChildAssocs(node, ContentModel.ASSOC\_CONTAINS, RegexQNamePattern.MATCH\_ALL);
for (ChildAssociationRef child : children) {
NodeRef childNode = child.getChildRef();
if (hasSubType(ContentModel.TYPE\_CONTENT, node)) {
documents.add(childNode);
} else if (hasSubType(ContentModel.TYPE\_FOLDER, node)) {
// documents.add(childNode);
getNodesRecursive(childNode, documents);
}
}
} else {
documents.add(node);
}
}
```
Upvotes: 0
|
2018/03/17
| 545 | 1,777 |
<issue_start>username_0: So here is my code. I have to replace a space with an asterisk and if there are an occurence of two spaces in a row in the string replace it with one dash
```
php
$string = "Keep your spacing perfect!";
$search = array(' ',' ');
$search2 = array('*','-');
echo str_replace($search, $search2, $string);
?
```
when i run it it prints out
```
Keep*your****spacing***perfect!
```
which is suppose to be
```
Keep*your--spacing-*perfect!
```
so what is wrong with my code and how do i fix it? I did some research but could not come to a solution. Any help is appreciated!<issue_comment>username_1: You have just to swap your replaces. Because you replace single space **before** replacing double spaces.
```
$string = "Keep your spacing perfect!";
$search = array(' ',' '); // swap !
$search2 = array('-','*'); // swap !
echo str_replace($search, $search2, $string);
```
Outputs:
```
Keep*your--spacing-*perfect!
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Try this:
```
php
$string = "Keep your spacing perfect!";
$string1 = preg_replace("/\s\s/", "-", $string);
$string2 = preg_replace("/\s/", '*', $string1);
echo $string2;
?
```
The output of this is the following:
```
Keep*your--spacing-*perfect!
```
Upvotes: 0 <issue_comment>username_3: The answer is this line in the [PHP manual entry for `str_replace`](http://php.net/manual/en/function.str-replace.php):
>
> If `search` or `replace` are arrays, their elements are processed first to last.
>
>
>
So just put the order of the array values in the opposite order:
```
php
$string = "Keep your spacing perfect!";
$search = array(' ',' ');
$search2 = array('-','*');
echo str_replace($search, $search2, $string);
</code
```
Upvotes: 0
|
2018/03/17
| 770 | 3,029 |
<issue_start>username_0: I had made an app using xamarin.android that plays with images. I want other app to share images to my app, I tried the following but throws exception.
Here is Android manifest file
```
xml version="1.0" encoding="utf-8"?
```
Main.axml
```
xml version="1.0" encoding="utf-8"?
```
MainActivity.cs
```
namespace ReceiveDataFromApp
{
[Activity(Label = "ReceiveDataFromApp", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);`
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
ImageView imageView = (ImageView)FindViewById(Resource.Id.imageView);
if (Intent.Data != null)
{
try
{
var uri = Intent.Data;
var iis = ContentResolver.OpenInputStream(uri);
imageView.SetImageBitmap(BitmapFactory.DecodeStream(iis));
}
catch (Exception e)
{
Toast.MakeText(this, e.Message, ToastLength.Long).Show();
}
}
}
}
}
```
Exception:
```
Java.Lang.RuntimeException: Unable to instantiate activity ComponentInfo{ReceiveDataFromApp.ReceiveDataFromApp/ReceiveDataFromApp.ReceiveDataFromApp.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "ReceiveDataFromApp.ReceiveDataFromApp.MainActivity" on path: DexPathList[[zip file "/data/app/ReceiveDataFromApp.ReceiveDataFromApp-1/base.apk"],nativeLibraryDirectories=[/data/app/ReceiveDataFromApp.ReceiveDataFromApp-1/lib/arm, /data/app/ReceiveDataFromApp.ReceiveDataFromApp-1/base.apk!/lib/armeabi-v7a, /vendor/lib, /system/lib]]
```
Do correct what I am doing wrong.<issue_comment>username_1: The Android operating system uses content providers to facilitate access to shared data such as images, media files, contacts and so on. You can find how to use it [here](https://learn.microsoft.com/en-us/xamarin/android/platform/content-providers/).
Upvotes: 0 <issue_comment>username_2: >
> ClassNotFoundException: Didn't find class "ReceiveDataFromApp.ReceiveDataFromApp.MainActivity"
>
>
>
By default, Xamarin creates MD5-based Java class names to avoid name clashing in the generated Java wrappers.
To hard-code a Java class name, use the `Name` parameter in the `ActivityAttribute`
```
[Activity(Name = "ReceiveDataFromApp.ReceiveDataFromApp.MainActivty", Label = "ReceiveDataFromApp", MainLauncher = true)]
public class MainActivity : Activity
~~~~
```
Upvotes: 2 <issue_comment>username_3: Here's the solution of the issue, thanks to @sushihangover
```
[Activity(Name = "ReceiveDataFromApp.ReceiveDataFromApp.MainActivty", Label = "ReceiveDataFromApp", MainLauncher = true)]
public class MainActivity : Activity
~~~~
```
In manifest file you have to add:
```
```
Upvotes: 3 [selected_answer]
|
2018/03/17
| 578 | 2,371 |
<issue_start>username_0: I'm having trouble submitting my app.
I've already done the Volley settings as below, but the Play Store shows up for rejection.
HostnameVerifier
Your app (s) are using an unsafe implementation of the HostnameVerifier interface. You can find more information about how to solve the issue in this Google Help Center article.
```
RequestQueue queue = Volley.newRequestQueue(Services.this, new HurlStack(null, newSslSocketFactory()));
// Request a string response from the provided URL.
try {
final ProgressDialog pDialog = new ProgressDialog(Services.this);
pDialog.setMessage("Wainting ...");
pDialog.show();
String url = "https://sitesecurity.com";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener(){
@Override
public void onResponse(String response) {
}
private SSLSocketFactory newSslSocketFactory() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HttpsTrustManager());
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new DadosConsultaPerto.NullX509TrustManager()}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
SSLSocketFactory sf = context.getSocketFactory();
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
```
I tried several methods but the error persists.
Vulnerability APK Version(s) Past Due Date
HostnameVerifier
Your app(s) are using an unsafe implementation of the HostnameVerifier interface. You can find more information about how resolve the issue in this Google Help Center article.
5 March 01, 2017<issue_comment>username_1: Delete `newSslSocketFactory()` and stop referring to it in your `HurlStack` constructor call. That is where you are using `HostnameVerifier` in a way that is completely insecure.
My guess is that your `HttpsTrustManager` is [this one](https://stackoverflow.com/a/27603256/115145), which is also completely insecure and will cause your app to be banned from the Play Store. Deleting `newSslSocketFactory()` will solve that problem as well.
Upvotes: 1 <issue_comment>username_2: First select apk version and in Alerts (pre-launch report), select security and trust and in details you will find affected class.
Upvotes: 0
|
2018/03/17
| 395 | 1,395 |
<issue_start>username_0: I want to know the difference between date +%F and date '+%F' in UNIX. I am getting same result for both. When i am using the later one in my shell program i am not getting the expected output while the first one gives me the expected output.
Eg:
```
DATE=$(date '+%F')
echo $DATE
2018-03-18
DATE=$(date +%F)
echo $DATE
2018-03-18
```
the problem is when i am using it inside a for loop
```
#!/bin/bash
PICTURES=$(ls /root/Desktop/images | grep jpeg)
DATE=$(date '+%F')
for PICTURE in $PICTURES
do
echo "Renaming ${PICTURE} as ${DATE}-${PICTURE}"
done
```
Error:
line 7: Unexpected EOF while looking for matching `"'
line 10: syntax error: unexpected end of file<issue_comment>username_1: Delete `newSslSocketFactory()` and stop referring to it in your `HurlStack` constructor call. That is where you are using `HostnameVerifier` in a way that is completely insecure.
My guess is that your `HttpsTrustManager` is [this one](https://stackoverflow.com/a/27603256/115145), which is also completely insecure and will cause your app to be banned from the Play Store. Deleting `newSslSocketFactory()` will solve that problem as well.
Upvotes: 1 <issue_comment>username_2: First select apk version and in Alerts (pre-launch report), select security and trust and in details you will find affected class.
Upvotes: 0
|
2018/03/17
| 939 | 3,399 |
<issue_start>username_0: I use webpack 3 for my build process.
webpack.config.js:
```js
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
use: [
{
loader: "css-loader",
options: {
minimize: true,
modules: true,
importLoaders: 1
}
},
{
loader: "postcss-loader",
options: {
path: './postcss.config.js'
}
},
{
loader: "sass-loader",
options: {
includePaths: [dirAssets]
}
}
],
fallback: "style-loader",
publicPath: './'
})
},
```
I require my main.scss in main.js and in dev and build env my selectors looks like this:
```
._1RIaajDV8RXjVfAFhmcSaz {}
```
It should looks like:
```
.h1 {}
```
Any Idea? I can't solve this problem.<issue_comment>username_1: It's hard to know exactly as there are other factors that will play into this but I would suspect it's your minimizing tool.
Using "minimize : true" means that you want the css-loader to squash your css files down to as small of text as it can get. However, per the documentation sometimes this can be destructive to the css:
>
> minimize
>
>
> By default the css-loader minimizes the css if specified by the module system.
>
>
> In some cases the minification is destructive to the css, so you can provide your own options to the cssnano-based minifier if needed. See cssnano's documentation for more information on the available options.
>
>
> You can also disable or enforce minification with the minimize query parameter.
>
>
>
<https://github.com/webpack-contrib/css-loader>
Try turning off minification and/or introducing the cssnano as specified in the documentation.
Upvotes: 0 <issue_comment>username_2: Weird string
============
>
> Webpack format css selectors in weird string
>
>
>
The `weird` string is actually a unique generated ident (hash:base64) for local scoped css.
If you don't need to use [css-modules](https://github.com/css-modules/css-modules) in your project, just remove or set `modules: false` to solve your problem.
[Modules](https://github.com/css-modules/css-modules)
-----------------------------------------------------
>
> The query parameter modules enables the CSS Modules spec.
> This enables local scoped CSS by default.
>
>
>
The loader replaces local selectors with unique identifiers.
```
:local(.className) { background: red; }
:local .className { color: green; }
```
The choosen unique identifiers are exported by the module.
```
._23_aKvs-b8bW2Vg3fwHozO { background: red; }
._23_aKvs-b8bW2Vg3fwHozO { color: green; }
```
Local ident name
----------------
>
> You can configure the generated ident with the localIdentName query parameter (default [hash:base64])
>
>
>
```
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]--[hash:base64:5]'
}
}
```
### Main.scss
```
.h1 {}
```
### Exported css
```
.h1--_1RIaajDV8RXjVfAFhmcSaz {}
```
Upvotes: 3 [selected_answer]
|
2018/03/17
| 903 | 3,052 |
<issue_start>username_0: The order in which the letters are printed is "ABDC" Why does it print the last letter C? I provided my thinking steps and guide in the comments in the code.
```
public class Base {
public static void main(String[] args) {
Base b = new Derived();
b.methodOne();
}
public void methodOne() { //Step 1
System.out.print("A"); //Print "A" first
methodTwo(); //Sends me to Derived class's methodTwo()
}
public void methodTwo() { //Step 3
System.out.print("B"); //Print "B" second
}
}
public class Derived extends Base{
public void methodOne() {
super.methodOne();
System.out.print("C");
}
public void methodTwo(){ //Step 2
super.methodTwo(); //Sends me to Base class's methodTwo()
System.out.println("D"); //Step 3 Print "D"
}
```
}<issue_comment>username_1: It's hard to know exactly as there are other factors that will play into this but I would suspect it's your minimizing tool.
Using "minimize : true" means that you want the css-loader to squash your css files down to as small of text as it can get. However, per the documentation sometimes this can be destructive to the css:
>
> minimize
>
>
> By default the css-loader minimizes the css if specified by the module system.
>
>
> In some cases the minification is destructive to the css, so you can provide your own options to the cssnano-based minifier if needed. See cssnano's documentation for more information on the available options.
>
>
> You can also disable or enforce minification with the minimize query parameter.
>
>
>
<https://github.com/webpack-contrib/css-loader>
Try turning off minification and/or introducing the cssnano as specified in the documentation.
Upvotes: 0 <issue_comment>username_2: Weird string
============
>
> Webpack format css selectors in weird string
>
>
>
The `weird` string is actually a unique generated ident (hash:base64) for local scoped css.
If you don't need to use [css-modules](https://github.com/css-modules/css-modules) in your project, just remove or set `modules: false` to solve your problem.
[Modules](https://github.com/css-modules/css-modules)
-----------------------------------------------------
>
> The query parameter modules enables the CSS Modules spec.
> This enables local scoped CSS by default.
>
>
>
The loader replaces local selectors with unique identifiers.
```
:local(.className) { background: red; }
:local .className { color: green; }
```
The choosen unique identifiers are exported by the module.
```
._23_aKvs-b8bW2Vg3fwHozO { background: red; }
._23_aKvs-b8bW2Vg3fwHozO { color: green; }
```
Local ident name
----------------
>
> You can configure the generated ident with the localIdentName query parameter (default [hash:base64])
>
>
>
```
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]--[hash:base64:5]'
}
}
```
### Main.scss
```
.h1 {}
```
### Exported css
```
.h1--_1RIaajDV8RXjVfAFhmcSaz {}
```
Upvotes: 3 [selected_answer]
|
2018/03/17
| 1,523 | 4,845 |
<issue_start>username_0: I have a view that populates a form in our Extranet. We only want to see the latest data for each group of Matter Numbers.
In the image below we don't want to see any event dates to the right of where it's RED because they are old events. We do want to keep the data that is to the left.
The rows I have highlighted in the tables are the rows that should appear in the Extranet form.
[](https://i.stack.imgur.com/OPBdw.jpg)
Each line is a different Matter Number.
This is the view that was created to pull the data.
I can't figure out how to only show the latest events.
Any help will be greatly appreciated.
```
SELECT e.eventsno AS DocketID,
M1.mattercode,
M1.clientid,
M1.matterid,
M1.AreaofLaw,
DocketCode,
e.eventdate AS StartDate,
e.enddate,
et.eventdesc,
Cast(e.notes AS VARCHAR(4096)) AS Summary
FROM dbo.events AS e
INNER JOIN dbo.eventmatters AS em
ON em.events = e.events
INNER JOIN dbo.matters AS m
ON m.matters = em.matters
INNER JOIN dbo.eventtypes AS et
ON et.eventtypes = e.eventtypes
RIGHT OUTER JOIN dbo.vu_lp2_matters AS M1
ON M1.mattercode = m.matterid
WHERE e.eventkind = 'D'
AND e.eventtypes IN (SELECT eventtypes
FROM dbo.events
WHERE ( et.eventdesc <> 'Accounts Receivable'
OR et.eventdesc NOT LIKE 'Reminder%' )
)
AND ( e.eventdate >= CONVERT(DATETIME, '2014-01-01 00:00:00', 102))
```<issue_comment>username_1: You could use `ROW_NUMBER/RANK` to get first value for each group:
```
WITH cte AS (
SELECT
ROW_NUMBER() OVER(PARTITION BY M1.mattercode ORDER BY e.eventdate DESC) AS rn
-- your complex query
)
SELECT *
FROM cte
WHERE rn = 1;
```
Upvotes: 0 <issue_comment>username_2: Use ROW\_NUMBER function to your query , order the partition by event date descending and filter records having row\_number =1 :
```
SELECT * from (
SELECT e.eventsno AS DocketID,
M1.mattercode,
M1.clientid,
M1.matterid,
M1.AreaofLaw,
DocketCode,
e.eventdate AS StartDate,
e.enddate,
et.eventdesc,
Cast(e.notes AS VARCHAR(4096)) AS Summary ,
ROW_NUMBER () OVER (PARTITION BY M1.mattercode order by e.eventdate desc) as row_no
FROM dbo.events AS e
INNER JOIN dbo.eventmatters AS em
ON em.events = e.events
INNER JOIN dbo.matters AS m
ON m.matters = em.matters
INNER JOIN dbo.eventtypes AS et
ON et.eventtypes = e.eventtypes
RIGHT OUTER JOIN dbo.vu_lp2_matters AS M1
ON M1.mattercode = m.matterid
WHERE e.eventkind = 'D'
AND e.eventtypes IN (SELECT eventtypes
FROM dbo.events
WHERE ( et.eventdesc <> 'Accounts Receivable'
OR et.eventdesc NOT LIKE 'Reminder%' )
)
AND ( e.eventdate >= CONVERT(DATETIME, '2014-01-01 00:00:00', 102))
) TMP where row_no=1
```
Upvotes: 0 <issue_comment>username_3: Thank you for your help. I ended up using a CTE to get the data to display properly. Below is the completed script.
```
With cte As
(Select e.EventsNo,
m1.MatterCode,
m1.ClientID,
m1.MatterID,
m1.AreaOfLaw,
e.EventTypes AS DocketCode,
e.EventDate,
e.EndDate,
et.DocketDesc ,
Cast(e.notes AS VARCHAR(4096)) Summary ,
Row_Number() Over(Partition By MatterCode Order By EventDate Desc) AS rnLastOverAll,
Row_Number() Over(Partition By MatterCode, DocketDesc Order By EventDate Desc) As rnLastByDocDesc
FROM dbo.events e
INNER JOIN dbo.eventmatters em ON em.events = e.events
INNER JOIN dbo.matters m ON m.matters = em.matters
INNER JOIN dbo.vu_LP2_DocketCodes et ON et.DocketCode = e.eventtypes
RIGHT OUTER JOIN dbo.vu_lp2_matters M1 ON M1.mattercode = m.matterid
WHERE e.eventkind = 'D'
)
Select c2.EventsNo 'DocketID',c2.MatterCode,c2.ClientID,c2.MatterID, c2.AreaOfLaw,
c2.DocketCode, c2.EventDate 'StartDate', c2.EndDate, c2.DocketDesc, c2.Summary
From cte c1
Inner Join cte c2 On c1.MatterCode = c2.MatterCode And c2.rnLastByDocDesc = 1
And (
(c1.DocketDesc = 'Demand' And c2.DocketDesc In ('Demand'))
Or (c1.DocketDesc = 'Complaint' And c2.DocketDesc In ('Demand', 'Complaint'))
Or (c1.DocketDesc = 'Pre-Trial' And c2.DocketDesc In ('Demand', 'Complaint', 'Pre-Trial'))
Or (c1.DocketDesc = 'Post Judgment' And c2.DocketDesc In ('Demand', 'Complaint', 'Pre-Trial', 'Post Judgment'))
Or (c1.DocketDesc = 'Stop Collections' And c2.DocketDesc In ('Demand', 'Complaint', 'Pre-Trial', 'Post Judgment', 'Stop Collections'))
) Where c1.rnLastOverAll = 1
```
Upvotes: 1
|
2018/03/17
| 1,713 | 4,655 |
<issue_start>username_0: I'm trying to recurse over a dataset to find the highest level item, i.e. one that does not have a parent.
The structure looks like this:
```
ββββββββββββββ¦βββββββββββββ
β Item β Material β
β βββββββββββββ¬βββββββββββββ£
β 2094-00003 β MHY00007 β
β 2105-0001 β 2105-0002 β
β 2105-0002 β 2105-1000 β
β 2105-1000 β 2105-1003 β
β 2105-1003 β 7547-122 β
β 7932-00001 β 7932-00015 β
β 7932-00002 β 7932-00015 β
β 7932-00010 β MHY00007 β
β 7932-00015 β 7932-05000 β
β 7932-05000 β MHY00007 β
ββββββββββββββ©βββββββββββββ
```
So, for example, if I select 7547-122, the function will return 2105-0001. So the function has recursively followed the tree upwards, 7547-122 -> 2105-1003 -> 2105-1000 -> β¦ -> 2105-0001.
When I run my code, I can only get it to return one top level, as you can see from the MHY00007 case, some times there are multiple top levels. How can I return a list of all the top levels any given material has?
My code:
```
import pandas as pd
class BillOfMaterials:
def __init__(self, bom_excel_path):
self.df = pd.read_excel(bom_excel_path)
self.df = self.df[['Item', 'Material']]
def find_parents(self, part_number):
material_parent_search = self.df[self.df.Material == part_number]
parents = list(set(material_parent_search['Item']))
return parents
def find_top_levels(self, parents):
top_levels = self.__ancestor_finder_([parents])
print(f'{parents} top level is {top_levels}')
return {parents: top_levels}
def __ancestor_finder_(self, list_of_items):
for ancestor in list_of_items:
print(f'Searching for ancestors of {ancestor}')
ancestors = self.find_parents(ancestor)
print(f'{ancestor} has ancestor(s) {ancestors}')
if not ancestors:
return ancestor
else:
highest_level = self.__ancestor_finder_(ancestors)
return highest_level
BOM = BillOfMaterials(bom_excel_path="Path/To/Excel/File/BOM.xlsx")
ItemsToSearch = ['7547-122', 'MHY00007']
top_levels = []
for item in ItemsToSearch:
top_levels.append(BOM.find_top_levels(item))
```<issue_comment>username_1: Yes, you can do this recursively, for example:
```
import pandas as pd
class BillOfMaterials:
def __init__(self, bom_excel_path):
self.df = pd.read_excel(bom_excel_path)
self.df = self.df[['Item', 'Material']]
def find_parents(self, part_number):
return list(set(self.df[self.df.Material == part_number]['Item']))
def find_top_levels(self, item):
parents = self.find_parents(item)
if not parents:
# there are no parent items => this item is a leaf
return [item]
else:
# there are parent items => recursively find grandparents
grandparents = []
for parent in parents:
grandparents = grandparents + self.find_top_levels(parent)
return grandparents
if __name__ == '__main__':
BOM = BillOfMaterials(bom_excel_path="testdata.xlsx")
ItemsToSearch = ['7547-122', 'MHY00007']
for i in ItemsToSearch:
print('')
print('The top levels of ' + i + ' are: ')
print(BOM.find_top_levels(i))
```
Note the recursive call of `self.find_top_levels(parent)`.
This will give the output
```
The top levels of 7547-122 are:
['2105-0001']
The top levels of MHY00007 are:
['2094-00003', '7932-00001', '7932-00002', '7932-00010']
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Recursion over a `pandas` dataframe will be slower than using a `dict`.
For performance, I recommend you create a dictionary and create a simple function to iteratively cycle up your tree structure. Below is an example.
```
import pandas as pd
df = pd.DataFrame({'Item': ['2094-00003', '2105-0001', '2105-0002', '2105-1000',
'2105-1003', '7932-00001', '7932-00002', '7932-00010',
'7932-00015', '7932-05000'],
'Material': ['MHY00007', '2105-0002', '2105-1000', '2105-1003',
'7547-122', '7932-00015', '7932-00015', 'MHY00007',
'7932-05000', 'MHY00007']})
parent_child = df.set_index('Item')['Material'].to_dict()
child_parent = {v: k for k, v in parent_child.items()}
def get_all_parents(x):
while x in child_parent:
x = child_parent[x]
yield x
def get_grand_parent(x):
for last in get_all_parents(x):
pass
return last
get_grand_parent('7547-122')
# '2105-0001'
```
Upvotes: 1
|
2018/03/17
| 359 | 1,288 |
<issue_start>username_0: I have nodes which don't have the 'name' property, in that case in the browser, it doesn't show a default property to be shown. Most of the nodes look blank, which isn't good for visualization. How to display that better in such cases?<issue_comment>username_1: When you perform a query in the browser, the viz is inside a panel.
In the top bar of this panel, you will see the facet for labels and relationships.
If you click on one of those elements, the bottom bar will change, and will allow you to change the field to display, the color and size.
Upvotes: 0 <issue_comment>username_2: Here are the two images to explain what to do.
Say for whatever reason the user node does not display anything.
[](https://i.stack.imgur.com/61NLY.jpg)
To display something, first click on the top user as shown below.
[](https://i.stack.imgur.com/G1lyl.jpg)
Now in the bottom pan you see the properties of the user label. Now click what ever property that you what to be displayed. I want name so I click name below.
[](https://i.stack.imgur.com/6J4qN.jpg)
Upvotes: 2
|
2018/03/17
| 438 | 1,494 |
<issue_start>username_0: I want to add a blurred shadow for my edit text but I don't know how?
I had made the shape but I don't know the attribute for adding blur to the edit text.
I made a drawable resource file and make this as a background to my edit text but it doesn't look as the picture
and this my code.
```
xml version="1.0" encoding="utf-8"?
```
[](https://i.stack.imgur.com/w6ZKK.png)<issue_comment>username_1: When you perform a query in the browser, the viz is inside a panel.
In the top bar of this panel, you will see the facet for labels and relationships.
If you click on one of those elements, the bottom bar will change, and will allow you to change the field to display, the color and size.
Upvotes: 0 <issue_comment>username_2: Here are the two images to explain what to do.
Say for whatever reason the user node does not display anything.
[](https://i.stack.imgur.com/61NLY.jpg)
To display something, first click on the top user as shown below.
[](https://i.stack.imgur.com/G1lyl.jpg)
Now in the bottom pan you see the properties of the user label. Now click what ever property that you what to be displayed. I want name so I click name below.
[](https://i.stack.imgur.com/6J4qN.jpg)
Upvotes: 2
|
2018/03/17
| 478 | 1,218 |
<issue_start>username_0: I would like to replace NAs in numeric columns using some variation of `mutate_if` and `replace_na` if possible, but can't figure out the syntax.
```
df <-tibble(
first = c("a", NA, "b"),
second = c(NA, 2, NA),
third = c(10, NA, NA)
)
#> # A tibble: 3 x 3
#> first second third
#>
#> 1 a NA 10.0
#> 2 2.00 NA
#> 3 b NA NA
```
Final result should be:
```
#> # A tibble: 3 x 3
#> first second third
#>
#> 1 a 0 10.0
#> 2 2.00 0
#> 3 b 0 0
```
My attempts look like:
```
df %>% mutate_if(is.numeric , replace_na(., 0) )
#>Error: is_list(replace) is not TRUE
```<issue_comment>username_1: ```
df %>% mutate_if(is.numeric , replace_na, replace = 0)
# A tibble: 3 x 3
# first second third
#
#1 a 0 10.0
#2 NA 2.00 0
#3 b 0 0
```
Upvotes: 6 [selected_answer]<issue_comment>username_2: The in another answer mentioned solution based on `mutate_if` is based on a **suspended function** in `dplyr`. The suggested alternative is to use the `across()` function. Here a solution using that one:
```
df %>%
mutate(
across(where(is.numeric), ~replace_na(.x, 0))
)
# A tibble: 3 Γ 3
first second third
1 a 0 10
2 NA 2 0
3 b 0 0
```
Upvotes: 3
|
2018/03/17
| 377 | 1,506 |
<issue_start>username_0: I'm working on android application which works as expected , but I'm using FirebaseUI to authenticate users login , I'm using this code for authentication and registration :
```
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build(),
new AuthUI.IdpConfig.FacebookBuilder().build()))
.build(),
RC_SIGN_IN);
```
Is there any way to know if the current user is new user after login using `onActivityResult()`<issue_comment>username_1: ```
df %>% mutate_if(is.numeric , replace_na, replace = 0)
# A tibble: 3 x 3
# first second third
#
#1 a 0 10.0
#2 NA 2.00 0
#3 b 0 0
```
Upvotes: 6 [selected_answer]<issue_comment>username_2: The in another answer mentioned solution based on `mutate_if` is based on a **suspended function** in `dplyr`. The suggested alternative is to use the `across()` function. Here a solution using that one:
```
df %>%
mutate(
across(where(is.numeric), ~replace_na(.x, 0))
)
# A tibble: 3 Γ 3
first second third
1 a 0 10
2 NA 2 0
3 b 0 0
```
Upvotes: 3
|
2018/03/17
| 1,223 | 3,768 |
<issue_start>username_0: I am using just Ruby (no rails) to make a gem that takes a yaml file as an input an it produces a pdf.
I am using pdfKit and Haml. In the haml file I need to render an image. When using pure HTML, PDFKit shows the image, but when using Haml::Engine and the haml file the image doesn't get rendered.
I have put the image, the .module and the haml file under one folder to make sure the issue is not the path.
In my gemspec I have the following
.
.
```
gem.add_development_dependency("pdfkit", "0.8.2")
gem.add_development_dependency("wkhtmltopdf-binary")
gem.add_development_dependency("haml")
```
The HTML that works:
```
junk
HI

Bye
```
Haml version that doesn't work:
```
%html
%head
%title
junk
%body
HI
= img "watermark.png"
Bye
```
module:
```
require "pdfkit"
require "yaml"
require "haml"
require "pry"
.
.
junk = Haml::Engine.new(File.read("lib/abc/models/junk.haml")).render
kit2 = PDFKit.new(junk)
kit2.to_file("pdf/junk.pdf")
```
when using the html file, pdf renders the image, however, when I use the haml this is now my pdf looks like
[](https://i.stack.imgur.com/2zf8O.png)
and If I use
```
%img(src="watermark.png")
```
I get the following error when pdf is generated
`Exit with code 1 due to network error: ContentNotFoundError`
The PDF still gets generated, but the still looks like the image above.
So I am trying to see without using any rails, and img\_tag, image\_tag etc.. how would I just use the %img in haml file to render the proper image
Following is the output of junk, when I create `@img = "watermark.png"`
[1](https://i.stack.imgur.com/2zf8O.png) pry(DD)> junk
```
=> "\n\n\njunk\n\n\n\nHI\n\nBye\n\n\n"
```
Replace the img tag `%img(src=@img)` still same result<issue_comment>username_1: I think this is not HAML issue, but `wkhtmltopdf` thing. Apparently it's not very good at handling relative urls to images. It should work with absolute path, for example:
```
%img(src="/home/user/junk/watermark.png")
```
Upvotes: 2 <issue_comment>username_2: To create an image tag in HAML you will need to use
```
%img(src="foo.png")
# or
%img{src: "foo.png"}
```
If you use
```
= img "watermark.png"
```
then you are calling the `img` method (if it exists), passing it `"watermark.png"` as argument and outputting the return value of that method in the generated HTML.
Honestly i'm not sure how that HTML template should work, when the HAML template that generates the same HTML does not. So I guess you run that script from different directories or so?
Anyways: Problem is, that you will need absolute paths for your files. Otherwise wkhtmltopdf will not be able to resolve your images.
You can use `File.expand_path` (see sample) for this, or write a custom helper.
I tried following:
Created two files:
```
/tmp/script.rb
/tmp/watermark.png
/tmp/template.haml
```
Where *watermark.png* is a screenshot I took from this question, *script.rb* is:
```
require "pdfkit"
require "haml"
template = File.read("template.haml")
html = Haml::Engine.new(template).render
File.write("template.html", html)
pdf = PDFKit.new(html)
pdf.to_file("output.pdf")
```
And *template.haml* is:
```
%html
%head
%title Something
%body
BEFORE
%img(src="#{File.expand_path(__dir__, "watermark.png")}")
AFTER
```
When I run this script like:
```
ruby-2.5.0 tmp$ ruby script.rb
```
Then the HTML that is generated is:
```
Something
BEFORE

AFTER
```
And the generated PDF looks like:
[](https://i.stack.imgur.com/lhXOj.jpg)
Upvotes: 1
|