date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/19 | 2,636 | 10,343 | <issue_start>username_0: I'm trying to install react-native-navigation(wix) package, I'm following the steps on android(<https://wix.github.io/react-native-navigation/#/installation-android>) but in android studio the build fails with the message. Gradle 4.1( I don't know if this is related)
```
Could not resolve project :react-native-navigation.
Required by:
project :app
Unable to find a matching configuration of project :react-native-navigation: None of the consumable configurations have attributes.
Error:Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve project :react-native-navigation.
Open File
Show Details
Error:Unable to resolve dependency for ':app@debugAndroidTest/compileClasspath': Could not resolve project :react-native-navigation.
Open File
Show Details
Error:Unable to resolve dependency for ':app@debugUnitTest/compileClasspath': Could not resolve project :react-native-navigation.
Open File
Show Details
Error:Unable to resolve dependency for ':app@release/compileClasspath': Could not resolve project :react-native-navigation.
Open File
Show Details
Error:Unable to resolve dependency for ':app@releaseUnitTest/compileClasspath': Could not resolve project :react-native-navigation.
```
I leave the details below(my user is called home, is not a typo):
Issue Description
local.properties file
```
sdk.dir=/home/home/Android/Sdk
```
settings.gradle
```
include ':app'
include ':react-native-navigation'
project(':react-native-navigation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-navigation/android/app/')
App gradle file
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
defaultConfig {
applicationId "com.example.home.myapplication"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "com.android.support:appcompat-v7:25.0.1"
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
//tried implementation as well here instead of compile but didn't work either
compile project(':react-native-navigation')
}
```
### Environment
* React Native Navigation version: "1.1.370"
* React Native version: "0.52.0"
* Platform(s) (iOS, Android, or both?): Android
* Device info (Simulator/Device? OS version? Debug/Release?): Android Studio
Which version of gradle and android api should I use with react native? Is there any way to solve this? I see that my app gradle file is nothing alike the instructions, that compile project statement is not valid in my version of gradle. Any idea? Maybe the local.settings is wrong and is not finding the files?...Any help would be appreciated<issue_comment>username_1: The problem was that the last gradle version wasn't compatible with the package as I suspected. I had to use gradle 3 in the end and everything worked
Upvotes: 0 <issue_comment>username_2: Environment
```
React Native Navigation version: "2.0.2502"
React Native version: "0.56.0"
Platform(s) (iOS, Android, or both?): Android
Device info (Simulator/Device? OS version? Debug/Release?): Android Studio
```
I followed the [official documentation](https://wix.github.io/react-native-navigation/v2/#/), then had the same issue. In my situation I moved the 'RNN' folder within my react-native project's `node_modules`, then Gradle worked.
Upvotes: 0 <issue_comment>username_3: ```
We also get the same problem on my android app, Here is the solution.
Follow the steps to overcome this error.
Step 1:
Requirements
node >= 8
react-native >= 0.51
Step 2:
npm install --save react-native-navigation
Step 3:
Add the following in android/settings.gradle:
include ':react-native-navigation'
project(':react-native-navigation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-navigation/lib/android/app/')
Step 4:
Make sure you're using the new gradle plugin, edit android/gradle/wrapper/gradle-wrapper.properties
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
-distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
Step 5:
Update android/build.gradle:
buildscript {
repositories {
+ google()
+ mavenLocal()
+ mavenCentral()
+ jcenter()
- maven {
- url 'https://maven.google.com/'
- name 'Google'
- }
}
dependencies {
+ classpath 'com.android.tools.build:gradle:3.0.1'
- classpath 'com.android.tools.build:gradle:2.2.3'
}
}
allprojects {
repositories {
+ google()
+ mavenCentral()
mavenLocal()
jcenter()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
- maven {
- url 'https://maven.google.com/'
- name 'Google'
- }
+ maven { url 'https://jitpack.io' }
}
}
ext {
- buildToolsVersion = "26.0.3"
+ buildToolsVersion = "27.0.3"
- minSdkVersion = 16
+ minSdkVersion = 19
compileSdkVersion = 26
targetSdkVersion = 26
supportLibVersion = "26.1.0"
}
Step 6:
Update project dependencies in android/app/build.gradle.
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
applicationId "com.yourproject"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
ndk {
abiFilters "armeabi-v7a", "x86"
}
}
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_1_8
+ targetCompatibility JavaVersion.VERSION_1_8
+ }
...
}
dependencies {
- compile fileTree(dir: "libs", include: ["*.jar"])
- compile "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
- compile "com.facebook.react:react-native:+" // From node_modules
+ implementation fileTree(dir: "libs", include: ["*.jar"])
+ implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
+ implementation "com.facebook.react:react-native:+" // From node_modules
+ implementation project(':react-native-navigation')
}
Step 7:
Update MainActivity.java
MainActivity.java should extend com.reactnativenavigation.NavigationActivity instead of ReactActivity.
This file is located in android/app/src/main/java/com//MainActivity.java.
-import com.facebook.react.ReactActivity;
+import com.reactnativenavigation.NavigationActivity;
-public class MainActivity extends ReactActivity {
+public class MainActivity extends NavigationActivity {
- @Override
- protected String getMainComponentName() {
- return "yourproject";
- }
}
Step 7:
Update MainApplication.java
This file is located in android/app/src/main/java/com//MainApplication.java.
...
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
+import com.reactnativenavigation.NavigationApplication;
+import com.reactnativenavigation.react.NavigationReactNativeHost;
+import com.reactnativenavigation.react.ReactGateway;
import java.util.Arrays;
import java.util.List;
-public class MainApplication extends Application implements ReactApplication {
+public class MainApplication extends NavigationApplication {
+
+ @Override
+ protected ReactGateway createReactGateway() {
+ ReactNativeHost host = new NavigationReactNativeHost(this, isDebug(), createAdditionalReactPackages()) {
+ @Override
+ protected String getJSMainModuleName() {
+ return "index";
+ }
+ };
+ return new ReactGateway(this, isDebug(), host);
+ }
+
+ @Override
+ public boolean isDebug() {
+ return BuildConfig.DEBUG;
+ }
+
+ protected List getPackages() {
+ // Add additional packages you require here
+ // No need to add RnnPackage and MainReactPackage
+ return Arrays.asList(
+ // eg. new VectorIconsPackage()
+ );
+ }
+
+ @Override
+ public List createAdditionalReactPackages() {
+ return getPackages();
+ }
- ...
+}
Step 8:
RNN and React Native version
react-native-navigation supports multiple React Native versions. Target the React Native version required by your project by specifying the RNN build flavor in android/app/build.gradle.
android {
...
defaultConfig {
applicationId "com.yourproject"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
+ missingDimensionStrategy "RNN.reactNativeVersion", "reactNative57" // See note below!
versionCode 1
versionName "1.0"
...
}
...
}
```
For the more details, you can follow this link
[enter link description here](https://wix.github.io/react-native-navigation/#/docs/Installing?id=android)
Upvotes: 2 [selected_answer]<issue_comment>username_4: Do you have the Android SDK 27 installed? Open your Android SDK Manager in Android Studio and make sure you install that version there. Also try creating an emulator that is based on that version.
Upvotes: 0 |
2018/03/19 | 579 | 2,181 | <issue_start>username_0: I want to programmatically `up` a `docker-compose.yml` file in `--detach` mode then wait and block the application until all images of the compose file get up as `Containers` so that I can run my integration tests.
Notice that `docker-compose images`, and `docker-compose inspect` are useless since they are unable to detect anything until the containers run.
**More details:**
I want to implement it as an abstract library which works with any docker-compose.yml file, and I want the library to be used by F# on dotnet core. There are some solutions around that need to be used on linux, but I don't want to limit the developers to use a special OS or tool other than the F#, dotnet core, docker, and docker-compose CLI<issue_comment>username_1: You can use something like [wait-for-it](https://github.com/vishnubob/wait-for-it/blob/master/README.md) to wait until some port is listen to execute a command.
For instance:
```
wait-for-it.sh : --
```
Upvotes: 0 <issue_comment>username_1: From this [docker-compose PR](https://github.com/docker/compose/pull/5643) (version >= 1.20.0) (which is have been already merged) `docker-compose ps` shows whether each service is healthy or not. So, defining a **healthcheck** on each [service](https://docs.docker.com/compose/compose-file/#healthcheck) or [image](https://docs.docker.com/engine/reference/builder/#healthcheck) and executing `docker-compose ps` will tell if your services are available.
The column State of `docker-compose ps` is:
* For starting: **Up (health: starting)**
* For no health check: **Up**
* For healthy: **Up (healthy)**
* For unhealthy: **Up (unhealthy)**
For instance for an `postresql` service, a healtcheck might be:
```
...
postgres:
image: postgres:9.6
healthcheck:
test: ["CMD", "lsof", "-i:5432"]
interval: 1m30s
timeout: 10s
retries: 3
...
```
You will need `lsof` available on your image. You can also use `nc`, `telnet`, `netstat` or a more specific tool for the service, like `pgsql`.
Upvotes: 1 |
2018/03/19 | 326 | 1,138 | <issue_start>username_0: i enter a command for add docker's official GPG key but i don't have OK in output.
The command is :
```
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
```<issue_comment>username_1: I realize this is an old question, but hope this helps someone.
I had the same issue with Ubuntu 18.04.
In my case the error was:
```
gpg: no valid OpenPGP data found
```
What solved the issue for me was running the command below to gain root access:
```
sudo su -
```
With root privileges, I once again ran:
```
root@hostname:~# curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
```
Root access is not necessary to complete the rest of the Docker installation steps.
To leave the root shell either type `exit`, or press CTRL + D.
Upvotes: 2 <issue_comment>username_2: I got the same issue as well, but the output showed me that I have to use *root* user instead of *superuser*:
`E: This command can only be used by root.`
And once I logged in with *root* user, I can successfully use the original command with the response on my window:
`OK`
Upvotes: 0 |
2018/03/19 | 498 | 1,873 | <issue_start>username_0: I have a string displayed in a page and I want to store this string in a variable so I can use this variable for a check further in the test process.
Here is what it looks like:
```
let storedValue: string;
element(by.id('myElement')).getText().then((elementValue: string) => {
storedValue = elementValue;
console.log('stored value: ' + storedValue);
});
// Some unrelated code will go here in the future
browser.wait(() => storedValue !== null, 5000, 'browser.wait timeout');
expect(element(by.id('myElement')).getText()).toEqual(storedValue);
```
If the string in the page is *hello*, the test fails with the log `Expected 'Hello' to equal undefined.`
Why is it still undefined ?
I thought that Protractor would queue the last two instructions synchronously in the ControlFlow.
Maybe there is another way to store this variable, or to wait for the `storedValue` to be defined ?<issue_comment>username_1: I realize this is an old question, but hope this helps someone.
I had the same issue with Ubuntu 18.04.
In my case the error was:
```
gpg: no valid OpenPGP data found
```
What solved the issue for me was running the command below to gain root access:
```
sudo su -
```
With root privileges, I once again ran:
```
root@hostname:~# curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
```
Root access is not necessary to complete the rest of the Docker installation steps.
To leave the root shell either type `exit`, or press CTRL + D.
Upvotes: 2 <issue_comment>username_2: I got the same issue as well, but the output showed me that I have to use *root* user instead of *superuser*:
`E: This command can only be used by root.`
And once I logged in with *root* user, I can successfully use the original command with the response on my window:
`OK`
Upvotes: 0 |
2018/03/19 | 2,593 | 7,658 | <issue_start>username_0: I need to generate result for time slots between dates and for time
```
select scheduleId,startDate,endDate,startTime,endTime,weekdayMask,
(CASE WHEN [weekdayMask] | 0x01 = [weekdayMask] THEN 1 ELSE 0 END) AS MONDAY,
(CASE WHEN [weekdayMask] | 0x02 = [weekdayMask] THEN 1 ELSE 0 END) AS TUESDAY,
(CASE WHEN [weekdayMask] | 0x04 = [weekdayMask] THEN 1 ELSE 0 END) AS WEDNESDAY,
(CASE WHEN [weekdayMask] | 0x08 = [weekdayMask] THEN 1 ELSE 0 END) AS THURSDAY,
(CASE WHEN [weekdayMask] | 0x10 = [weekdayMask] THEN 1 ELSE 0 END) AS FRIDAY,
(CASE WHEN [weekdayMask] | 0x20 = [weekdayMask] THEN 1 ELSE 0 END) AS SATURDAY,
(CASE WHEN [weekdayMask] | 0x40 = [weekdayMask] THEN 1 ELSE 0 END) AS SUNDAY
from otp.tutor_schedule
```
RESULT from the above query
```
scheduleId startDate endDate startTime endTime weekdayMask MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY SUNDAY
----------- ---------- ---------- ---------------- ---------------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
11 2017-01-01 2017-09-30 10:00:00.0000000 14:00:00.0000000 21 1 0 1 0 1 0 0
```
Now I need to generate the one hour time slots for the weekdays between the StartDate and endDate fields.
SQL fiddle link <http://sqlfiddle.com/#!18/49f1b/1>
Can any one please help me out<issue_comment>username_1: Perhaps a recursive CTE will get you started down the right path?
```
;WITH cte AS(
SELECT CAST('2018-01-01' AS DATETIME) AS StartDate
UNION ALL
SELECT DATEADD(HH, 1, StartDate)
FROM cte
WHERE StartDate < '2018-09-30'
)
SELECT *
FROM cte
OPTION (MAXRECURSION 7000)
```
Upvotes: 2 <issue_comment>username_2: You can use the following. Put your original query on the first `CTE` (I hard-coded some values to test).
Basically I use a recursive `CTE` to generate all hours between each start date and end date. Then filter the results depending on each weekday, for each schedule. The first statement is used to set the `DATEPART WEEKDAY` to a known value to compare later.
```
SET DATEFIRST 1 -- 1: Monday, 7: Sunday
;WITH YourQueryResults AS
(
SELECT
scheduleId = 1,
startDate = CONVERT(DATE, '2017-01-01'),
endDate = CONVERT(DATE, '2017-09-30'),
startTime = CONVERT(TIME, '10:00:00.0000000'),
endTime = CONVERT(TIME, '14:00:00.0000000'),
MONDAY = 1,
TUESDAY = 0,
WEDNESDAY = 1,
THURSDAY = 0,
FRIDAY = 1,
SATURDAY = 0,
SUNDAY = 0
UNION ALL
SELECT
scheduleId = 2,
startDate = CONVERT(DATE, '2017-01-01'),
endDate = CONVERT(DATE, '2017-09-30'),
startTime = CONVERT(TIME, '17:00:00.0000000'),
endTime = CONVERT(TIME, '20:00:00.0000000'),
MONDAY = 1,
TUESDAY = 0,
WEDNESDAY = 0,
THURSDAY = 1,
FRIDAY = 0,
SATURDAY = 0,
SUNDAY = 0
),
RecursiveDatetimesByHour AS
(
SELECT
scheduleId = Y.scheduleId,
DatetimeByHour = CONVERT(DATETIME, Y.startDate) + CONVERT(DATETIME, Y.startTime),
WeekDay = DATEPART(WEEKDAY, CONVERT(DATETIME, Y.startDate) + CONVERT(DATETIME, Y.startTime))
FROM
YourQueryResults AS Y
UNION ALL
SELECT
scheduleId = R.scheduleId,
DatetimeByHour = DATEADD(HOUR, 1, R.DatetimeByHour),
WeekDay = DATEPART(WEEKDAY, DATEADD(HOUR, 1, R.DatetimeByHour))
FROM
RecursiveDatetimesByHour AS R
WHERE
DATEADD(HOUR, 1, R.DatetimeByHour) <
(SELECT CONVERT(DATETIME, Y.endDate) + CONVERT(DATETIME, Y.endTime) FROM YourQueryResults AS Y
WHERE Y.scheduleId = R.scheduleId)
)
SELECT
R.scheduleId,
R.DatetimeByHour,
R.WeekDay
FROM
RecursiveDatetimesByHour AS R
INNER JOIN YourQueryResults AS Y ON R.scheduleId = Y.scheduleId
WHERE
CONVERT(TIME, R.DatetimeByHour) BETWEEN Y.startTime AND Y.endTime AND
(
(Y.MONDAY = 1 AND R.WeekDay = 1) OR
(Y.TUESDAY = 1 AND R.WeekDay = 2) OR
(Y.WEDNESDAY = 1 AND R.WeekDay = 3) OR
(Y.THURSDAY = 1 AND R.WeekDay = 4) OR
(Y.FRIDAY = 1 AND R.WeekDay = 5) OR
(Y.SATURDAY = 1 AND R.WeekDay = 6) OR
(Y.SUNDAY = 1 AND R.WeekDay = 7)
)
OPTION
(MAXRECURSION 32000)
```
Some things can be improved (avoid doing so many casts for example), but it can give you a good idea of how to solve your problem.
Upvotes: 2 [selected_answer]<issue_comment>username_3: Please check following CTE query
I used a calendar table as you can see in first CTE expression, [dbo.DateTable](http://www.kodyaz.com/articles/sql-server-dates-table-using-tsql-cte-calendar-table.aspx)
For time, I mean hours I used basic method; reading from spt\_values
But you can also create a time table as well
I hope it helps
```
;with dt as (
select
convert(date, [date]) as [date],
DATEPART(dw, [date]) as wd,
case when DATEPART(dw, [date]) = 1 then 1 end as SUNDAY,
case when DATEPART(dw, [date]) = 2 then 1 end as MONDAY,
case when DATEPART(dw, [date]) = 3 then 1 end as TUESDAY,
case when DATEPART(dw, [date]) = 4 then 1 end as WEDNESDAY,
case when DATEPART(dw, [date]) = 5 then 1 end as THURSDAY,
case when DATEPART(dw, [date]) = 6 then 1 end as FRIDAY,
case when DATEPART(dw, [date]) = 7 then 1 end as SATURDAY
from [dbo].[DateTable]('2017-01-01', '2017-12-31') as dt
), tt as (
select convert(time, dateadd(hh,number-1,'00:00:00')) as [time]
from master..spt_values
where Type = 'P' and number between 1 and 25
), schedule as (
select
scheduleId,startDate,endDate,startTime,endTime,weekdayMask,
(CASE WHEN [weekdayMask] | 0x01 = [weekdayMask] THEN 1 ELSE 0 END) AS MONDAY,
(CASE WHEN [weekdayMask] | 0x02 = [weekdayMask] THEN 1 ELSE 0 END) AS TUESDAY,
(CASE WHEN [weekdayMask] | 0x04 = [weekdayMask] THEN 1 ELSE 0 END) AS WEDNESDAY,
(CASE WHEN [weekdayMask] | 0x08 = [weekdayMask] THEN 1 ELSE 0 END) AS THURSDAY,
(CASE WHEN [weekdayMask] | 0x10 = [weekdayMask] THEN 1 ELSE 0 END) AS FRIDAY,
(CASE WHEN [weekdayMask] | 0x20 = [weekdayMask] THEN 1 ELSE 0 END) AS SATURDAY,
(CASE WHEN [weekdayMask] | 0x40 = [weekdayMask] THEN 1 ELSE 0 END) AS SUNDAY
from tutor_schedule
), cte as (
select
dt.[date],
scheduleId,startDate,endDate,startTime,endTime,
ROW_NUMBER() over (partition by scheduleId, [date] order by [time]) as rn,
tt.[time]
from dt
left join schedule as s
on dt.[date] between s.startDate and s.endDate
left join tt
on tt.[time] >= s.startTime and tt.[time] < s.endTime
where
dt.MONDAY = s.MONDAY or
dt.TUESDAY = s.TUESDAY or
dt.WEDNESDAY = s.WEDNESDAY or
dt.THURSDAY = s.THURSDAY or
dt.FRIDAY = s.FRIDAY or
dt.SATURDAY = s.SATURDAY or
dt.SUNDAY = s.SUNDAY
)
select
scheduleId,
[date],
dateadd(hh, rn-1,startTime) as starttime,
dateadd(hh, rn,startTime) as endtime
from cte
where starttime <= [time]
```
I have tested with following sample data
```
create table tutor_schedule (
scheduleId int identity(1,1),
startDate date,
endDate date,
startTime time,
endTime time,
weekdayMask int
)
insert into tutor_schedule select '2017-01-01','2017-09-30','10:00:00','14:00:00',21
insert into tutor_schedule select '2017-01-05','2017-01-12','13:00:00','15:00:00',12
```
Upvotes: 1 |
2018/03/19 | 1,112 | 4,098 | <issue_start>username_0: I cant seem to locate an answer to this anywhere through searches...
I am trying to iterate through a list on a webpage using vba and then use the data in excel.
Accessing the webpage is fine, locating the correct div is fine but I cannot find how to iterate through the list.
What I am trying is:
```
Sub getdata()
Dim ie As InternetExplorer
Dim html As HTMLDocument
Set ie = New InternetExplorer
ie.Visible = False
ie.navigate "http://www.springfieldeducationalfurniture.co.uk/products/60-Chair-Trolley/11116/"
Do While ie.READYSTATE <> READYSTATE_COMPLETE
Application.StatusBar = "Attempting connection ..."
DoEvents Loop
Set html = ie.document
Set ie = Nothing
Application.StatusBar = ""
Dim content Set content = html.getElementsByClassName("tabs__content")
For Each bullet In content
'tried this
IHtml = bullet.innerHTML'this gives the whole div not sure how to convert to a string
'and this but get "Run-time error '438': Object doesn't support this property or method"
IHtml = bullet.getElementsByTagName("li")
Next
End Sub
```
They HTML I am after is as follows, I am wanting to iterate through the in the and assign the content i.e. "Requires simple self assembly" to a cell in excel (once I read the data from the list, the rest is easy):
```
* [Description](#)
* [Delivery](#)
[Information](#)
60 Chair Trolley
* Requires simple self assembly
* Non marking wheels
* Heavy duty lockable castors
* Black frame
* Vertical / hanging chair storage
* Does not fit through a single doorway
* Fits through double doors when fully loaded
* Dimensions: W780 x L1770 x H1340mm
Code: Y16527
[Delivery](#)
Please [contact us](/contact) for delivery information.
```<issue_comment>username_1: And this targets the class you mentioned. Requires reference to HTML Object library and Microsoft XML (your version)
```
Option Explicit
Sub Getinfo2()
Dim http As New XMLHTTP60
Dim html As New HTMLDocument
With http
.Open "GET", "http://www.springfieldeducationalfurniture.co.uk/products/60-Chair-Trolley/11116/", False
.send
html.body.innerHTML = .responseText
End With
Dim posts As MSHTML.IHTMLElementCollection
Dim post As MSHTML.IHTMLElement
Set posts = html.getElementsByClassName("tabs__content")(0).getElementsByTagName("li")
For Each post In posts
Debug.Print post.innerHTML
Next post
End Sub
```
Output:
[](https://i.stack.imgur.com/UdSmc.png)
This gets the html for all the li elements
```
Option Explicit
Sub Getinfo2()
Dim http As New XMLHTTP60
Dim html As New HTMLDocument
With http
.Open "GET", "http://www.springfieldeducationalfurniture.co.uk/products/60-Chair-Trolley/11116/", False
.send
html.body.innerHTML = .responseText
End With
Dim posts As MSHTML.IHTMLElementCollection
Dim post As MSHTML.IHTMLElement
Set posts = html.getElementsByTagName("li")
For Each post In posts
Debug.Print post.innerHTML
Next post
End Sub
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is an alternative option that doesn't require any reference's to library's (Late binding). It also show a different way of looping through the class, as well as the LI's.
```
Sub getData()
Dim ie As Object
Dim li As Object
Dim tabsClass As Object
'Late Binding
Set ie = CreateObject("InternetExplorer.Application")
On Error GoTo Catch
ie.Visible = False
ie.navigate "http://www.springfieldeducationalfurniture.co.uk/products/60-Chair-Trolley/11116/"
While ie.ReadyState <> 4 Or ie.Busy: DoEvents: Wend
'LOOP EACH CLASS ELEMENT
For Each tabsClass In ie.Document.getElementsByClassName("tabs__content")
'LOOP EACH LI WITHIN THAT CLASS
For Each li In tabsClass.getElementsByTagName("li")
Debug.Print li.innertext
Next li
Next tabsClass
'CLOSE INSTANCE OF IE
Catch:
ie.Quit
Set ie = Nothing
End Sub
```
Upvotes: 1 |
2018/03/19 | 785 | 3,055 | <issue_start>username_0: `Xamarin.Forms.Device.StartTimer` is a convenient method to repeatedly call some code in a certain interval. This is similar to JavaScript's `SetInverval()` method. JavaScript also has a method to set a single delay, called `SetTimeout()` - it delays a certain amount of time, then calls the callback code once. Is there a `SetTimeout` equivalent for Xamarin.Forms, where I simply want the code to be called in the background after a certain delay?
NOTE: I know I can `return false` to stop the recurrence, and that's easy enough. It just seems like if you're only intending to call the callback once, it's a little semantically misleading to use this recurring timer mechanism.<issue_comment>username_1: And this targets the class you mentioned. Requires reference to HTML Object library and Microsoft XML (your version)
```
Option Explicit
Sub Getinfo2()
Dim http As New XMLHTTP60
Dim html As New HTMLDocument
With http
.Open "GET", "http://www.springfieldeducationalfurniture.co.uk/products/60-Chair-Trolley/11116/", False
.send
html.body.innerHTML = .responseText
End With
Dim posts As MSHTML.IHTMLElementCollection
Dim post As MSHTML.IHTMLElement
Set posts = html.getElementsByClassName("tabs__content")(0).getElementsByTagName("li")
For Each post In posts
Debug.Print post.innerHTML
Next post
End Sub
```
Output:
[](https://i.stack.imgur.com/UdSmc.png)
This gets the html for all the li elements
```
Option Explicit
Sub Getinfo2()
Dim http As New XMLHTTP60
Dim html As New HTMLDocument
With http
.Open "GET", "http://www.springfieldeducationalfurniture.co.uk/products/60-Chair-Trolley/11116/", False
.send
html.body.innerHTML = .responseText
End With
Dim posts As MSHTML.IHTMLElementCollection
Dim post As MSHTML.IHTMLElement
Set posts = html.getElementsByTagName("li")
For Each post In posts
Debug.Print post.innerHTML
Next post
End Sub
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is an alternative option that doesn't require any reference's to library's (Late binding). It also show a different way of looping through the class, as well as the LI's.
```
Sub getData()
Dim ie As Object
Dim li As Object
Dim tabsClass As Object
'Late Binding
Set ie = CreateObject("InternetExplorer.Application")
On Error GoTo Catch
ie.Visible = False
ie.navigate "http://www.springfieldeducationalfurniture.co.uk/products/60-Chair-Trolley/11116/"
While ie.ReadyState <> 4 Or ie.Busy: DoEvents: Wend
'LOOP EACH CLASS ELEMENT
For Each tabsClass In ie.Document.getElementsByClassName("tabs__content")
'LOOP EACH LI WITHIN THAT CLASS
For Each li In tabsClass.getElementsByTagName("li")
Debug.Print li.innertext
Next li
Next tabsClass
'CLOSE INSTANCE OF IE
Catch:
ie.Quit
Set ie = Nothing
End Sub
```
Upvotes: 1 |
2018/03/19 | 1,032 | 3,830 | <issue_start>username_0: I have a simple web application in Angular v5. This is a purely client-side application in the meaning of it doesn't use any server-side (this is a basic calculator application that load data from JSON file with some measurements and display to the user some analysis according to that JSON).
During development I've tested the application using the Angular-cli "serve", by running - `ng serve` command, and it works great.
Now I wont to bundle my app and start using it. I would like to run this app locally on my machine without any server.
According to the [Angular documentation](https://angular.io/guide/deployment), to bundle the application to deployment, I should run the command: `ng build --prod --base-href=./`. There to flag `--prod` will deploy a *minified* and *uglified* version of the application. And the `--base-href=./` will set in the **index.html** to allow me loading the application files (all the ABC.bundles.js file) directly from the local machine.
Now, when I'm opening the `dist/index.html` file I can see that all the scripts have loaded, however, I have an error in the console:
>
> ERROR Error: Uncaught (in promise): SecurityError: Failed to execute
> 'replaceState' on 'History': A history state object with URL
> 'file:///C:/.../dist/' cannot be created in a document with origin
> 'null' and URL 'file:///C:/.../dist/index.html'.
>
>
>
How do I deploy/bundle my application to run locally, without a server?<issue_comment>username_1: Try using `HashLocationStrategy`
<https://angular.io/api/common/HashLocationStrategy>
<https://angular.io/guide/router#hashlocationstrategy>
In your module
```
imports [
RouterModule.forRoot(routes, {useHash: true})
]
```
Upvotes: 1 <issue_comment>username_2: When using **angular-router** you need a server-side since the router is used to serve pages.
To solve these issue you have 2 choices:
1. Use some sort of light-weight server like NPM's [http-server](https://www.npmjs.com/package/http-server) which allow you to run a server on a local machine from the command-line.
2. Drop the **angular-router** completely - Yes this is a bit extreme solution and I'm sure it will not be a valid solution to anybody with more than 2 pages in his application. But if you have a very very simple app with one page only and you don't need routing capabilities then this is a valid solution.
Upvotes: 3 [selected_answer]<issue_comment>username_3: In your routes configuration add;
`RouterModule.forRoot(routes, {useHash: true});`
In your index.html do this;
`document.write('<base href="' + document.location + '" />');`
And then build with --base-href ./ e.g
`ng build --prod --base-href ./`
source <https://github.com/angular/angular/issues/13948>
Upvotes: 1 <issue_comment>username_4: i have also faced same issue and it was not working after deployment into server, i have added `HashLocationStrategy`.
<https://angular.io/api/common/HashLocationStrategy>
<https://angular.io/guide/router#hashlocationstrategy>
for me page was not loading and throwing 404 page not found after requesting from Google.com
url --- <http://techeducation.in>
i have solved this after commenting or removing ...
from index.html file of `dist` folder.
Upvotes: 1 <issue_comment>username_5: Since Angular 13 despricated deployUrl. Cause trouble if you using CDN cache but your app running on different domain like heroku or something else.
here is the solution step by step:
1. delete deployUrl, no need to change it to baseHref, we keep it default
2. replace url to load it manually by replace-file.js:
```
const replace = require('replace-in-file');
const prefix = 'https://your-cdn.com/assets';
const action2options = {
files: path.join(process.cwd(), '/dist/browser/index.html'),
from: [/
```
Upvotes: 0 |
2018/03/19 | 2,285 | 6,036 | <issue_start>username_0: I am trying to create a 13 period calendar in mssql but I am a bit stuck. I am not sure if my approach is the best way to achieve this. I have my base script which can be seen below:
```
Set DateFirst 1
Declare @Date1 date = '20180101' --startdate should always be start of
financial year
Declare @Date2 date = '20181231' --enddate should always be start of
financial year
SELECT * INTO #CalendarTable
FROM dbo.CalendarTable(@Date1,@Date2,0,0,0)c
DECLARE @StartDate datetime,@EndDate datetime
SELECT @StartDate=MIN(CASE WHEN [Day]='Monday' THEN [Date] ELSE NULL END),
@EndDate=MAX([Date])
FROM #CalendarTable
;With Period_CTE(PeriodNo,Start,[End])
AS
(SELECT 1,@StartDate,DATEADD(wk,4,@StartDate) -1
UNION ALL
SELECT PeriodNo+1,DATEADD(wk,4,Start),DATEADD(wk,4,[End])
FROM Period_CTE
WHERE DATEADD(wk,4,[End])< =@EndDate
OR PeriodNo+1 <=13
)
select * from Period_CTE
```
Which gives me this:
`PeriodNo Start End
1 2018-01-01 00:00:00.000 2018-01-28 00:00:00.000
2 2018-01-29 00:00:00.000 2018-02-25 00:00:00.000
3 2018-02-26 00:00:00.000 2018-03-25 00:00:00.000
4 2018-03-26 00:00:00.000 2018-04-22 00:00:00.000
5 2018-04-23 00:00:00.000 2018-05-20 00:00:00.000
6 2018-05-21 00:00:00.000 2018-06-17 00:00:00.000
7 2018-06-18 00:00:00.000 2018-07-15 00:00:00.000
8 2018-07-16 00:00:00.000 2018-08-12 00:00:00.000
9 2018-08-13 00:00:00.000 2018-09-09 00:00:00.000
10 2018-09-10 00:00:00.000 2018-10-07 00:00:00.000
11 2018-10-08 00:00:00.000 2018-11-04 00:00:00.000
12 2018-11-05 00:00:00.000 2018-12-02 00:00:00.000
13 2018-12-03 00:00:00.000 2018-12-30 00:00:00.000`
The result i am trying to get is
[](https://i.stack.imgur.com/GYpUq.png)
Even if I have to take a different approach I would not mind, as long as the result is the same as the above.
dbo.CalendarTable() is a function that returns the following results. I can share the code if desired.
[](https://i.stack.imgur.com/DGfGJ.png)<issue_comment>username_1: I'd create a general number's table [like suggested here](https://stackoverflow.com/a/32474751/5089204) and add a column `Periode13`.
The trick to get the *tiling* is the integer division:
```
DECLARE @PeriodeSize INT=28; --13 "moon-months" a 28 days
SELECT TOP 100 (ROW_NUMBER() OVER(ORDER BY (SELECT NULL))-1)/@PeriodeSize
FROM master..spt_values --just a table with many rows to show the principles
```
You can add this to an existing numbers table with a simple update statement.
UPDATE A fully working example (using the logic linked above)
-------------------------------------------------------------
```
DECLARE @RunningNumbers TABLE (Number INT NOT NULL
,CalendarDate DATE NOT NULL
,CalendarYear INT NOT NULL
,CalendarMonth INT NOT NULL
,CalendarDay INT NOT NULL
,CalendarWeek INT NOT NULL
,CalendarYearDay INT NOT NULL
,CalendarWeekDay INT NOT NULL);
DECLARE @CountEntries INT = 100000;
DECLARE @StartNumber INT = 0;
WITH E1(N) AS(SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N)), --10 ^ 1
E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b), -- 10 ^ 2 = 100 rows
E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b), -- 10 ^ 4 = 10,000 rows
E8(N) AS(SELECT 1 FROM E4 a CROSS JOIN E4 b), -- 10 ^ 8 = 10,000,000 rows
CteTally AS
(
SELECT TOP(ISNULL(@CountEntries,1000000)) ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) -1 + ISNULL(@StartNumber,0) As Nmbr
FROM E8
)
INSERT INTO @RunningNumbers
SELECT CteTally.Nmbr,CalendarDate.d,CalendarExt.*
FROM CteTally
CROSS APPLY
(
SELECT DATEADD(DAY,CteTally.Nmbr,{ts'2018-01-01 00:00:00'})
) AS CalendarDate(d)
CROSS APPLY
(
SELECT YEAR(CalendarDate.d) AS CalendarYear
,MONTH(CalendarDate.d) AS CalendarMonth
,DAY(CalendarDate.d) AS CalendarDay
,DATEPART(WEEK,CalendarDate.d) AS CalendarWeek
,DATEPART(DAYOFYEAR,CalendarDate.d) AS CalendarYearDay
,DATEPART(WEEKDAY,CalendarDate.d) AS CalendarWeekDay
) AS CalendarExt;
```
--The mockup table from above is now filled and can be queried
```
WITH AddPeriode AS
(
SELECT Number/28 +1 AS PeriodNumber
,CalendarDate
,CalendarWeek
,r.CalendarDay
,r.CalendarMonth
,r.CalendarWeekDay
,r.CalendarYear
,r.CalendarYearDay
FROM @RunningNumbers AS r
)
SELECT TOP 100 p.*
,(SELECT MIN(CalendarDate) FROM AddPeriode AS x WHERE x.PeriodNumber=p.PeriodNumber) AS [Start]
,(SELECT MAX(CalendarDate) FROM AddPeriode AS x WHERE x.PeriodNumber=p.PeriodNumber) AS [End]
,(SELECT MIN(CalendarDate) FROM AddPeriode AS x WHERE x.PeriodNumber=p.PeriodNumber AND x.CalendarWeek=p.CalendarWeek) AS [wkStart]
,(SELECT MAX(CalendarDate) FROM AddPeriode AS x WHERE x.PeriodNumber=p.PeriodNumber AND x.CalendarWeek=p.CalendarWeek) AS [wkEnd]
,(ROW_NUMBER() OVER(PARTITION BY PeriodNumber ORDER BY CalendarDate)-1)/7+1 AS WeekOfPeriode
FROM AddPeriode AS p
ORDER BY CalendarDate
```
Try it out...
Hint: Do not use a `VIEW` or `iTVF` for this.
---------------------------------------------
This is non-changing data and much better placed in a physically stored table with appropriate indexes.
Upvotes: 1 <issue_comment>username_2: Not abundantly sure external links are accepted here, but I wrote an article that pulls of a 5-4-4 'Crop Year' fiscal year with all the code. Feel free to use all the code in these articles.
[SQL Server Calendar Table](https://www.experts-exchange.com/articles/12267/SQL-Server-Calendar-Table.html)
[SQL Server Calendar Table: Fiscal Years](https://www.experts-exchange.com/articles/12265/SQL-Server-Calendar-Table-Fiscal-Years.html)
Upvotes: 0 |
2018/03/19 | 1,553 | 5,198 | <issue_start>username_0: I am reindexing my index data from ES 5.0(parent-child) to ES 6.2(Join type)
Data in index ES 5.0 is stored as parent-child documents in separate types and for reindex i have created new index/mapping based on 6.2 in my new cluster.
The parent documents flawlessly reindex to new index but the child documents throwing error as below
```
{
"index": "index_two",
"type": "_doc",
"id": "AVpisCkMuwDYFnQZiFXl",
"cause": {
"type": "mapper_parsing_exception",
"reason": "failed to parse",
"caused_by": {
"type": "illegal_argument_exception",
"reason": "[routing] is missing for join field [field_relationship]"
}
},
"status": 400
}
```
scripts i am using to reindex the data
```
{
"source": {
"remote": {
"host": "http://myescluster.com:9200",
"socket_timeout": "1m",
"connect_timeout": "20s"
},
"index": "index_two",
"type": ["actions"],
"size": 5000,
"query":{
"bool":{
"must":[
{"term": {"client_id.raw": "cl14ous0ydao"}}
]
}
}
},
"dest": {
"index": "index_two",
"type": "_doc"
},
"script": {
"params": {
"jdata": {
"name": "actions"
}
},
"source": "ctx._routing=ctx._routing;ctx.remove('_parent');params.jdata.parent=ctx._source.user_id;ctx._source.field_relationship=params.jdata"
}
}
```
I have passed the routing field in painless script as the documents are dynamic from source index.
Mapping of the destination index
```
{
"index_two": {
"mappings": {
"_doc": {
"dynamic_templates": [
{
"template_actions": {
"match_mapping_type": "string",
"mapping": {
"fields": {
"raw": {
"index": true,
"ignore_above": 256,
"type": "keyword"
}
},
"type": "text"
}
}
}
],
"date_detection": false,
"properties": {
"attributes": {
"type": "nested"
}
},
"cl_other_params": {
"type": "nested"
},
"cl_triggered_ts": {
"type": "date"
},
"cl_utm_params": {
"type": "nested"
},
"end_ts": {
"type": "date"
},
"field_relationship": {
"type": "join",
"eager_global_ordinals": true,
"relations": {
"users": [
"actions",
"segments"
]
}
},
"ip_address": {
"type": "ip"
},
"location": {
"type": "geo_point"
},
"processed_ts": {
"type": "date"
},
"processing_time": {
"type": "date"
},
"products": {
"type": "nested",
"properties": {
"traits": {
"type": "nested"
}
}
},
"segment_id": {
"type": "integer"
},
"start_ts": {
"type": "date"
}
}
}
}
}
```
My sample source document
```
{
"_index": "index_two",
"_type": "actions",
"_id": "AVvKUYcceQCc2OyLKWZ9",
"_score": 7.4023576,
"_routing": "cl14ous0ydaob71ab2a1-837c-4904-a755-11e13410fb94",
"_parent": "cl14ous0ydaob71ab2a1-837c-4904-a755-11e13410fb94",
"_source": {
"user_id": "cl14ous0ydaob71ab2a1-837c-4904-a755-11e13410fb94",
"client_id": "cl14ous0ydao",
"session_id": "CL-e0ec3941-6dad-4d2d-bc9b",
"source": "betalist",
"action": "pageview",
"action_type": "pageview",
"device": "Desktop",
"ip_address": "172.16.58.3",
"location": "20.7333 , 77",
"attributes": [
{
"key": "url",
"value": "https://www.google.com/",
"type": "string"
}
],
"products": []
}
}
```<issue_comment>username_1: I had the same issue and searching in elasticsearch discussions I found [this](https://discuss.elastic.co/t/an-routing-missing-exception-is-obtained-when-reindex-sets-the-routing-value/155140/2) that works:
`POST` *\_reindex*
```
{
"source": {
"index": "old_index",
"type": "actions"
},
"dest": {
"index": "index_two"
},
"script": {
"source": """
ctx._type = "_doc";
String routingCode = ctx._source.user_id;
Map join = new HashMap();
join.put('name', 'actions');
join.put('parent', routingCode);
ctx._source.put('field_relationship', join);
ctx._parent = null;
ctx._routing = new StringBuffer(routingCode)"""
}
}
```
Hope this helps :) .
Upvotes: 1 <issue_comment>username_2: I'd like to point out that routing is generally not required for a join field, however if you're creating the child before the parent is created, then you're going to face this problem.
It's advisable to re-index all the parents first then the children.
Upvotes: 0 |
2018/03/19 | 848 | 3,039 | <issue_start>username_0: I am trying to solve a challenge on a coding site. The problem is about int matrixes. I am using c# language.I need to create a function that takes a parameter as `int[][]` (integer matrix) and also return `int[][]` (another integer matrix). Starting of problem (the empty function given to me) is like that
```
int[][] boxBlur(int[][] image) {
}
```
and this is what i tried so far
```
int[][] boxBlur(int[][] image) {
int pixelLength = image[0].Length - 2;
int[][] newBox = new int[pixelLength][pixelLength];
int pixelSum = 0;
int c = 0;
for(int t = 0; t
```
Now i don't have any problem with algorithm, probably it will work but the problem is that i can't define an Array like `int[][]`. It gives an error like `Cannot implicitly convert type int to int[][]` and when i try to create this array like
`int[,] newBox = new int[pixelLength,pixelLength];`
it also gives error because it says the return type is wrong and i can't change the return type so i need to define a matrix exactly like `int[][]`.
Is there any way to do it or do i need to try another way?<issue_comment>username_1: `int[][]` and `int[,]` are two different things. The first is [Jagged Array](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays), the second is [Multidimensional Array](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays).
When initializing jagged array you can give only the array length, not the length of all the arrays in it:
```
int[][] newBox = new int[pixelLength][];
```
And insert new array each time:
```
newBox[index] = new int[size];
```
Upvotes: 2 <issue_comment>username_2: `int[][]` is a *jagged array*, or in other words, an *array of arrays*.
When you see a `int[]`, you understand it as an array of integers. That is, every "slot" of the array holds and integer. An array of arrays is exactly the same, except that every slot holds an array.
Once you understand that, it should make perfect sense why the correct way to initialize your jagged array is:
```
int[][] newBox = new int[pixelLength][];
```
Now you've said that `newBox` is an array of int arrays: `newBox[0]` is of type `int[]`, `newBox[1]` is of type `int[]`, etc. Because the default value of an array, like any other reference type, is `null`, the value of `newBox[0]`, `newBox[1]`, etc. is `null`; you need to initialize each and every one of them.
The advantage of jagged arrays is, of course, that each `int[]` can be the size you wish, hence the name *jagged* array.
So what you are essentially missing, once you initialize your jagged array correctly, is initalizing each and everyone of the `int[]` arrays before using them. You can do this inside the adequate loop.
Carrying on from here should be easy.
An interesting test to verify if you've understood everything correctly is initalizing and correctly filling up all the values of the following type:
```
int[][][] myHeadHurtsArray;
```
Upvotes: 4 [selected_answer] |
2018/03/19 | 1,961 | 7,147 | <issue_start>username_0: This is a follow-up question to this [one](https://stackoverflow.com/a/48850849/3002584):
As explained in the above-linked answer:
>
> When you provide an *expression* for a binding value rather than just a
> reference to an observable, KO effectively wraps that expression in a
> computed when applying the bindings.
>
>
>
Thus, I expected that when providing the `changeCity` as a binding expression (it is a function and not an observable), then changing the value on the `input` box would fire the `changeCity` function.
However, as you can see on the first snippet, it doesn't (Nor when binding it as `changeCity()`), but If `changeCity` is declared as a `ko.computed`, it does fire - see the second snippet.
Does it mean that a bounded function and a bounded computed are not completely the same with regard to dependency tracking?
**First snippet - bounded function:**
```js
var handlerVM = function () {
var self = this;
self.city = ko.observable("London");
self.country = ko.observable("England");
self.changeCity = function () {
if (self.country() == "England") {
self.city("London");
} else {
self.city("NYC");
}
}
}
ko.applyBindings(new handlerVM());
```
```html
###
```
**Second snippet - bounded computed:**
```js
var handlerVM = function () {
var self = this;
self.city = ko.observable("London");
self.country = ko.observable("England");
self.changeCity = ko.computed(function () {
if (self.country() == "England") {
self.city("London");
} else {
self.city("NYC")
}
});
}
ko.applyBindings(new handlerVM());
```
```html
###
```<issue_comment>username_1: >
> the expected behavior in both snippets is that once the text in the input box is changed (and the focus is out), changeCity is fired (Happens on the 2nd, not on the 1st).
>
>
>
Ahhh, now I understand. You are describing what a [*subscription*](http://knockoutjs.com/documentation/observables.html#explicitly-subscribing-to-observables) does.
First off, rid your mind of DOM events. The field does not exist. All there is is your viewmodel. (\*)
With this mind-set it's clear what to do: React to changes in your `country` property, via `.subscribe()`. The following does what you have in mind.
```js
var handlerVM = function () {
var self = this;
self.city = ko.observable("London");
self.country = ko.observable("England");
self.country.subscribe(function (newValue) {
switch (newValue.toLowerCase()) {
case "england":
self.city("London");
break;
case "usa":
self.city("NYC");
break;
default:
self.city("(unknown)");
}
});
}
ko.applyBindings(new handlerVM());
```
```html
###
```
---
(\*) Of course the field still exists. But it helps to imagine the view (your HTML) as 100% dependent on your viewmodel. Knockout does all the viewmodel-view interaction for you. It takes care of displaying changes in the viewmodel data, and it takes care of feeding back user interactions into your viewmodel. All you should pay attention to is changes in your viewmodel.
Whenever you feel that you need to listen to a basic DOM event like "click", chances are that you are doing something wrong, i.e. chances are you are missing an observable, or a [custom binding](http://knockoutjs.com/documentation/custom-bindings.html).
Upvotes: 2 <issue_comment>username_2: I take it that you're not just trying to solve a practical problem, but that you're mostly interested in the "theoretical difference" between passing a `computed` or a plain `function` to a binding. I'll try to explain the differences/similarities.
Let's start with an example
---------------------------
```js
const someObs = ko.observable(10);
const someFn = () => someObs() + 1;
const someComp = ko.computed(someFn);
const dec = () => someObs(someObs() - 1);
ko.applyBindings({ someObs, someFn, someComp, dec });
```
```html
Obs. value:
Computed created in binding:
Computed created in vm:
-1
```
The example above shows that both `someFn` and `someComp` do the same thing. By referencing `someFn()` in a binding handler's value, you've essentially created a computed with a dependency to `someObs`.
Why this doesn't work in your first example
-------------------------------------------
You never referenced your `changeCity` method in any knockout related code, which means there'll never be the chance to create a dependency. Of course, you can force one, but it's kind of weird:
```js
var handlerVM = function () {
var self = this;
self.city = ko.observable("London");
self.country = ko.observable("England");
self.changeCity = function () {
if (self.country() == "England") {
self.city("London");
} else {
self.city("NYC");
}
}
}
ko.applyBindings(new handlerVM());
```
```html
###
```
Why a regular `computed` *does* work
------------------------------------
In your second example, you use a `ko.computed`. Upon instantiating a `ko.computed`, the passed function is evaluated once (immediately) and dependencies to all used observables are created.
If you were to change the `ko.computed` to a `ko.pureComputed`, you'll see your second example will also stop working. A `pureComputed` only evaluates once its return value is actually used and won't create dependencies until then.
The internals
-------------
Knockout [wraps your binding's value in a function](https://github.com/knockout/knockout/blob/master/src/binding/expressionRewriting.js#L130) *as a string*. You can read more about this in [an answer I wrote earlier](https://stackoverflow.com/a/43097922/3297291).
We also know that any `observable` that is called inside a binding-handler's `init` method, creates a dependency that calls the binding's `update` method when a change happens.
So, in the example I gave, this is what happens:
1. The `text` binding is parsed
2. The function `function() { return someFn(); }` is passed as a *value accessor* to the `text` binding's `init` method.
3. The value accessor is called to initialize the text field
4. `someObs` is asked for its value and a dependency is created
5. The correct value is rendered to the DOM
Then, upon pressing the button and changing `someObs`:
6. `someObs` is changed, triggering the `text` binding's `update` method
7. The `update` method calls the `valueAccessor`, re-evaluating `someObs` and correctly updating its text.
Practical advice
----------------
To wrap up, some practical advice:
* Use a `ko.pureComputed` when you create a new value out of one or more `observable` values. *(your example)*
```
self.city = ko.pureComputed(
() => self.country() === "england"
? "london"
: "nyc"
);
```
* Use a `subscribe` if you want to create *side effects* based on an observable value changing. E.g.: a `console.log` of a new value or a reset of a timer.
* Use a `ko.computed` when you want to create *side effects* based on a change in any of several observables.
Upvotes: 3 [selected_answer] |
2018/03/19 | 350 | 1,444 | <issue_start>username_0: I'm taking about preparing by google store different versions of apk with resources adequate for our phone DPI/size. It didn't when I started programming on Android 4 years ago. Has anything changed? I can see that my apk downloaded from Google Play has smaller size than apk uploaded to the store. Is it because of improved compression algorithm or maybe they added removing unnecessary resources? If yes, any official source? I didn't find anything about this.<issue_comment>username_1: I would bet on compression and maybe some common library optimisation.
That said, there **is** a mechanism for shrinking unused resources. It is **integrated into proguard**, but is currently opt-in. You can read more about it [here](https://developer.android.com/studio/build/shrink-code.html).
Upvotes: 0 <issue_comment>username_2: At the moment Google Play does not optimize the app by removing unnecessary resources, though this may happen in future. What you are seeing is almost certainly compression or patching, which you can read about in [this blog post](https://android-developers.googleblog.com/2016/12/saving-data-reducing-the-size-of-app-updates-by-65-percent.html).
If you want to make sure you can take advantage of future optimizations in this space you should opt-in to [Google Play app signing](https://support.google.com/googleplay/android-developer/answer/7384423) for your app.
Upvotes: 2 [selected_answer] |
2018/03/19 | 1,079 | 2,921 | <issue_start>username_0: ```
data = [{"map_name": "PHX7260.AE5020003.9"},
{"map_name": "PHX7260.AE5020003.10"},
{"map_name": "PHX7260.AE5020003.1"}]
```
I want to sort this data in descending order alphabetically and numerically both.
I tried the below but it doesn't work on array of objects.
```
var myArray = data;
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
console.log(myArray.sort(collator.compare));
```
How should I go about it, the data of objects is received and it should be returned as objects only and not as array to display.<issue_comment>username_1: You can use `array#sort` with `string#localeCompare` with `numeric` property set to `true`.
```js
const data = [{"map_name": "PHX7260.AE5020003.9"}, {"map_name": "PHX7260.AE5020003.10"},{"map_name": "PHX7260.AE5020003.1"}];
data.sort((a,b) => b.map_name.localeCompare(a.map_name, undefined, {numeric: true}));
console.log(data);
```
Upvotes: 1 <issue_comment>username_2: * You can get the string and the number before/after the last dot respectively.
* Compare the string first, if they are equal sort by number else use the function `localeCompare`.
*This approach sorts using descending direction.*
Look how `ZHX7260.AE5020003.10` is placed at the first position.
```js
var data = [{"map_name": "PHX7260.AE5020003.9"}, {"map_name": "ZHX7260.AE5020003.10"}, {"map_name": "PHX7260.AE5020003.10"}, {"map_name": "PHX7260.AE5020003.1"}];
data.sort((a, b) => {
var astr = a.map_name.substring(0, a.map_name.lastIndexOf('.'));
var bstr = b.map_name.substring(0, b.map_name.lastIndexOf('.'));
if (astr === bstr) {
var aidx = a.map_name.substring(a.map_name.lastIndexOf('.') + 1);
var bidx = b.map_name.substring(b.map_name.lastIndexOf('.') + 1);
return bidx - aidx;
} else return bstr.localeCompare(astr);
});
console.log(data);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
```html
also since PHX7260.AE5020003 are same hence the output expected is above , if the string aredifferent it should sort the string first and then the number
```
Upvotes: 0 <issue_comment>username_3: Using javascript's native `Array.sort()` method, you can split your strings on `.` and do a multi-step sort like below:
```js
var data = [{"map_name": "PHX7260.AE5020003.9"},
{"map_name": "PHX7260.AE5020003.10"},
{"map_name": "PHX7260.AE5020003.1"}]
function compare(a,b){
if(!!parseInt(a) && !!parseInt(b)){
a = parseInt(a)
b = parseInt(b)
}
if(a > b) return 1
else if(a < b) return -1
else return 0
}
function sortData(a,b){
let a_arr = a.map_name.split('.'),
b_arr = b.map_name.split('.')
while(a_arr.length){
let val = compare(a_arr.shift(), b_arr.shift())
if(val) return val
}
return 0
}
console.log(data.sort(sortData))
```
Upvotes: 0 |
2018/03/19 | 994 | 3,569 | <issue_start>username_0: When I am checking the naming rules for my code. If i got variable or function name have more letters than allowed ERROR. I count the total character by manually or have to copy paste into Notpad++. Is there is any options to find the number of selected characters in eclipse.<issue_comment>username_1: Eclipse does not provide a way to display the length of a text selection like NotePad++.
[Bug 73904: Show length of selection in status box](https://bugs.eclipse.org/bugs/show_bug.cgi?id=73094) was raised in 2004 (!!!) to add this feature but it still hasn't been implemented.
The good news is that [someone has written a plugin named **getStringLength**](https://github.com/aleroot/getStringLength) to do exactly what you want, as mentioned in a comment in the Eclipse Bug Report:
>
> Eclipse plugin that add the selected text counter on the right side of
> the column and row position in the Eclipse status bar. After you
> double click the text, this plug-in will show the length of text you
> selected in the eclipse status bar; in the case you select more than
> one row it will show the number of rows selected, like Notepad++ do.
>
>
>
The bad news is that I couldn't get it to work properly. After adding the plugin to Eclipse's **dropins** folder the status bar is updated as described, but the details are misaligned and not rendering correctly:
[](https://i.stack.imgur.com/OZW37.png)
Through careful testing I can see that the plugin actually is updating the length of the selected text, but the entry on the status bar is practically illegible. Still, in the absence of anything else, it is worth trying - perhaps you will have better luck in your environment. Let us know if it works for you.
Upvotes: 2 <issue_comment>username_2: You don't need a plugin anymore with [Eclipse 2019-09](https://www.eclipse.org/eclipse/news/4.13/platform.php#editor-status-line):
>
> Editor status line shows more selection details
> -----------------------------------------------
>
>
> The status line for Text Editors now shows the cursor position, and when the editor has something selected, shows the number of characters in the selection as well.
>
>
>
[](https://i.stack.imgur.com/IBXZ4.png)
>
> This also works in the block selection mode.
>
>
>
[](https://i.stack.imgur.com/asUlF.png)
>
> These two new additions to the status line can be disabled via the `General > Editors > Text Editors` preference page.
>
>
>
Upvotes: 0 <issue_comment>username_3: i has fixed error rendering in eclipse version=4.12.0 on windows 10, with steps.
1. clone project ([getStringLength project](https://github.com/aleroot/getStringLength.git))
2. import to
* edit file com.lyf.plugin.getStringLength.SelectedTextInfoControlContribution.java (line 26).
`@Override
protected Control createControl(Composite parent) {
parent.getParent().setRedraw(true);
......
}`
* build plugin:
```
1. Right-click your plugin project in Package Explorer window.
2. Press Export... in shown context menu.
3. Select Plug-In Development -> Deployable plug-ins and fragments (or Deployable plug-ins and fragments directly in old Eclipses).
4. Close Eclipse. Copy this JAR to eclipse/plugins/ path. Run Eclipse again.
```
Good luck!
Upvotes: 0 |
2018/03/19 | 1,904 | 5,061 | <issue_start>username_0: I keep on getting this error message:
>
> A required class was missing while executing org.eclipse.jetty:jetty-maven-plugin:9.2.3.v20140905:run: javax/ws/rs/client/RxInvokerProvider
>
>
>
I have tried to remove the maven repo so that it is forced to download the library again, but with no result. If I manually add this dependency it complains on another thing and so on which makes me think it is something else that causes this.
Anyone have any clue? here is my pom.xml as well
```
xml version="1.0" encoding="UTF-8"?
se.hrmsoftware.hrm
sleepy-oyster-projects
1.2-SNAPSHOT
4.0.0
war
sleepy-common-ws
org.glassfish.jersey
jersey-bom
${jersey.version}
pom
import
org.glassfish.jersey.containers
jersey-container-servlet-core
2.17
org.glassfish.jersey.media
jersey-media-json-jackson
2.17
se.hrmsoftware.hrm
sleepy-commons
${project.version}
org.apache.maven.plugins
maven-war-plugin
src/main/webapp/WEB-INF/web.xml
org.apache.maven.plugins
maven-compiler-plugin
2.5.1
true
1.8
1.8
2.26
UTF-8
```
Also this project have been working but now it won't start it anymore.
Here is the maven dependency tree:
```
se.hrmsoftware.hrm:sleepy-common-ws:war:1.2-SNAPSHOT
[INFO] +- org.glassfish.jersey.containers:jersey-container-servlet-core:jar:2.17:compile
[INFO] | +- org.glassfish.hk2.external:javax.inject:jar:2.4.0-b10:compile
[INFO] | +- org.glassfish.jersey.core:jersey-common:jar:2.26:compile
[INFO] | | +- javax.annotation:javax.annotation-api:jar:1.2:compile
[INFO] | | \- org.glassfish.hk2:osgi-resource-locator:jar:1.0.1:compile
[INFO] | +- org.glassfish.jersey.core:jersey-server:jar:2.26:compile
[INFO] | | +- org.glassfish.jersey.core:jersey-client:jar:2.26:compile
[INFO] | | +- org.glassfish.jersey.media:jersey-media-jaxb:jar:2.26:compile
[INFO] | | \- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] | \- javax.ws.rs:javax.ws.rs-api:jar:2.0.1:compile
[INFO] +- org.glassfish.jersey.media:jersey-media-json-jackson:jar:2.17:compile
[INFO] | +- org.glassfish.jersey.ext:jersey-entity-filtering:jar:2.26:compile
[INFO] | +- com.fasterxml.jackson.jaxrs:jackson-jaxrs-base:jar:2.3.2:compile
[INFO] | | +- com.fasterxml.jackson.core:jackson-core:jar:2.3.2:compile
[INFO] | | \- com.fasterxml.jackson.core:jackson-databind:jar:2.3.2:compile
[INFO] | +- com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:jar:2.3.2:compile
[INFO] | | \- com.fasterxml.jackson.module:jackson-module-jaxb-annotations:jar:2.3.2:compile
[INFO] | \- com.fasterxml.jackson.core:jackson-annotations:jar:2.3.2:compile
[INFO] \- se.hrmsoftware.hrm:sleepy-commons:jar:1.2-SNAPSHOT:compile
[INFO] +- org.glassfish.jersey.containers:jersey-container-servlet:jar:2.26:compile
[INFO] +- net.sourceforge.jtds:jtds:jar:1.3.1:compile
[INFO] +- com.microsoft.sqlserver:mssql-jdbc:jar:6.2.2.jre8:compile
[INFO] +- org.slf4j:slf4j-api:jar:1.7.12:compile
[INFO] +- jcifs:jcifs:jar:1.3.17:compile
[INFO] | \- javax.servlet:servlet-api:jar:2.4:compile
[INFO] +- org.slf4j:slf4j-simple:jar:1.7.12:compile
[INFO] +- commons-logging:commons-logging:jar:1.1.1:compile
[INFO] +- com.mchange:c3p0:jar:0.9.5.1:compile
[INFO] | \- com.mchange:mchange-commons-java:jar:0.2.10:compile
[INFO] +- commons-net:commons-net:jar:3.3:compile
[INFO] +- org.springframework:spring-jdbc:jar:4.1.6.RELEASE:compile
[INFO] | +- org.springframework:spring-beans:jar:4.1.6.RELEASE:compile
[INFO] | +- org.springframework:spring-core:jar:4.1.6.RELEASE:compile
[INFO] | \- org.springframework:spring-tx:jar:4.1.6.RELEASE:compile
[INFO] \- com.vaadin:vaadin-server:jar:7.5.5:compile
[INFO] +- com.vaadin:vaadin-sass-compiler:jar:0.9.12:compile
[INFO] | +- org.w3c.css:sac:jar:1.3:compile
[INFO] | \- com.vaadin.external.flute:flute:jar:1.3.0.gg2:compile
[INFO] +- com.vaadin:vaadin-shared:jar:7.5.5:compile
[INFO] | +- com.vaadin.external.streamhtmlparser:streamhtmlparser-jsilver:jar:0.0.10.vaadin1:compile
[INFO] | \- com.vaadin.external.google:guava:jar:16.0.1.vaadin1:compile
[INFO] \- org.jsoup:jsoup:jar:1.8.1:compile
```<issue_comment>username_1: `javax.ws.rs.client.RxInvokerProvider` was introduced in JAX RS API 2.1
Yet your dependency tree has ...
```
[INFO] | \- javax.ws.rs:javax.ws.rs-api:jar:2.0.1:compile
```
You have a bad dependency.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Whenever you encounter "Also this project have been working but now it wont start it anymore." you need to figure out what was changed when the project broke. In order to do so, you need source control (like git, mercurial or bazaar). Check out commits until you find the one where it worked before the commit and not after. Then look into what was changed.
If you use git, then `git bisect` may be helpful. See <https://git-scm.com/book/en/v2/Git-Tools-Debugging-with-Git#_binary_search> for how to do this.
If you don't use source control, now is a good time to reconsider.
Upvotes: 1 |
2018/03/19 | 869 | 2,527 | <issue_start>username_0: `stringi = "fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd"`
I was able to make a regEx to DYNAMICALLY find every last occurrence of a character X in every word: (I call it dynamically because I only have to change ONE spot)
`(n)(?!(\w+?)?\1(\w+?)?)` gives
```
"fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd"
^ ^ ^ ^ ^
```
`(d)(?!(\w+?)?\1(\w+?)?)` gives
```
"fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd"
^ ^ ^ ^ ^
```
### Question:
How can I get a "dynamic" regEx. That means I have to replace one spot like above to give me:
`some regEx with >>> n <<<` gives
```
"fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd"
^ ^ ^ ^ ^
```
`some regEx with >>> d <<<` gives
```
"fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd"
^ ^ ^ ^ ^
```
Is it possible to match those with a regEx and that I only have to change ONE spot when I want to match another character?
### Please note:
Pure regEx, no js string splitting etc..
### The Problem
With the lookbehind I run into a fixed length problem.<issue_comment>username_1: >
> That means I have to replace one spot
>
>
>
You first match `n` then every thing else:
```
n(\S*)
```
```js
var str = "fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd";
var char = 'n';
console.log(str.replace(new RegExp(char + '(\\S*)', 'g'), '*$1'));
var char = 'd';
console.log(str.replace(new RegExp(char + '(\\S*)', 'g'), '*$1'));
```
If it's a matter of interest, since Chrome has [implemented lookbehinds](https://github.com/tc39/proposal-regexp-lookbehind) (that luckily are infnite lookbehinds) you can acheive same result with this regex:
```
(?
```
[Live demo](https://regex101.com/r/w5sdfC/1)
Upvotes: 3 [selected_answer]<issue_comment>username_2: In [this regex demo](https://regex101.com/r/Lx9UUz/2), the lookbehind seems to be okay with not fixed length - with javascript. So this is the regex:
```
(?<=\b[^\Wd]*)d
```
Explanation:
* `\b` is a word barrier
* `[^d]*d` finds non-`d` characters, and then a `d`
* `[^\Wd]` is not a `d` but word characters. I.e. `\W` is not a word character, so `[^\W]` is a word character. So `[^\Wd]` is every word character, except `d`
* `\b[^\Wd]*d` would match the start of every word, up to the first `d`. Using the right constructs, this could be enough.
* `(?<=...)` is the lookbehind.
Upvotes: 1 |
2018/03/19 | 565 | 1,686 | <issue_start>username_0: I have the following jQuery code:
```
$(".dtp").datetimepicker({
format: 'Y-M-D hh:mm',
minDate: new Date()
});
```
I am using `datetimepicker` from Bootstrap and I'm trying to disable some days, based on information in my database.
For example all Mondays and Saturdays could be disabled. I can't seem to find information about how to do this.<issue_comment>username_1: >
> That means I have to replace one spot
>
>
>
You first match `n` then every thing else:
```
n(\S*)
```
```js
var str = "fuunnynsdfdn dfdfomdfdnd dfdfnntr ndfdf thatnfdfdfdfd";
var char = 'n';
console.log(str.replace(new RegExp(char + '(\\S*)', 'g'), '*$1'));
var char = 'd';
console.log(str.replace(new RegExp(char + '(\\S*)', 'g'), '*$1'));
```
If it's a matter of interest, since Chrome has [implemented lookbehinds](https://github.com/tc39/proposal-regexp-lookbehind) (that luckily are infnite lookbehinds) you can acheive same result with this regex:
```
(?
```
[Live demo](https://regex101.com/r/w5sdfC/1)
Upvotes: 3 [selected_answer]<issue_comment>username_2: In [this regex demo](https://regex101.com/r/Lx9UUz/2), the lookbehind seems to be okay with not fixed length - with javascript. So this is the regex:
```
(?<=\b[^\Wd]*)d
```
Explanation:
* `\b` is a word barrier
* `[^d]*d` finds non-`d` characters, and then a `d`
* `[^\Wd]` is not a `d` but word characters. I.e. `\W` is not a word character, so `[^\W]` is a word character. So `[^\Wd]` is every word character, except `d`
* `\b[^\Wd]*d` would match the start of every word, up to the first `d`. Using the right constructs, this could be enough.
* `(?<=...)` is the lookbehind.
Upvotes: 1 |
2018/03/19 | 1,336 | 3,789 | <issue_start>username_0: I'm currently working on code that reads in a sequence of integers in the form of m1, n1, m2, n2, until I input a zero, and it prints the sum of m \* n. Here is what I have so far:
```
#include
#include
#include
int main()
{
int m, n, i, sum = 0;
bool plus = true;
scanf("%d", &m);
scanf("%d", &n);
for(i = m; i <= n; i++)
{
sum = sum + (m \* n);
if(!plus)
{
putchar('+');
}
printf("%d\*%d", m, n);
plus = false;
}
printf("=%d\n", sum);
return 0;
}
```
If I type in 1, 1, 0, it prints out 1 \* 1 = 1, but if I were to type in, 1, 2, 3, 4, 0, it prints out 1\*2+1\*2=4. I'm just confused on how I get it to calculate 1\*2 and 3\*4.<issue_comment>username_1: you never read the 3rd and 4th arguments as the scanf calls are outside the loop. If you put them and the plus initializtion inside the loop, and correct the loop initilization and termination conditions your code should work (If I am not missing anything else).
Upvotes: 2 <issue_comment>username_2: ```
#include
#include
int main(void)
{
int sum, m, n;
if (!scanf("%d", &m))
return 0;
while (m)
{
if (!scanf("%d", &n))
return 0;
sum += m \* n;
if (!scanf("%d", &m))
return 0;
}
printf("%d", sum);
}
```
Try this. I wrote it quickly, but it should work. Code also should check if number of arguments is correct (situation when user input is X 0 or X X X 0 etc.). Issues spotted in your code:
1. User input outside the loop
2. No scanf() returns check
Upvotes: -1 <issue_comment>username_3: >
> I'm currently working on code that reads in a sequence of integers in
> the form of m1, n1, m2, n2, **until I input a zero**
>
>
>
It seems the approach you are using in whole is wrong. You should not enter the variables `m` and `n`. At least I do not see where 0 is entered and checked in your code.
What you are doing is calculating
```
sum = sum + (m * n);
```
`n - m + 1` times in the loop. Because `m` and `n` correspondingly were entered like `1` and `2` you got `4` (`1 * 2 + 1 * 2`).
I can suggest the following approach.
```
#include
int main(void)
{
printf( "Enter a sequence of integers (0 - exit): " );
long long int sum = 0;
int value, prev\_value;
unsigned int i;
i = 0;
while ( scanf( "%d", &value ) == 1 && value != 0 )
{
if ( i % 2 )
{
if ( i != 1 ) printf( " + " );
printf( " %d \* %d ", prev\_value, value );
sum += ( long long int )prev\_value \* value;
}
else
{
prev\_value = value;
}
++i;
}
if ( i % 2 )
{
if ( i != 1 ) printf( " + " );
printf( "%d", prev\_value );
sum += prev\_value;
}
printf( " = %lld\n", sum );
return 0;
}
```
The program output might look like
```
Enter a sequence of integers (0 - exit): 1 2 3 4 0
1 * 2 + 3 * 4 = 14
```
Upvotes: 2 [selected_answer]<issue_comment>username_4: You don't want a `for` loop like that, as you want to loop an indefinite amount. My recommendation is to use `while (true)`, and `break` from the loop when you reach the termination condition (or when `scanf()` fails to read both inputs):
```
#include
#include
int main()
{
int sum = 0;
char const \*plus = "";
while (true)
{
int m, n;
if (scanf("%d%d", &m, &n) != 2)
break;
if (m == 0 || n == 0)
break;
sum += m \* n;
printf("%s%d\*%d", plus, m, n);
plus = "+";
}
printf("=%d\n", sum);
}
```
A couple of other improvements in there: I've reduced the scope of `m` and `n` to be inside the loop, and I've changed `plus` to refer to the actual string to insert, rather than indirecting through a boolean.
Arguably, you might want to separate the `scanf()` back into the two calls you had, so that the terminating `0` need not be paired:
```
if (scanf("%d", &m) != 1 || m == 0)
break;
if (scanf("%d", &n) != 1 || n == 0)
break;
```
Upvotes: 0 |
2018/03/19 | 2,215 | 8,857 | <issue_start>username_0: I am using button with style="`?android:attr/buttonBarNeutralButtonStyle`"
```
```
I would like to get its color, so I can use it with other view elements as well.
Currently I am reading its color value like this:
```
int color;
View button = findViewById(R.id.passwordSigninButton);
if ((button != null) && (button instanceof Button))
color = ((Button) button).getCurrentTextColor();
// -16738680
```
...and it works fine. But I would prefer to get the color associated with the applicable style directly, without need to use of actual button, in case I want to use it without button being in my layout.
So I tried this approach:
```
TypedValue typedValue = new TypedValue();
getApplicationContext().getTheme().resolveAttribute(
android.R.attr.buttonBarNeutralButtonStyle, typedValue, true);
TypedArray typedArray = context.obtainStyledAttributes(
typedValue.data, new int[]{android.R.attr.textColor});
int color = typedArray.getColor(0, -1);
// -1
typedArray.recycle();
```
But I am getting `-1`, which means I am not getting the color I expected.
How can I get the color from the `android.R.attr.buttonBarNeutralButtonStyle` style?<issue_comment>username_1: I ran the same code that you have given above. I was able to get an Integer value.
**Output: System.out: Printing the color int value: -49023**
```
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TypedValue typedValue = new TypedValue();
getApplicationContext().getTheme().resolveAttribute(
android.R.attr.buttonBarNeutralButtonStyle, typedValue, true);
TypedArray typedArray = this.obtainStyledAttributes(
typedValue.data, new int[]{android.R.attr.textColor});
int color = typedArray.getColor(0, -1);
System.out.println("Printing the color int value: " + color);
typedArray.recycle();
}
}
```
*Below code has a different style:*
```
getApplicationContext().getTheme().resolveAttribute(
android.R.attr.actionButtonStyle, typedValue, true);
TypedArray typedArray = this.obtainStyledAttributes(
typedValue.data, new int[]{android.R.attr.colorForeground});
int color = typedArray.getColor(0, -1);
System.out.println("Printing the color int value: " + color);
```
**Output:System.out: Printing the color int value: -16777216**
---
I am using Android Studio 3.0.1
Build #AI-171.4443003, built on November 9, 2017
JRE: 1.8.0\_152-release-915-b08 x86\_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Mac OS X 10.13.3
Upvotes: 0 <issue_comment>username_2: *See update for direct derivation below.*
Your approach to determining the color of neutral button text is trying to duplicate the steps that Android takes in determining the color. This processing is under the hood and can change from release to release as I think we are seeing from the responses to this question. I am sure that the Android developers feel free to change the underlying implementation as long as the result is the same, so, even if you can get a solution that works today, it will be fragile and may break tomorrow.
You do have a solution, but it involves creating a layout that you want to avoid. I suggest the following approach which, I believe, will serve your purpose, will be a little more robust and will avoid the need for a layout file. You indicate that you are using `android.support.v7.app.AppCompatDialog` which creates `AppCompatButton` buttons.
The following two lines will give you the color of the neutral button text without a layout or the complication of extracting attributes. I have tested this on an emulator running API 22 and a Samsung S7 running API 24 and both results are consistent with what is seen with an explicit layout.
```
android.support.v7.widget.AppCompatButton button =
new android.support.v7.widget.AppCompatButton(this, null,
android.R.attr.buttonBarNeutralButtonStyle);
int color = button.getCurrentTextColor();
```
---
**Direct Derivation**
Although I believe that the above solution is the best, the following code will derive the default color of the neutral button for all APIs. This approach simply looks for the `textColor` attribute and, if that is not defined, looks for `textAppearance` and looks at the `textColor` defined there. It looks like the difference between the different APIs is how the color is specified. This solution *may* be robust enough to withstand subsequent updates but *caveat emptor*.
**MainActivity.java**
```
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v7.widget.AppCompatButton button =
new android.support.v7.widget.AppCompatButton(this, null, android.R.attr.buttonBarNeutralButtonStyle);
Log.d("MainActivity", String.format("<<<< Button color = 0x%08X", button.getCurrentTextColor()));
Log.d("MainActivity", String.format("<<<< Derived color = 0x%08X", getNeutralButtonColor(Color.WHITE)));
}
private int getNeutralButtonColor(int defaultColor) {
TypedArray ta;
int color = defaultColor;
boolean colorFound = false;
int textColorResId;
final int baseAttr = R.attr.buttonBarNeutralButtonStyle;
// Look for an explicit textColor attribute and use it if it is defined.
ta = getTheme().obtainStyledAttributes(null, new int[]{android.R.attr.textColor}, baseAttr, 0);
textColorResId = ta.getResourceId(0, -1);
if (textColorResId == -1) { // try to get color if not resource id
int type = ta.getType(0);
if (type >= TypedValue.TYPE_FIRST_COLOR_INT && type <= TypedValue.TYPE_LAST_COLOR_INT) {
color = ta.getColor(0, defaultColor);
colorFound = true;
}
}
ta.recycle();
if (textColorResId == -1 && !colorFound) {
// No color, yet. See if textAppearance is defined.
ta = obtainStyledAttributes(null, new int[]{android.R.attr.textAppearance},
baseAttr, 0);
int textAppearanceId = ta.getResourceId(0, -1);
if (textAppearanceId != -1) {
// OK, textAppearance is defined. Get the embedded textColor.
ta.recycle();
ta = obtainStyledAttributes(textAppearanceId, new int[]{android.R.attr.textColor});
textColorResId = ta.getResourceId(0, -1);
if (textColorResId == -1) { // try to get color if not resource id
int type = ta.getType(0);
if (type >= TypedValue.TYPE_FIRST_COLOR_INT && type <= TypedValue.TYPE_LAST_COLOR_INT) {
color = ta.getColor(0, defaultColor);
colorFound = true;
}
}
}
ta.recycle();
}
if (textColorResId != -1 && !colorFound) {
ColorStateList colorStateList = AppCompatResources.getColorStateList(this, textColorResId);
if (colorStateList != null) {
color = colorStateList.getDefaultColor();
colorFound = true; // in case needed later
}
}
return color;
}
@SuppressWarnings("unused")
private static final String TAG = "MainActivity";
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: You can create colors.xml inside values folder of the project and define the colors you want to use for the views. eg :
```
xml version="1.0" encoding="utf-8"?
#FFFFFF
#008000
#0000FF
#000000
```
Then in your styles, refer the colors from this file :
eg :
```
<item name="android:textColor">@color/blue</item>
```
Then for any other elements you want the color you need not depend on a view and just access from this colors.xml
```
textView.setTextColor(getResources().getColor(R.color.blue));
```
But if you want to really access it from the styles :
```
// The attributes you want retrieved
int[] attrs = {android.R.attr.textColor, android.R.attr.text};
// Parse style
TypedArray typedArray = obtainStyledAttributes(R.style.stylename, attrs);
// Get color from style
int textColor = typedArray.getColor(0, "default color");
//Check by priting
Log("Retrieved textColor as hex:", Integer.toHexString(textColor));
//recycle
typedArray.recycle()
```
Upvotes: 0 |
2018/03/19 | 817 | 2,571 | <issue_start>username_0: how to remove last single line available in file using perl.
I have my data like below.
```
"A",1,-2,-1,-4,
"B",3,-5,-2.-5,
```
---
how to remove the last line... I am summing all the numbers but receiving a null value at the end.
Tried using chomp but did not work.
Here is the code currently being used:
```
while () {
chomp(my @row = (split ',' , $\_ , -1);
say sum @row[1 .. $#row];
}
```<issue_comment>username_1: Try this (shell one-liner) :
```
perl -lne '!eof() and print' file
```
or as part of a script :
```
while (defined($_ = readline ARGV)) {
print $_ unless eof();
}
```
Upvotes: 1 <issue_comment>username_2: You should be using `Text::CSV` or `Text::CSV_XS` for handling comma separated value files. Those modules are available on CPAN. That type of solution would look like this:
```
use Text::CSV;
use List::Util qw(sum);
my $csv = Text::CSV->new({binary => 1})
or die "Cannot use CSV: " . Text::CSV->error_diag;
while(my $row = $csv->getline($fh)) {
next unless ($row->[0] || '') =~ m/\w/; # Reject rows that don't start with an identifier.
my $sum = sum(@$row[1..$#$row]);
print "$sum\n";
}
```
If you are stuck with a solution that doesn't use a proper CSV parser, then at least you'll need to add this to your existing while loop, immediately after your chomp:
```
next unless scalar(@row) && length $row[0]; # Skip empty rows.
```
The point to this line is to detect when a row is empty -- has no elements, or elements were empty after the chomp.
Upvotes: 1 <issue_comment>username_3: I suspect this is an X/Y question. You think you want to avoid processing the final (empty?) line in your input when actually you should be ensuring that all of your input data is in the format you expect.
There are a number of things you can do to check the validity of your data.
```
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use List::Util 'sum';
use Scalar::Util 'looks_like_number';
while () {
# Chomp the input before splitting it.
chomp;
# Remove the -1 from your call to split().
# This automatically removes any empty trailing fields.
my @row = split /,/;
# Skip lines that are empty.
# 1/ Ensure there is data in @row.
# 2/ Ensure at least one element in @row contains
# non-whitespace data.
next unless @row and grep { /\S/ } @row;
# Ensure that all of the data you pass to sum()
# looks like numbers.
say sum grep { looks\_like\_number $\_ } @row[1 .. $#row];
}
\_\_DATA\_\_
"A",1.2,-1.5,4.2,1.4,
"B",2.6,-.50,-1.6,0.3,-1.3,
```
Upvotes: 0 |
2018/03/19 | 369 | 1,225 | <issue_start>username_0: I have an ASP.NET Core 2.0 Razor Pages project. I am using Visual Studio 2017.
I have added one of our in-house assemblies to the project (it contains common definitions, types and functions etc). The project compiles but when I attempt to run it I get the following error.
[](https://i.stack.imgur.com/ihNUa.png)
Here is my .csproj file
```html
netcoreapp2.0
2018.3.12.6
..\packages\Common.dll
```
Here's my Visual Studio 2017 project showing the assembly in the project.
[](https://i.stack.imgur.com/6x6ul.png)
Googling the error doesn't provide much useful information.
How do I add a reference to a custom assembly in an ASP.NET Core 2.0 Razor Pages project?<issue_comment>username_1: The solution to the problem has been posted here <https://github.com/dotnet/core-setup/issues/2981>
See the top comment (by tuespetre) and then the update just further down (also by tuespetre). This worked for me.
Upvotes: 0 <issue_comment>username_2: I fixed the same issue by installing `Microsoft.Extensions.DependencyModel`, version 2.0.3.
Upvotes: 2 |
2018/03/19 | 351 | 1,323 | <issue_start>username_0: I'm currently using a simple method to test my textfield text like :
```
extension String {
func test() -> Bool {
return true
}
}
```
Now if try my function on a concrete String, all is ok
`let result = myString.test() //result is a Bool`
But if I execute it on an Optional String ( like `UITExtField.text` ), the type becomes `Optional`
`let result = myOptionalString?.test() //result is a Optional`
Is there a way to provide a default value ( or implementation ) to avoid the test of the result when the caller is `Optional`.
*I Know I can use some operators like `??` or do an if-else statement, but it's lot of code for nothing*
Thanks!<issue_comment>username_1: You can make extension for `Optional String`.
Example
```
extension Optional where Wrapped == String {
func test() -> Bool {
switch self {
case .none: return false
case .some(let string): return true
}
}
}
```
I hope it'll help you ;)
Upvotes: 3 [selected_answer]<issue_comment>username_2: You could extend `Optional` to return a default value if `nil`, or forward to `test()` if not.
```
extension Optional where Wrapped == String {
func test() -> Bool {
guard let value = self else { return false }
return value.test()
}
}
```
Upvotes: 1 |
2018/03/19 | 741 | 2,401 | <issue_start>username_0: I'm trying to do a count to see how many fields in column `value` are > 10:
```
SELECT
COUNT(CASE WHEN t.value > 10)
THEN 1
ELSE NULL
END
FROM table t
WHERE t.DATE = '2017-01-01'
```
However, the column has a few custom entries like `+15` or `>14.0`, so I added the following:
```
SELECT
COUNT(CASE WHEN value LIKE '>%'
and Replace(value, '>', '') > 10)
FROM table t
WHERE t.DATE = '2017-01-01'
```
However, after doing that, I get the following error:
>
> Conversion failed when converting the varchar value '>14.0' to data
> type int. Warning: Null value is eliminated by an aggregate or other
> SET operation.
>
>
>
Seeing I have no access to rewrite the database with an `UPDATE`, does anyone have a workaround solution?<issue_comment>username_1: It would be helpful to see the table and sample data, but it sounds like you have strings that are numbers and a sign.
You can cast it to convert the data since you are mixing and matching data types.
```
SELECT
COUNT(CASE WHEN CAST(value AS VARCHAR(10)) LIKE '>%'
and CAST(Replace(value, '>', '') AS your_num_datatype_here) > 10)
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You *could* fix this, either by simply changing `10` to `10.0`:
```
SELECT CASE WHEN '14.0' > 10.0 THEN 1 ELSE 0 END
```
This will cause the implicit conversion of `'14.0'` to decimal rather than int, which works, or you explicitly convert it:
```
SELECT CASE WHEN CONVERT(DECIMAL(14, 2), '14.0') > 10 THEN 1 ELSE 0 END
```
If it were me however, and I was not in a position to update the data, and do something a bit left field, like [use a numeric data type to store numbers](https://sqlblog.org/2009/10/12/bad-habits-to-kick-choosing-the-wrong-data-type), I would ignore these values completely, and simply use [`TRY_CONVERT`](https://learn.microsoft.com/en-us/sql/t-sql/functions/try-convert-transact-sql) to avoid the conversion errors:
```
SELECT
COUNT(CASE WHEN TRY_CONVERT(DECIMAL(14, 2), value) > 10 THEN 1 END)
```
It is a varchar column, so the possibilities of what nonsense could be in there are endless, you might get a query that works now by replacing `>` and `+`, but then what about when someone puts in `<`, or ends up with a space in between like `+ 14`, or something completely random like `'aaaa'`, where does it end?
Upvotes: 2 |
2018/03/19 | 472 | 1,754 | <issue_start>username_0: Is there a way to reopen a merge request within Gitlab once it's been merged like there is with an issue?
In this example a merge request was merged before a code review and has been reverted, but it would be great to reopen the original merge request to keep the original history/discussions<issue_comment>username_1: This is currently not possible. There is a [feature request](https://gitlab.com/gitlab-org/gitlab-foss/issues/26072) and someone already [started working on it](https://gitlab.com/gitlab-org/gitlab-foss/merge_requests/8352), but that work has stalled.
Currently the only option I see is to open a new merge request and link the old one. Probably not what you want, but easy to do, and at least the two MRs are linked.
I also looked at the [API](https://docs.gitlab.com/ce/api/notes.html#merge-requests), whether it is possible to duplicate the old MR. While the API does allow you to add discussions, this is very limited. Especially as it is currently not possible to add discussions to a specific file and line number. [It is not even possible to extract that information via the API](https://gitlab.com/gitlab-org/gitlab-foss/issues/22842).
Thus the only option to accomplish "reopening" or "duplicating" a merge request is to mess with the database or work on the [merge request](https://gitlab.com/gitlab-org/gitlab-foss/merge_requests/8352).
Upvotes: 3 <issue_comment>username_2: There's `Reopen merge request` button in Gitlab (Checked with 10.3.4-ce, but appeared earlier). However it does absolutely nothing when pressed, even with commits added to the branch the merge request is tied with.
[](https://i.stack.imgur.com/ZH2ID.png)
Upvotes: 3 |
2018/03/19 | 785 | 3,239 | <issue_start>username_0: I have a `DialogFragment` on an `Activity` class. This fragment has an `EditText` field and all I want to do is check if the field has less than 3 digits on the input then show a toast message. App keeps crashing and I can't even see what exception it is throwing me in the LogCat/Stacktrace.
Activity Class:
```
public class ParentActivity extends AppCompatActivity{
public boolean getTextCodeLength(){
EditText editTextfield = (EditText)findViewById(R.id.textFieldName);
if(editTextfield.length() < 4)
{
return false;
}
return true;
}
}
```
Fragment Class:
```
public class EnterTextFragment extends DialogFragment {
public void onDialogOkClick(DialogInterface dialog) {
try {
15. boolean result = ((ParentActivity) getActivity()).getTextCodeLength();
if (result == false) {
Toast.makeText(myContext, "Code needs to be longer than 4 digits", Toast.LENGTH_LONG).show();
}
}
catch(Exception ex)
{
Log.e("YOUR_APP_LOG_TAG", "I got an error", ex);
}
//Perform some other functions
}
}
```
Whenever it hits the line marked with number `15` - it keeps crashing and I don't even get what's causing the error because I am unable to see any exceptions in the LogCat as mentioned. Some help would great be appreciated.
More Context:
The toast is for testing purposes. Ideally I want to let the user stay on the fragment if their input is less than 4 digits.<issue_comment>username_1: Move this code to onCreate method of activity:
```
mEditTextfield = (EditText)findViewById(R.id.textFieldName);
```
Add field to your activity class:
```
private EditText mEditTextfield;
```
Modify your method:
```
public boolean getTextCodeLength(){
if(mEditTextfield.length() < LIMIT)
{
return false;
}
return true;
}
```
Also check if fragment is attached to activity in onDialogOkClick().
Upvotes: 0 <issue_comment>username_2: Why you don't handle `getTextCodeLength()` inside the fragment? It's wrong to define it inside the activity since it uses fields from fragment and the result is used only inside the fragment. I would is to keep a reference of the field inside the fragment (finding a view in the hierarchy is costly and it shouldn't be done each time when you press the button). So, declare a `EditText` in the fragment:
```
private EditText editText;
```
Override `onCreateView` to get a reference of the field:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.your_fragment_layout, container, false);
editText = contentView.findViewById(R.id.textFieldName);
return contentView;
}
```
Then delete the `getTextCodeLength` from the activity(also, maybe rename this method since the current name is misleading) and move it inside the fragment:
```
public boolean getTextCodeLength(){
if(editText.length() < 4)
{
return false;
}
return true;
}
```
Now everything should work smoothly without any crashes.
Upvotes: 2 [selected_answer] |
2018/03/19 | 464 | 1,746 | <issue_start>username_0: I use JMeter WebDriver Sampler (JMeter v4.0) for Chrome Driver (where I specify the path to chromedriver in `jp@gc - Chrome Driver Config`), and it works.
Now I want to try with latest Firefox Browser (FF Quantum v59.0), but it doesn't work. FF browser is opened but it doesn't go further, ex `WDS.browser.get('http://jmeter-plugins.org')` is not executed.
It seems JMeter WebDriver Sampler doesn't catch up with geckodriver and changes of FF. I google it, but I don't find any info on this regard. Does anyone know any update on this? Is there any workaround? Thanks<issue_comment>username_1: You should look at JMeter [Firefox Driver Config](https://jmeter-plugins.org/wiki/FirefoxDriverConfig/) plugin restrictions:
>
> the latest Firefox version may not work with the latest WebDriver set. The table below describes the version of Firefox that is compatible with JMeterPlugins:
>
>
>
Current version is compatible only with version 26 of Firefox
Also [firefox jmeter addon](https://addons.mozilla.org/en-US/firefox/addon/jmeter/) is not compatible
>
> This add-on is not compatible with your version of Firefox.
>
>
> Not compatible with Firefox Quantum
>
>
>
Upvotes: 2 [selected_answer]<issue_comment>username_2: The jmeter firefox driver config is only compatible with firefox 26, 33 and the latest is 45 and 46.
You cannot use the version of firefox which is greater than 46.0
Upvotes: 1 <issue_comment>username_3: Did you add the geckodriver file path in environment variable "Path". If not try that. I am using latest firefox with Jmeter Webdriver and is working for me.
Computer Properties - Advance System Settings - Environment Variables - Path (Add File Path without File name)
Upvotes: 0 |
2018/03/19 | 931 | 2,809 | <issue_start>username_0: I have this:
```css
span {
padding: 10px;
display: inline;
}
[title]:hover::before {
background: #333;
top: 20%;
background: rgba(0,0,0,.8);
border-radius: 5px;
color: #fff;
content: attr(title);
padding: 5px 15px;
position: absolute;
z-index: 98;
width: auto;
}
```
```html
Save
```
And I need to add a pointing arrow like this:
[](https://i.stack.imgur.com/KmEmw.png)
Can anyone help me achieve this by using only pseudo elements?
Thanks.<issue_comment>username_1: Like this?
```css
span {
padding: 10px;
display: inline;
}
[title] {
position: relative;
}
[title]:hover:before {
background: #333;
top: 100%;
background: rgba(0, 0, 0, .8);
border-radius: 5px;
color: #fff;
content: attr(title);
padding: 5px 15px;
position: absolute;
z-index: 98;
width: auto;
margin-top: 10px;
}
[title]:hover:after {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 10px solid #333;
content: ' ';
position: absolute;
top: 100%;
left: 50%;
}
```
```html
Save
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: I used a CSS triangle generator to create the arrow.
**Edit:** Added CSS for center alignment. Also provided comments in CSS explaining each value.
Add `:hover` pseudo selector to show tooltips only on hover. I removed them for easier development.
```css
.center-align {
text-align: center;
}
[title] {
position: relative;
}
[title]:before,
[title]:after {
z-index: 98;
}
[title]:before {
bottom: -10px;
/* calculate 50% width of the parent element minus width of the current element */
left: calc(50% - 10px);
width: 0;
height: 0;
border-style: solid;
border-width: 0 10px 10px 10px;
border-color: transparent transparent #333 transparent;
content: "";
position: absolute;
display: block;
}
[title]:after {
background: #333;
/* calculate single line height plus height of the arrow element */
top: calc(1em + 10px);
border-radius: 5px;
color: #fff;
content: attr(title);
padding: 5px 10px;
position: absolute;
/* calculate 50% width of the parent minus half of the width of current element minus half of the padding */
left: calc(50% - 45px - 5px);
/* requires fixed width for calculation above */
width: 90px;
text-align: center;
}
```
```html
Save and write a long description
Save
Save and write a long description
Save
```
Upvotes: 2 <issue_comment>username_3: *tooltip using tailwind peer selectors on hover or on focus (no JS)*
```html
?
Hi!, how can i help you?
```
Upvotes: 0 |
2018/03/19 | 815 | 3,163 | <issue_start>username_0: ```
var password= document.forms["PestControl"]["password"].value;
var confirmpassword= document.forms["PestControl"]["confirmpassword"].value;
function validateForm() {
//alert('inside');
if(!validatePassword()){
alert("password did not matched or blank password fields");
document.forms["PestControl"]["password"].focus();
return false;
}
else if($.trim(password) != $.trim(confirmpassword)){
alert("password did not matched");
document.forms["PestControl"]["password"].focus();
return true;
}
else {
document.PestControl.action = "medical\_college\_process.php?trans=addcollege";
document.PestControl.method = "post";
document.PestControl.submit();
}
}
function validatePassword(){
var password= document.forms["PestControl"]["password"].value;
var confirmpassword= document.forms["PestControl"]["confirmpassword"].value;
var Exist = false;
if((password.value === '') && (confirm\_password.value==='')) {
alert();
Exist = false;
}
else if(password.value != confirm\_password.value) {
Exist = false;
}
else {
Exist = true;
}
async:false;
return Exist;
}
Password
Confirm Password
Save
when i click on save button for password and confirm password i m getting an alert of password did not match or blank password for non-matching password as well as for matching password ...getting same alert message
when i click on save button for password and confirm password i m getting an alert of password did not match or blank password for non-matching password as well as for matching password ...getting same alert message
```
when i click on save button for password and confirm password i m getting an alert of password did not match or blank password for non-matching password as well as for matching password ...getting same alert message
when i click on save button for password and confirm password i m getting an alert of password did not match or blank password for non-matching password as well as for matching password ...getting same alert message<issue_comment>username_1: ```
function validatePassword(){
var password= document.getElementById("your pass id").value;
var confirmpassword= document.getElementById("confirm_password").value;
var Exist = false;
if((password === '') && (confirmpassword==='')) {
alert();
Exist = false;
}
else if(password != confirmpassword) {
Exist = false;
}
else {
Exist = true;
}
}
```
Upvotes: -1 <issue_comment>username_2: Please have a look at below code. It worked on my side.
```js
function validatePassword(){
var password= document.forms["PestControl"]["password"];
var confirmpassword= document.forms["PestControl"]["confirmpassword"];
var Exist = false;
if((password.value === '') && (confirmpassword.value==='')) {
alert('no input');
Exist = false;
}
else if(password.value != confirmpassword.value) {
alert('wrong password');
Exist = false;
}
else {
alert('correct');
Exist = true;
}
async:false;
return Exist;
}
```
```html
User password:
User confirm password:
```
Upvotes: 0 |
2018/03/19 | 1,006 | 3,382 | <issue_start>username_0: Following the example answer found at [ASP.NET/HTML: HTML button's onClick property inside ASP.NET (.cs)](https://stackoverflow.com/questions/3167246/asp-net-html-html-buttons-onclick-property-inside-asp-net-cs)
The button `"Click Me!"` works if I add the button html normally on the page. If I add it to the page using ASP.NET VB.NET `InnerHTML`, the click doesn't fire. Does anyone know why?
Below is after the HTML is rendered.
[](https://i.stack.imgur.com/LWrzy.jpg)
Below is the ASP.NET VB.NET code:
```
strTbl1 = "
| |
| --- |
|"
strTbl1 = strTbl1 + " Click me! |
"
strTbl1 = strTbl1 + "
"
Task1Assignees.InnerHtml = strTbl1
```
I have attempted `, `asp:Button ..` and etc but all don't register click event. If I attempt an asp type then I get a JavaScript error as well.`
**UPDATE:**
**Server Side function**
```
Protected Sub Button1_OnClick(ByVal sender As Object, ByVal e As EventArgs)
MsgBox("hi")
End Sub
```
**FINAL FIX**
So using example from [Dynamic created Buttons VB.Net with Loop](https://stackoverflow.com/questions/24604297/dynamic-created-buttons-vb-net-with-loop) and from the accepted answer below, I was able to fix my code like so
**Page\_Load** (outside the IsPostBack check)
```
Task1Assignees.Controls.Clear()
For j As Integer = 0 To System.Web.HttpContext.Current.Session("intAssignees") Step 1
Dim btn As New Button
btn.Text = "Mark Completed"
btn.CssClass = "btn btn-success"
btn.ID = "btnAssignee" & j
AddHandler btn.Click, AddressOf Send
Task1Assignees.Controls.Add(btn)
Next
```
**Button Creation**
```
System.Web.HttpContext.Current.Session("intAssignees") = ds1.Tables(0).Rows.Count
Task1Assignees.Controls.Clear()
For j As Integer = 0 To System.Web.HttpContext.Current.Session("intAssignees") Step 1
Dim btn As New Button
btn.Text = "Mark Completed"
btn.Cssclass = "btn btn-success"
btn.ID = "btnAssignee" & j
AddHandler btn.Click, AddressOf Send
Task1Assignees.Controls.Add(btn)
Next
```
**Function for button**
```
Sub Send()
Response.Redirect("~\Home.aspx")
End Sub
```<issue_comment>username_1: ```
function validatePassword(){
var password= document.getElementById("your pass id").value;
var confirmpassword= document.getElementById("confirm_password").value;
var Exist = false;
if((password === '') && (confirmpassword==='')) {
alert();
Exist = false;
}
else if(password != confirmpassword) {
Exist = false;
}
else {
Exist = true;
}
}
```
Upvotes: -1 <issue_comment>username_2: Please have a look at below code. It worked on my side.
```js
function validatePassword(){
var password= document.forms["PestControl"]["password"];
var confirmpassword= document.forms["PestControl"]["confirmpassword"];
var Exist = false;
if((password.value === '') && (confirmpassword.value==='')) {
alert('no input');
Exist = false;
}
else if(password.value != confirmpassword.value) {
alert('wrong password');
Exist = false;
}
else {
alert('correct');
Exist = true;
}
async:false;
return Exist;
}
```
```html
User password:
User confirm password:
```
Upvotes: 0 |
2018/03/19 | 628 | 2,307 | <issue_start>username_0: I am trying to to debug the react native app, If I don't try to debug JS remotely then everything is fine, but when I try to debug JS remotely I do get this error.
[](https://i.stack.imgur.com/mWXL4.png)<issue_comment>username_1: try to change your URL of Chrome from <http://localhost:8081/debugger-ui/> to <http://192.168.XXXX.XXXX.xip.io:8081/debugger-ui/>
source: <https://github.com/facebook/react-native/issues/17618>
Upvotes: 3 <issue_comment>username_2: I installed chrome CORS extension and enabled the CORS then it worked, Even If I open chrome with disable security manually then also it didn't worked for me until I install the extension.
Upvotes: 1 [selected_answer]<issue_comment>username_3: I had this error too. The reason for me was the opened debugger tab in chrome from previous session. So when I closed it everything works fine now :)
Upvotes: 8 <issue_comment>username_4: Aha! Found a better, less hacky solution. It seems when I upgraded Expo client on windows, it changed my default 'host'. Click the cog and change 'host' to 'LAN' to avoid CORS[](https://i.stack.imgur.com/xUtbw.png)
Upvotes: 0 <issue_comment>username_5: Close emulator.
Close node console which get opened after executing command react-native run-android.
Start emulator again.
Run project again.
Hope this help.
Upvotes: 2 <issue_comment>username_6: I had same error, I just closed the browser and refreshed my simulator. It may open the browser window again with debugging window. But it takes care of the error. If not I suggest terminating your simulator and running the build commands again.
Upvotes: 3 <issue_comment>username_7: i just cleared my browser cache and my app cache and its working now
this error appears when you have
Upvotes: 1 <issue_comment>username_8: This can be solved by restarting JS debugging and closing existing debugger.
* Close Chrome debugger session
On iOS, do:
* `CMD + CTRL + Z`
* Press `Stop Remote JS Debugging`
* `CMD + CTRL + Z` Again
* `enable Remote JS Debugging`
Almost the same on Android, but the difference is the keyboard command it is `CMD + M` on Mac or `CTRL+M` on Windows devices.
Upvotes: 2 |
2018/03/19 | 3,366 | 6,770 | <issue_start>username_0: I want to convert a JSON (not JSON-LD) array to RDF in Java. I have seen similar posts to the forum but not exact answer. The JSON array contains objects and arrays, something like:
```
{
"results": [
{
"record_id": "3d87f4df-f17e-4632-9449",
"demographics": { "gender":"female", "race":"", "age":20 }
},
{
"record_id": "ec5ca92d-865a-431f-9984",
"demographics": { "gender":"male", "age":118 }
},
{
"record_id": "0a79ecf0-83d8-4148-9054",
"demographics": { "gender":"female", "age":118 }
},
{
"record_id": "229276f8-1893-480b-b6e7",
"demographics": { "gender":"female", "age":35 }
},
{
"record_id": "0574cc3b-fb9c-495f-851c",
"demographics": { "gender":"female", "age":40 }
},
{
"record_id": "f3ccfdf6-231e-4a3e-bee0",
"demographics": { "gender":"male", "age":118 }
}
]
}
```
Any ideas?
Thanx!<issue_comment>username_1: I'd suggest you not hardcoding this conversion.
For RDBMS sources (by the way, why not use them), there is W3C-standardized [R2RML](https://www.w3.org/TR/r2rml/) ([r2rml](/questions/tagged/r2rml "show questions tagged 'r2rml'")).
For JSON and XML sources, there is [RML](http://rml.io/spec.html), an unofficial extension of R2RML.
[RML Mapper](https://github.com/RMLio/RML-Mapper) is a Java implementation of RML:
`$ bin/RML-Mapper -m ~/Desktop/mappings.ttl -o ~/Desktop/results.ttl`
In general, you should place `rml:iterator "$.results.[*]"` in the `rml:logicalSource` section to iterate over array elements. The exact answer depends on which vocabularies you want to use and the data model you want to achieve.
Let's suppose you need something like this:
```
@prefix exr: .
@prefix exo: .
exr:gender_female
a exo:Gender ;
rdfs:label "female" .
exr:gender_male
a exo:Gender ;
rdfs:label "male" .
exr:record_3d87f4df-f17e-4632-9449
a exo:Record ;
exo:patient_age 20 ;
exo:patient_gender exo:gender_female .
exr:record_ec5ca92d-865a-431f-9984
a exo:Record ;
exo:patient_age 118 ;
exo:patient_gender exo:gender_male .
```
Then your mappings should be:
```
@prefix rr: .
@prefix rml: .
@prefix ql: .
@prefix xsd: .
@prefix exo: .
@prefix exr: .
<#RecordMapping>
rml:logicalSource [
rml:source "/home/skralin/Desktop/results.json";
rml:referenceFormulation ql:JSONPath;
rml:iterator "$.results.[\*]"
];
rr:subjectMap [
rr:template "http://example.org/resource/record\_{record\_id}";
rr:class exo:Record
];
rr:predicateObjectMap [
rr:predicate exo:patient\_gender;
rr:objectMap [
rr:parentTriplesMap <#GenderMapping>
]
];
rr:predicateObjectMap [
rr:predicate exo:patient\_age;
rr:objectMap [
rml:reference "demographics.age" ;
rr:datatype xsd:integer
]
].
<#GenderMapping>
rml:logicalSource [
rml:source "/home/skralin/Desktop/results.json";
rml:referenceFormulation ql:JSONPath;
rml:iterator "$.results.[\*].demographics.gender"
];
rr:subjectMap [
rr:template "http://example.org/resource/gender\_{$}";
rr:class exo:Gender
];
rr:predicateObjectMap [
rr:predicate rdfs:label;
rr:objectMap [
rml:reference "$"
]
].
```
Upvotes: 2 <issue_comment>username_2: You could define a proper `@context` and use any JSON-LD converter to create any RDF serialization. Find [Java example here](https://stackoverflow.com/a/49076956/1485527) and [here](https://stackoverflow.com/questions/43219064).
**Example**
```
{
"@context":{
"results":{
"@id":"info:stack/49365220/results",
"@container":"@list"
},
"record_id":{
"@id":"info:stack/49365220/record_id"
},
"gender":{
"@id":"info:stack/49365220/gender"
},
"age":{
"@id":"info:stack/49365220/age"
},
"demographics":{
"@id":"info:stack/49365220/demographics"
}
},
"results": [
{
"record_id": "3d87f4df-f17e-4632-9449",
"demographics": { "gender":"female", "race":"", "age":20 }
},
{
"record_id": "ec5ca92d-865a-431f-9984",
"demographics": { "gender":"male", "age":118 }
},
{
"record_id": "0a79ecf0-83d8-4148-9054",
"demographics": { "gender":"female", "age":118 }
},
{
"record_id": "229276f8-1893-480b-b6e7",
"demographics": { "gender":"female", "age":35 }
},
{
"record_id": "0574cc3b-fb9c-495f-851c",
"demographics": { "gender":"female", "age":40 }
},
{
"record_id": "f3ccfdf6-231e-4a3e-bee0",
"demographics": { "gender":"male", "age":118 }
}
]
}
```
When putting this to [Json-Ld Playground](https://json-ld.org/playground/#startTab=tab-nquads&json-ld=%7B%22%40context%22%3A%7B%22results%22%3A%7B%22%40id%22%3A%22info%3Astack%2F49365220%2Fresults%22%2C%22%40container%22%3A%22%40list%22%7D%2C%22record_id%22%3A%7B%22%40id%22%3A%22info%3Astack%2F49365220%2Frecord_id%22%7D%2C%22gender%22%3A%7B%22%40id%22%3A%22info%3Astack%2F49365220%2Fgender%22%7D%2C%22age%22%3A%7B%22%40id%22%3A%22info%3Astack%2F49365220%2Fage%22%7D%2C%22demographics%22%3A%7B%22%40id%22%3A%22info%3Astack%2F49365220%2Fdemographics%22%7D%7D%2C%22results%22%3A%5B%7B%22record_id%22%3A%223d87f4df-f17e-4632-9449%22%2C%22demographics%22%3A%7B%22gender%22%3A%22female%22%2C%22race%22%3A%22%22%2C%22age%22%3A20%7D%7D%2C%7B%22record_id%22%3A%22ec5ca92d-865a-431f-9984%22%2C%22demographics%22%3A%7B%22gender%22%3A%22male%22%2C%22age%22%3A118%7D%7D%2C%7B%22record_id%22%3A%220a79ecf0-83d8-4148-9054%22%2C%22demographics%22%3A%7B%22gender%22%3A%22female%22%2C%22age%22%3A118%7D%7D%2C%7B%22record_id%22%3A%22229276f8-1893-480b-b6e7%22%2C%22demographics%22%3A%7B%22gender%22%3A%22female%22%2C%22age%22%3A35%7D%7D%2C%7B%22record_id%22%3A%220574cc3b-fb9c-495f-851c%22%2C%22demographics%22%3A%7B%22gender%22%3A%22female%22%2C%22age%22%3A40%7D%7D%2C%7B%22record_id%22%3A%22f3ccfdf6-231e-4a3e-bee0%22%2C%22demographics%22%3A%7B%22gender%22%3A%22male%22%2C%22age%22%3A118%7D%7D%5D%7D) (or [any other RDF tool](https://stackoverflow.com/questions/48275500)) you can produce something like this:
**serialized as N-TRIPLE**
```
_:b0 \_:b13 .
\_:b1 \_:b2 .
\_:b1 "3d87f4df-f17e-4632-9449" .
\_:b10 "40"^^ .
\_:b10 "female" .
\_:b11 \_:b12 .
\_:b11 "f3ccfdf6-231e-4a3e-bee0" .
\_:b12 "118"^^ .
\_:b12 "male" .
\_:b13 \_:b1 .
\_:b13 \_:b14 .
\_:b14 \_:b3 .
\_:b14 \_:b15 .
\_:b15 \_:b5 .
\_:b15 \_:b16 .
\_:b16 \_:b7 .
\_:b16 \_:b17 .
\_:b17 \_:b9 .
\_:b17 \_:b18 .
\_:b18 \_:b11 .
\_:b18 .
\_:b2 "20"^^ .
\_:b2 "female" .
\_:b3 \_:b4 .
\_:b3 "ec5ca92d-865a-431f-9984" .
\_:b4 "118"^^ .
\_:b4 "male" .
\_:b5 \_:b6 .
\_:b5 "0a79ecf0-83d8-4148-9054" .
\_:b6 "118"^^ .
\_:b6 "female" .
\_:b7 \_:b8 .
\_:b7 "229276f8-1893-480b-b6e7" .
\_:b8 "35"^^ .
\_:b8 "female" .
\_:b9 \_:b10 .
\_:b9 "0574cc3b-fb9c-495f-851c" .
```
Upvotes: 0 |
2018/03/19 | 956 | 2,662 | <issue_start>username_0: I'm using the find feature of Visual Studio with regular expressions to find if's in my code where there's no following curly braces. I came up with `if\ .*\).*\n.*{` to find if's where there are curly braces and it works. So similarly, I tried to use `if\ .*\).*\n.*[^{]`, but it just returns all the if's in the code. Can someone explain why this happens?
**Edit:**
The pattern I'm trying to match is
```
if (someCondition)
{ // <- Spot if there is a curly brace here
...
}
```<issue_comment>username_1: You might want to change your logic and use `^` and `$` - the start and end symbols of a line from `regex` syntax. Read more about it [here.](https://regexone.com/lesson/line_beginning_end)
I see you are looking for lines which starts with `if` and ends without `{`
```
if (var name){
}
if (var name)
```
so you want second if, not the first.
REGEX : `if \([\w]+ [\w]+\)$`
Check demo [here.](https://regexr.com/3mfsq)
Upvotes: 0 <issue_comment>username_2: In case you want to match `if` at the start of a line (or after whitespace) that is followed with a space and any 0+ chars followed with `)` at the end of the line, and then the next line should start with any char but whitespace and `{` you may use
```
^\s*if .*\)\s*[\r\n]+\s*[^\s{]
```
See the [regex demo](http://regexstorm.net/tester?p=%5E%5Cs*if%20.*%5C%29%5Cs*%5B%5Cr%5Cn%5D%2B%5Cs*%5B%5E%5Cs%7B%5D&i=if%20%28someCondition%29%0D%0A%20%20%20%20wh%20%3D%20fg%3B%0D%0Aif%20%28someCondition%29%20%0D%0A%7B%0D%0A%20%20%20%20wh%20%3D%20fg%3B%0D%0A%7D%0D%0Aif%20%28someCondition%29%20%7B%0D%0A%20%20%20%20wh%20%3D%20fg%3B%0D%0A%7D).
**Details**
* `^` - start of a line
* `\s*` - 0+ whitespaces (note that in VS search and replace regex flavor, it does not match line breaks)
* `if .*\)` - `if`, space, any 0+ chars other than line break chars as many as possible and then a `)`
* `\s*[\r\n]+\s*` - 1+ line break(s) enclosed with optional (0 or more) whitespace chars
* `[^\s{]` - any char but a whitespace or `{`.
Upvotes: 2 [selected_answer]<issue_comment>username_3: Unless you make wild assumptions about code formatting and limiting syntax, this search is too complex for regex.
No matter how fancy this regex gets (they can get pretty darned fancy :-), it will never be fancy enough, because the syntax is context free, which is beyond the power of regex.
Grab a yacc file for C (or C99) grammar ... (no promises, but there is one at <http://www.quut.com/c/ANSI-C-grammar-y-2011.html>), and look at the structure of a selection\_statement (i.e. IF '(' expression ')' ...).
There may be tools for this, but you roll the dice with regex.
Upvotes: 0 |
2018/03/19 | 1,785 | 6,590 | <issue_start>username_0: I'm developing an app which has two type of user (Admin, Normal User). Color of UITabBar and NavigationBar changes according to user type.
How I declare colors;
```
struct Color{
struct NavigationBar{
static let tintColor = UIColor(red:0.01, green:0.54, blue:0.16, alpha:1.0)
static let textColor = UIColor.white
}
```
How I call;
```
tabBarController.tabBar.barTintColor = Color.TabBar.tintColor
```
I can write an If statement in where I call "Color.TabBar" and choose right color but I'm wondering If I can do it with enum. Like below code;
```
struct Color{
struct NavigationBar{
enum tintColor{
case admin
case user
var color: UIColor{
switch self {
case .admin:
return UIColor(red:0.01, green:0.54, blue:0.16, alpha:1.0)
case .user:
return UIColor(red:0.01, green:0.54, blue:0.16, alpha:1.0)
default:
return UIColor(red:0.01, green:0.54, blue:0.16, alpha:1.0)
}
}
}
//static let tintColor = UIColor(red:0.01, green:0.54, blue:0.16, alpha:1.0)
static let textColor = UIColor.white
}
```
I find below article but I think this does not related with my problem. So my question is that how can I write that kind of enum?
[How can I make a Swift enum with UIColor value](https://stackoverflow.com/questions/39112879/how-can-i-make-a-swift-enum-with-uicolor-value)<issue_comment>username_1: The way you implement is correct, but you need to keep user type as global.
This is how it needs to be done;
```
enum tintColor{
case admin
case user
var tabbarColor: UIColor{
switch self {
case .admin:
return UIColor(red:0.01, green:0.54, blue:0.16, alpha:1.0)
case .user:
return UIColor(red:0.01, green:0.54, blue:0.16, alpha:1.0)
default:
return UIColor(red:0.01, green:0.54, blue:0.16, alpha:1.0)
}
}
}
static var user = tintColor.user
user.tabbarColor // this returns .user color
```
Upvotes: 2 <issue_comment>username_2: I believe what you want is not possible. Enum may not be a class, only a generic type, a structure.
But it is usually not what you want as when you will have many of these values you will have a mess anyway. For instance at some point you will have a button background color, border color and text color. Then waht do you expect your result to be like:
```
button.backgroundColor = UIButton.backgroundColor
button.layer.borderColor = UIButton.borderColor.cgColor
button.label.textColor = UIButton.textColor
```
And now having 3 enums for a single component... It is a solution but I think it is a bad one...
I suggest you rather create a static class and have it like so:
```
class UserApperance {
static var userType: UserType = .admin
static var navigationTintColor: UIColor {
switch userType {
case .admin: ...
case .user: ...
}
}
}
```
So all you will do in the code is again
```
tabBarController.tabBar.barTintColor = UserApperance.navigationTintColor
```
And when you want to group them you can use nesting:
```
class UserApperance {
static var userType: UserType = .admin
class NavigationBar {
static var tintColor: UIColor {
switch UserApperance.userType {
case .admin: ...
case .user: ...
}
}
}
}
```
Where the result is now nicer:
```
tabBarController.tabBar.barTintColor = UserApperance.NavigationBar.tintColor
```
In my opinion this is the nicest way and with really hard situations like white-label applications you can really play around with nesting and do it per screen and even have code like:
```
let appearance = UserAppearance.thisScreenName
titleLabel.textColor = appearance.title.textColor
titleLabel.font = appearance.title.font
```
Bot to mention you can generalize some things and even have usage as
```
UserAppearance.thisScreenName.title.configure(label: titleLabel)
```
Which may set all the property of your UI element...
But if you really, really badly want to have this you can still use something like strings as colors or pretty much any primitive...
You can create extensions like
```
extension UIView {
var backgroundColorString: String? {
set {
self.backgroundColor = UIColor(hexString: newValue)
}
get {
return self.backgroundColor.toHexString()
}
}
}
```
Then you obviously use this property to set the color directly from enumeration. But I discourage you to do this.
Upvotes: 2 [selected_answer]<issue_comment>username_3: Ok, so you have millions way of dealing with this, but remember that you have three elements :
**A user role variable**. Surely not only related to the UI, and thus defined somewhere like `enum UserRole { case user, admin }`. Let's say that you retrieve this information somewhere, and that you inject this variable in your view controllers.
**A way to convert this user role into styles**. For example, by using some static functions:
```
struct Styles {
struct NavigationBar {
static func barColor(from userRole:UserRole) -> UIColor {
switch userRole {
case .user: return UIColor.blue
case .admin: return UIColor.blue
}
}
static barFont(from userRole:UserRole) -> UIFont {
//... do the swith thing again
}
}
}
```
Another but related approach would be, if you start having more styles, you can also create a struct instance from an userRole variable.
```
struct Styles {
struct NavigationBar {
let color:UIColor
let font:UIFont
init(userRole:UserRole) {
switch userRole {
case .admin:
color = .red
font = UIFont.systemFont(ofSize: 10)
case .user:
color = .blue
font = UIFont.systemFont(ofSize: 16)
}
}
}
}
```
**Finally, from your controller**, just call the adequate method to retrieve the style. Here is an exemple using a simple dependency injection :
```
let userRole:UserRole
init(userRole:UserRole) {
self.userRole = userRole
super.init()
}
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not implemented") }
override func viewDidload() {
super.viewDidLoad()
tabBarController.tabBar.barTintColor = Styles.NavigationBar.barColor(from: userRole)
}
```
Upvotes: 1 |
2018/03/19 | 339 | 1,087 | <issue_start>username_0: In this table we see different transaction in same date some of Transaction Dr and some transaction Cr. I need Cr - Dr as Transaction Amount per date.
Please see screenshot [1st Table](https://i.stack.imgur.com/4GG1w.png)
[](https://i.stack.imgur.com/4GG1w.png)
Result will be-
[Result](https://i.stack.imgur.com/uxnci.png)
[](https://i.stack.imgur.com/uxnci.png)<issue_comment>username_1: you could use a case when and group by
```
select date, sum(case when drcr = 'CR' then amount
when drcr = 'DR' then -amount
else 0 end)
from my_table
group by date
```
Upvotes: 1 <issue_comment>username_2: as @scaisEdge but you need a sum.
```
select date, sum(case when drcr = 'CR' then amuont else (-1 * amount) end) as tran_amt
from my_table
group by date
```
This should be clear, but the way it works is to add credits and substract debits to the total for each date.
Upvotes: 0 |
2018/03/19 | 275 | 1,068 | <issue_start>username_0: I'm curious regarding best practices. Let's assume I need to construct an object that further is not supposed to be modified:
```
void fn() {
const std::string& ref_to_const = "one";
...
const std::string const_object = "two";
...
}
```
The lifespan of both temporary object and const object will be the same. So what approach to use?<issue_comment>username_1: >
> So what approach to use?
>
>
>
Generally, the one that is more expressive: the plain `const std::string`.
The fact that a constant reference can bind to and extend the lifetime of a temporary value mainly exists for making call-by-reference possible for temporaries. There is no reason to make use of this in a situation like yours.
Upvotes: 4 [selected_answer]<issue_comment>username_2: You create an instance, and using a reference to store that instance is just obfuscating this fact. Make your code explicit: You create an instance, so declare it as an instance, not as a reference:
```
const std::string const_object = "two";
```
Upvotes: 2 |
2018/03/19 | 915 | 3,673 | <issue_start>username_0: We have fact table(30 columns) stored in parquet files on S3 and also created table on this files and cache it afterwards. Table is created using this code snippet:
```
val factTraffic = spark.read.parquet(factTrafficData)
factTraffic.write.mode(SaveMode.Overwrite).saveAsTable("f_traffic")
%sql CACHE TABLE f_traffic
```
We run many different calculations on this table(files) and are looking the best way to cache data for faster access in subsequent calculations. Problem is, that for some reason it's faster to read the data from parquet and do the calculation then access it from memory. One important note is that we do not utilize every column. Usually, around 6-7 columns per calculation and different columns each time.
Is there a way to cache this table in memory so we can access it faster then reading from parquet?<issue_comment>username_1: The materalize dataframe in cache, you should do:
```
val factTraffic = spark.read.parquet(factTrafficData)
factTraffic.write.mode(SaveMode.Overwrite).saveAsTable("f_traffic")
val df_factTraffic = spark.table("f_traffic").cache
df_factTraffic.rdd.count
// now df_factTraffic is materalized in memory
```
See also <https://stackoverflow.com/a/42719358/1138523>
But it's questionable whether this makes sense at all because parquet is a columnar file format (meaning that projection is very efficient), and if you need different columns for each query the caching will not help you.
Upvotes: 2 [selected_answer]<issue_comment>username_2: It sounds like you're running on Databricks, so your query might be automatically benefitting from the [Databricks IO Cache](https://databricks.com/blog/2018/01/09/databricks-cache-boosts-apache-spark-performance.html). From the Databricks [docs](https://docs.databricks.com/user-guide/databricks-io-cache.html):
>
> The Databricks IO cache accelerates data reads by creating copies of remote files in nodes’ local storage using fast intermediate data format. The data is cached automatically whenever a file has to be fetched from a remote location. Successive reads of the same data are then executed locally, which results in significantly improved reading speed.
>
>
> The Databricks IO cache supports reading Parquet files from DBFS, Amazon S3, HDFS, Azure Blob Storage, and Azure Data Lake. It does not support other storage formats such as CSV, JSON, and ORC.
>
>
>
The Databricks IO Cache is supported on Databricks Runtime 3.3 or newer. Whether it is enabled by default depends on the instance type that you choose for the workers on your cluster: currently it is enabled automatically for Azure Ls instances and AWS i3 instances (see the [AWS](https://docs.databricks.com/user-guide/databricks-io-cache.html) and [Azure](https://docs.azuredatabricks.net/user-guide/databricks-io-cache.html) versions of the Databricks documentation for full details).
If this Databricks IO cache is taking effect then explicitly using Spark's RDD cache with an untransformed base table may harm query performance because it will be storing a second redundant copy of the data (and paying a roundtrip decoding and encoding in order to do so).
Explicit caching can still can make sense if you're caching a transformed dataset, e.g. after filtering to significantly reduce the data volume, but if you only want to cache a large and untransformed base relation then I'd personally recommend relying on the Databricks IO cache and avoiding Spark's built-in RDD cache.
See the full Databricks IO cache documentation for more details, including information on cache warming, monitoring, and a comparision of RDD and Databricks IO caching.
Upvotes: 2 |
2018/03/19 | 546 | 1,542 | <issue_start>username_0: I have a certificate `mycert.pem` . I got the **public key** of the certificate by command:
```
openssl x509 -pubkey -noout -in mycert.pem > pubkey.pem
```
How can I get the SHA256 hash of the public key?<issue_comment>username_1: The openssl `-pubkey` outputs the key in PEM format (even if you use `-outform DER`).
Assuming you have a RSA public key, you have to convert the key in DER format (binary) and then get its hash value:
```
openssl rsa -in pubkey.pem -pubin -outform der | openssl dgst -sha256
```
Upvotes: 3 <issue_comment>username_2: You can use ssh-keygen. Convert file format first
```
ssh-keygen -i -m PKCS8 -f pubkey.pem > NEWpubkey.pem
```
Next get the fingerprint
```
ssh-keygen -lf NEWpubkey.pem
```
Get type inference
>
> 2048 SHA256:hYAU9plz1WZ+H+eZCushetKpeT5RXEnR8e5xsbFWRiU no comment (RSA)
>
>
>
Upvotes: 4 <issue_comment>username_3: You can try directly decode public key with base64, then pipe to `shasum -a256`or `openssl sha256` to get the hash you want:
```bash
sed '1d;$d' ./pubkey.pem | base64 -D | openssl sha256 # or shasum -a256
```
If you use command question mentioned to output pubkey.pem like:
```
-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
```
You need strip first and last line in advance like `sed '1d;$d'`.
Then we use base64 `-d` or `-D` to decode (default to stdout) and pipe to `openssl sha256`.
All in one command:
```bash
sed '1d;$d' <(openssl x509 -pubkey -noout -in mycert.pem) | base64 -D | openssl sha256
```
Upvotes: 1 |
2018/03/19 | 1,742 | 5,277 | <issue_start>username_0: I have a sales pandas dataframe, where each row represents a company name, and there are four columns showing the current, minimum, maximum, and average sales amount over the last five years.
I wonder if there's a way to plot the min, max, avg, current horizontal bars inside the dataframe.
Just to give you a concrete example:
<https://libguides.lib.umanitoba.ca/bloomberg/fixedincome>
If you look at the "Range" column, that's precisely what I'm trying to replicate inside the dataframe. I found matplotlib boxplot but I don't think I can plot them inside the dataframe.
Are you aware of any solutions?<issue_comment>username_1: I am not totally sure what exactly you are looking for, so if you need anything else, please tell me.
I used pandas to create some dummy data and matplotlib for the graphs.
```
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'current':[3,4,7], 'minimum':[1,3,2], 'maximum':[10,14,11], 'average':[8,5,9]})
# average current maximum minimum
#0 8 3 10 1
#1 5 4 14 3
#2 9 7 11 2
```
Now the important part. I somewhat recreated your example from the image. This loop iterates over every row in your dataframe, that is, your companies. The result is as many graphs as you have companies.
* `ax.plot` creates a straight line from the `minimum` value to the
`maximum` value.
* `ax.scatter` creates points for the `current` and `average` values.
Of course, you have to adjust the graph a bit to make it look like you want it to.
```
for index,row in df.iterrows():
fig, ax = plt.subplots()
ax.plot([df['minimum'][index],df['maximum'][index]],[0,0],zorder=0)
ax.scatter(df['current'][index],0,zorder=1)
ax.scatter(df['average'][index],0,zorder=2)
```
This would be the graph for the first company.
[](https://i.stack.imgur.com/QbwDo.png)
**Edit (see @username_2's comment):** Putting the plotted data closer together
You can follow the approach above but adjust the style of the graphs.
```
for index,row in df.iterrows():
fig, ax = plt.subplots(figsize=(7, 0.2)) # adjust the width and height of the graphs
ax.plot([df['minimum'][index],df['maximum'][index]],[0,0],color='gray',zorder=0)
ax.scatter(df['current'][index],0,zorder=1)
ax.scatter(df['average'][index],0,marker='D',zorder=2)
plt.xticks([]) # disable the ticks of the x-axis
plt.yticks([]) # disable the ticks of the y-axis
for spine in plt.gca().spines.values(): # disable the border around the graphs
spine.set_visible(False)
```
This looks pretty close to the image you posted in your question.
[](https://i.stack.imgur.com/VOY2J.jpg)
Upvotes: 2 [selected_answer]<issue_comment>username_2: Ok, so based on NK\_ help and the content available in:
[Matplotlib- Creating a table with line plots in cells?](https://stackoverflow.com/questions/47779560/matplotlib-creating-a-table-with-line-plots-in-cells)
I managed to put this together:
```
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
df = pd.DataFrame({'Name':["A","B","C","E","F"],'current':[3,4,7,6,6], 'minimum':[1,3,2,4,1], 'maximum':[10,14,11,7,10], 'average':[8,5,9,5,3]})
data = np.random.rand(100,5)
col1 = df["Name"]
col2 = df["current"]
col2colors = ["red", "g", "r", "r", "r"]
col3 = df["average"]
finalsc = "D+"
fig, axes = plt.subplots(ncols=5, nrows=5, figsize=(6,2.6),
gridspec_kw={"width_ratios":[1,1,1,3,3]})
fig.subplots_adjust(0.05,0.05,0.95,0.95, wspace=0.02, hspace=0.05) #wspace, hspace --> bordi interni grigi della tabella
for ax in axes.flatten():
ax.tick_params(labelbottom=0, labelleft=0, bottom=0, top=0, left=0, right=0)
ax.ticklabel_format(useOffset=False, style="plain")
for _,s in ax.spines.items():
s.set_visible(True)
border = fig.add_subplot(111)
border.tick_params(labelbottom=0, labelleft=0, bottom=0, top=0, left=0, right=0)
border.set_facecolor("None")
text_kw = dict(ha="center", va="bottom", size=15)
for i,ax in enumerate(axes[:,0]):
ax.text(0.5, 0.2, col1[i], transform=ax.transAxes, **text_kw)
for i,ax in enumerate(axes[:,1]):
ax.text(0.5, 0.2, "{:.2f}".format(col2[i]),transform=ax.transAxes, **text_kw)
ax.set_facecolor(col2colors[i])
ax.patch.set_color(col2colors[i])
for i,ax in enumerate(axes[:,2]):
ax.text(0.5, 0.2, "{:.2f}".format(col3[i]),transform=ax.transAxes, **text_kw)
for i,ax in enumerate(axes[:,3]):
ax.plot(data[:,i], color="green", linewidth=1)
for i,ax in enumerate(axes[:,4]):
ax.plot([df['minimum'][index],df['maximum'][index]],[0,0],zorder=0)
ax.scatter(df['current'][index],0,zorder=1)
ax.scatter(df['average'][index],0,zorder=2)
plt.show()
```
To be fully honest, I don't know if the code I put together is the best code I could have used, there are many parts I still have to understand.
Pleas, the last question I would have is:
could somebody help me to add to this table a first "row" in which we show in bold the titles of each column?
Thanks
Upvotes: 0 |
2018/03/19 | 1,426 | 3,309 | <issue_start>username_0: I have a `div` block that simulates a small spinner, everything works fine however with the `css` configurations that I have it is positioned in the upper right wing, I tried to center it but when I see it from a mobile device it moves from place .. how could to center it without it changing position in devices with different sizes?
```
.spinner {
display: block;
position: fixed;
z-index: 1031;
top: 15px;
right: 15px;
}
```<issue_comment>username_1: Since it is fixed, the `top|left|right|bottom` attributes are relative to the window. So a position in percentages, in this case 50% should do the trick.
```
.spinner {
display: block;
position: fixed;
z-index: 1031; /* High z-index so it is on top of the page */
top: 50%;
right: 50%; /* or: left: 50%; */
margin-top: -..px; /* half of the elements height */
margin-right: -..px; /* half of the elements width */
}
```
Alternative, given by Utkanos in the comments
```
.spinner {
display: block;
position: fixed;
z-index: 1031; /* High z-index so it is on top of the page */
top: calc( 50% - ( ...px / 2) ); /* where ... is the element's height */
right: calc( 50% - ( ...px / 2) ); /* where ... is the element's width */
}
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: Try this to get center position on all size
```
.spinner{
position: absolute;
margin: auto;
top:0;
bottom: 0;
left: 0;
right: 0;
}
```
Upvotes: 3 <issue_comment>username_3: If you prefer the spinner to cover the entire viewport:
```css
.spinner {
border: 1px solid;
position: fixed;
z-index: 1;
left: 0;
right: 0;
top: 0;
bottom: 0;
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 50 50'%3E%3Cpath d='M28.43 6.378C18.27 4.586 8.58 11.37 6.788 21.533c-1.791 10.161 4.994 19.851 15.155 21.643l.707-4.006C14.7 37.768 9.392 30.189 10.794 22.24c1.401-7.95 8.981-13.258 16.93-11.856l.707-4.006z'%3E%3CanimateTransform attributeType='xml' attributeName='transform' type='rotate' from='0 25 25' to='360 25 25' dur='0.6s' repeatCount='indefinite'/%3E%3C/path%3E%3C/svg%3E") center / 50px no-repeat;
}
```
If you want it to be only the size of the gif/svg:
```css
.spinner {
border: 1px solid;
position: fixed;
z-index: 1;
left: 0;
right: 0;
top: 0;
bottom: 0;
width: 50px;
height: 50px;
margin: auto;
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 50 50'%3E%3Cpath d='M28.43 6.378C18.27 4.586 8.58 11.37 6.788 21.533c-1.791 10.161 4.994 19.851 15.155 21.643l.707-4.006C14.7 37.768 9.392 30.189 10.794 22.24c1.401-7.95 8.981-13.258 16.93-11.856l.707-4.006z'%3E%3CanimateTransform attributeType='xml' attributeName='transform' type='rotate' from='0 25 25' to='360 25 25' dur='0.6s' repeatCount='indefinite'/%3E%3C/path%3E%3C/svg%3E") center / contain no-repeat;
}
```
Upvotes: 3 <issue_comment>username_4: Just try the `transform` and position `top` and `left` combination...
***Note:*** Here I have used font-awesome just for demonstration
```css
.spinner {
position: fixed;
z-index: 1031;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
```
```html
```
Upvotes: 3 |
2018/03/19 | 985 | 3,115 | <issue_start>username_0: My Goal is to **generate** log file on each day but of `MaxFileSize=100KB`
So I used DailyRollingFileAppender since I am using log4j 2.2 version
Date is working fine and when I used MaxFileSize it didnt worked and new file was not created based on filesize still date is working.
**Problem**: MaxFileSize not working with DatePattern for DailyRollingfileAppender
Here is log4j.properties file code:
```
log4j.rootLogger=DEBUG, stdout, file
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d [%t] %-5p (%F:%L) - %m%n
log4j.appender.file.File=${catalina.home}/logs/abc
log4j.appender.file.MaxFileSize=80KB
log4j.appender.file.MaxBackupIndex=2
log4j.appender.file.DatePattern='-'yyyy-MM-dd'.log'
```
Something need to be changed in date pattern but dont know yet<issue_comment>username_1: Try below configuration for rotating the file based on time and size -
```
status = warn
name= properties_configuration
property.basePath = ${catalina.home}/logs/
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.target = SYSTEM_OUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %level %c{1}:%L - %msg%n
appender.rolling.type = RollingFile
appender.rolling.name = fileLogger
appender.rolling.fileName=${basePath}/abc.log
appender.rolling.filePattern=${basePath}abc_%d{yyyyMMdd}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %level (%F:%L) - %msg%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size = 100 KB
# write your package name as the value of this key
logger.example.name = log4j2.example
logger.example.level = info
logger.example.additivity = false
logger.example.appenderRef.rolling.ref = fileLogger
logger.example.appenderRef.console.ref = consoleLogger
rootLogger.level = error
rootLogger.additivity = false
rootLogger.appenderRef.rolling.ref = fileLogger
rootLogger.appenderRef.console.ref = consoleLogger
```
Upvotes: 1 <issue_comment>username_2: ```xml
xml version="1.0" encoding="UTF-8"?
C:/logs/x2c.log
C:/logs/%d{yyyy-MM-dd-hh-mm}-%i.log
style{%d{yyyy-MMM-dd HH:mm:ss a}}{black} %-5p %style{[%t]}{blue} %highlight{%level}{FATAL=bg\_red, ERROR=red, WARN=yellow, INFO=green, DEBUG=blue} %logger{36} - %msg%n
```
This is the xml based configuration which is working fine but exact properties or basic configuration isn't working. File not created and no console output
Upvotes: 0 |
2018/03/19 | 1,449 | 5,329 | <issue_start>username_0: i am using the `atlassian-connect-express` toolkit for creating [Atlassian Connect based Add-ons with Node.js.](https://bitbucket.org/atlassian/atlassian-connect-express?_ga=2.34680361.944228291.1521436616-567879398.1514966208)
It provides Automatic JWT authentication of inbound requests as well as JWT signing for outbound requests back to the host.
The add-on is authenticated when i install it in the JIRA dashboard and return the following pay-load:
```
{ key: 'my-add-on',
clientKey: '*****',
publicKey: '********'
sharedSecret: '*****'
serverVersion: '100082',
pluginsVersion: '1.3.491',
baseUrl: 'https://myaccount.atlassian.net',
productType: 'jira',
description: 'Atlassian JIRA at https://myaccount.atlassian.net ',
eventType: 'installed' }
```
But i am not able to authenticate the JIRA Rest Api with the JWT token generated by the framework. It throws below error message.
```
404 '{"errorMessages":["Issue does not exist or you do not have permission to see it."],"errors":{}}'
```
below is the code when i send a GET request:
```
app.get('/getissue', addon.authenticate(), function(req, res){
var request = require('request');
request({
url: 'https://myaccount.atlassian.net/rest/api/2/issue/ABC-1',
method: 'GET',
}, function(error, response, body){
if(error){
console.log("error!");
}else{
console.log(response.statusCode, body);
}
});
res.render('getissue');
});
```
Below is the code for my app descriptor file:
```
{
"key": "my-add-on",
"name": "Ping Pong",
"description": "My very first add-on",
"vendor": {
"name": "Ping Pong",
"url": "https://www.example.com"
},
"baseUrl": "{{localBaseUrl}}",
"links": {
"self": "{{localBaseUrl}}/atlassian-connect.json",
"homepage": "{{localBaseUrl}}/atlassian-connect.json"
},
"authentication": {
"type": "jwt"
},
"lifecycle": {
"installed": "/installed"
},
"scopes": [
"READ",
"WRITE"
],
"modules": {
"generalPages": [
{
"key": "hello-world-page-jira",
"location": "system.top.navigation.bar",
"name": {
"value": "Hello World"
},
"url": "/hello-world",
"conditions": [{
"condition": "user_is_logged_in"
}]
},
{
"key": "getissue-jira",
"location": "system.top.navigation.bar",
"name": {
"value": "Get Issue"
},
"url": "/getissue",
"conditions": [{
"condition": "user_is_logged_in"
}]
}
]
}
```
}
I am pretty sure this is not the correct way i am doing, Either i should use OAuth. But i want to make the JWT method for authentication work here.<issue_comment>username_1: You should be using global variable 'AP' that's initialized by JIRA along with your add-on execution. You may explore it with Chrome/Firefox Debug.
Have you tried calling ?
```
AP.request(..,...);
```
instead of "var request = require('request');"
You may set at the top of the script follwing to pass JS hinters and IDE validations:
```
/* global AP */
```
And when using AP the URL should look like:
```
url: /rest/api/2/issue/ABC-1
```
instead of:
```
url: https://myaccount.atlassian.net/rest/api/2/issue/ABC-1
```
My assumption is that ABC-1 issue and user credentials are verified and the user is able to access ABC-1 through JIRA UI.
Here is doc for ref.: <https://developer.atlassian.com/cloud/jira/software/jsapi/request/>
Upvotes: 0 <issue_comment>username_2: Got it working by checking in here [Atlassian Connect for Node.js Express Docs](https://bitbucket.org/atlassian/atlassian-connect-express?_ga=2.59557037.1006855938.1523370641-567879398.1514966208)
Within JIRA ADD-On Signed HTTP Requests works like below. GET and POST both.
GET:
```
app.get('/getissue', addon.authenticate(), function(req, res){
var httpClient = addon.httpClient(req);
httpClient.get('rest/api/2/issue/ABC-1',
function(err, resp, body) {
Response = JSON.parse(body);
if(err){
console.log(err);
}else {
console.log('Sucessful')
}
});
res.send(response);
});
```
POST:
```
var httpClient = addon.httpClient(req);
var postdata = {
"fields": {
"project":
{
"key": "MYW"
},
"summary": "My Story Name",
"description":"My Story Description",
"issuetype": {
"name": "Story"
}
}
}
httpClient.post({
url: '/rest/api/2/issue/' ,
headers: {
'X-Atlassian-Token': '<PASSWORD>'
},
json: postdata
},function (err, httpResponse, body) {
if (err) {
return console.error('Error', err);
}
console.log('Response',+httpResponse)
});
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 884 | 2,248 | <issue_start>username_0: My builds fils with the folloewing error:
```
There is an error in XML document (1, 1).
```
>
> TFS2017 update 1 Agent version 2.127.0
>
>
>
We have a strange problem on our build server:
```
2018-03-19T13:23:41.9444545Z ##[section]Starting: Get Sources
2018-03-19T13:23:41.9962547Z Prepending Path environment variable with directory containing 'tf.exe'.
2018-03-19T13:23:41.9970401Z Setting environment variable
TFVC_BUILDAGENT_POLICYPATH
2018-03-19T13:23:41.9971268Z Querying workspace information.
2018-03-19T13:23:43.0915688Z ##[error]There is an error in XML document (1, 1).
2018-03-19T13:23:43.1000481Z ##[section]Finishing: Get Sources
```
If we run the same job again, on the same agent, it run's again without error We did not have these problem with agent with an older version 1.105.6<issue_comment>username_1: I installed a new agent next to the old one and it has its own work area, I can now perform a rollback.
I have the rollback disabled on the new agent.
I the file with the error: Worker\_20180319-132335-utc.log
The files are here: <https://onedrive.live.com/?id=A426FE4732C90B65%211438&cid=A426FE4732C90B65>
Upvotes: -1 <issue_comment>username_2: I had the same issue, after updating VS to "15.8.5" went through several rounds of trying to update the agents and look through the logs, the offending statement seems to be:
>
> [2018-09-24 20:10:56Z INFO ProcessInvoker] File name: 'tf'
> [2018-09-24 20:10:56Z INFO ProcessInvoker] Arguments: 'vc workspaces
> /format:xml
> /collection:<https://tfs.devxxxcatalyst.com/tfs/XXXCollection/>
> /loginType:OAuth /login:.,\*\*\*\*\*\*\*\* /noprompt'
>
>
>
Looked like the issue was with the workspace, I deleted all the work spaces TFS created:
[](https://i.stack.imgur.com/X29Fz.png)
Reran the build, seems to work now...
Upvotes: 2 <issue_comment>username_3: Let me spell it out: You need to `update the build agent`.
[](https://i.stack.imgur.com/wR6os.png)
The azure url is in format
>
> https://[myorganisation].visualstudio.com/[project\_name]/\_settings/agentqueues
>
>
>
Upvotes: 0 |
2018/03/19 | 462 | 1,810 | <issue_start>username_0: I am trying to activate an iOS Notification Center timer and simultaneously send a user to a web URL (in actuality a survey). I can't figure out how to get the two actions from a single button. Here is the code I have that currently uses two separate buttons:
```
@IBAction func timer(_ sender: Any)
{
let content = UNMutableNotificationContent()
content.title = "Reminder"
content.subtitle = "Click This Notice"
content.body = "Please Repeat Daily"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 86400, repeats: true)
let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
@IBAction func survey(_ sender: Any) {
if let url = NSURL(string: "https://yahoo.com"){ UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)}
}
```
Any help is much appreciated as I am a less than basic programmer.<issue_comment>username_1: From the Storyboard you can simply cntrl drag from your button to your View Controller. Select action and name action1.. or whatever.
Do this a second time for action2
Implement your two actions and you are done. When you click the button, both actions will be called.
Upvotes: 1 <issue_comment>username_2: This is what your button target may look like:
```
button.addTarget(self, action: #selector(timer(_:)), for: .touchUpInside)
```
Just call the second method from inside the first method:
```
@objc func timer(_ sender: Any) {
print("timer")
survey(sender)
}
@objc func survey(_ sender: Any) {
print("survey")
}
```
Just pass the button as the argument for the second method's parameter.
Upvotes: 0 |
2018/03/19 | 2,018 | 7,073 | <issue_start>username_0: Well, `Hospital` is the class which has vector of patients.
`FemaleIn`, `FemaleOut`, `MaleIn`, `MaleOut` are derived classes from patients(Base class). Those classes have `toString` function(method). What I am trying to do is, in `display` method in `Hospital` class, I just want to display only in case of `Outpatient` which is parent class of `FemaleOut` and `Maleout` or `Inpatient` which is parent class of `FemaleIn` and `MaleIn`. From what I am thinking to call only specific method from, for example, `Outpatient`, I will have to know which objects in which index of vector for automatically. Is there any idea to call only `toString` for specific class which is, for example, `FemaleIn` and `MaleIn` where parent class is `Inpatient`. Thank you for your any help or suggestion.
```
void Hospital::determinePatientType()
{
int selection;
cout << endl;
cout << "What is the patient type?" << endl;
cout << "1. Female Inpatient" << endl;
cout << "2. Female Outpatient" << endl;
cout << "3. Male Inpatient" << endl;
cout << "4. Male Outpatient" << endl;
cout << endl;
cin >> selection;
switch(selection)
{
case 1:
patients.push_back(new FemaleIn());
cout << patients.back() << endl;
patients[totalPatients]->enterPatientData();
totalPatients++;
break;
case 2:
patients.push_back(new FemaleOut());
cout << patients.back() << endl;
patients[totalPatients]->enterPatientData();
totalPatients++;
break;
case 3:
patients.push_back(new MaleIn());
cout << patients.back() << endl;
patients[totalPatients]->enterPatientData();
totalPatients++;
break;
case 4:
patients.push_back(new MaleOut());
cout << patients.back() << endl;
patients[totalPatients]->enterPatientData();
totalPatients++;
break;
default:
return;
}
}
void Hospital::display(string type)
{
cout << "Patient Name Spouse Name Sex Patient Type Unit/Appt. Date Diagnosis" << endl;
cout << "===================================================================================" << endl;
if(type=="All")
{
for(int i=0;itoString();
}
}
else if(type=="Outpatient")
{
for(int i=0;itoString();
}
}
else
{
for(int i=0;itoString();
}
}
}
```<issue_comment>username_1: As quick and dirty way you can use `dynamic_cast` to certain class pointer to detect whether given instance is of that class:
```
if (type == "Outpatient")
{
for(int i=0; i(patients[i]);
if (p) {
p->toString();
}
}
}
```
For clean way you could use [Visitor pattern](https://en.wikipedia.org/wiki/Visitor_pattern)
Visitor pattern implementation:
```
#include
#include
#include
#include
#include
class AbstractDirectionPatientsDispatcher;
class AbstractGenderPatientDispatcher;
class Patient
{
public:
virtual void accept(AbstractDirectionPatientsDispatcher &dispatcher) = 0;
virtual void accept(AbstractGenderPatientDispatcher &dispatcher) = 0;
std::string name;
};
class InPatient;
class OutPatient;
class AbstractDirectionPatientsDispatcher {
public:
virtual void dispatch(InPatient &patient) = 0;
virtual void dispatch(OutPatient &patient) = 0;
};
class FemalePatient;
class MalePatient;
class AbstractGenderPatientDispatcher {
public:
virtual void dispatch(FemalePatient &patient) = 0;
virtual void dispatch(MalePatient &patient) = 0;
};
template
class CRTPDispatchApplier : virtual public Patient
{
public:
void accept(Dispatcher &dispatcher) override {
dispatcher.dispatch(static\_cast(\*this));
}
};
class InPatient : public CRTPDispatchApplier
{
};
class OutPatient : public CRTPDispatchApplier
{
};
class FemalePatient : public CRTPDispatchApplier
{
};
class MalePatient : public CRTPDispatchApplier
{
};
class InFemale : public FemalePatient, public InPatient
{
};
class OutFemale : public FemalePatient, public OutPatient
{
};
class InMale : public MalePatient, public InPatient
{
};
class OutMale : public MalePatient, public OutPatient
{
};
class DummyDirectionDispatecher : public AbstractDirectionPatientsDispatcher
{
public:
void dispatch(InPatient & ) override {
}
void dispatch(OutPatient & ) override {
}
};
class DummyGenderDispatcher : public AbstractGenderPatientDispatcher
{
public:
void dispatch(FemalePatient &) override {
}
void dispatch(MalePatient &) override {
}
};
template
class DispatchByDirection : public DummyDirectionDispatecher
{
public:
DispatchByDirection(std::function action) :
m\_action(std::move(action))
{}
void dispatch(Direction & p) override {
m\_action(p);
}
private:
std::function m\_action;
};
template
class DispatchByGender : public DummyGenderDispatcher
{
public:
DispatchByGender(std::function action) :
m\_action(std::move(action))
{}
void dispatch(Gender & p) override {
m\_action(p);
}
private:
std::function m\_action;
};
int main() {
InFemale f1;
OutFemale f2;
InMale m1;
OutMale m2;
f1.name = "Eve";
f2.name = "Alice";
m1.name = "Bob";
m2.name = "Charlie";
std::vector patients;
patients.push\_back(&f1);
patients.push\_back(&f2);
patients.push\_back(&m1);
patients.push\_back(&m2);
DispatchByDirection print\_in\_patients{[](InPatient &patient){
std::cout << "in: " << patient.name << std::endl;
}};
for (auto p : patients) {
p->accept(print\_in\_patients);
}
std::cout << std::endl;
DispatchByDirection print\_out\_patients{[](OutPatient &patient) {
std::cout << "out: " << patient.name << std::endl;
}};
for (auto p : patients) {
p->accept(print\_out\_patients);
}
std::cout << std::endl;
DispatchByGender print\_female{[](FemalePatient &patient) {
std::cout << "female: " << patient.name << std::endl;
}};
for (auto p : patients) {
p->accept(print\_female);
}
std::cout << std::endl;
DispatchByGender print\_male{[](MalePatient &patient) {
std::cout << "male: " << patient.name << std::endl;
}};
for (auto p : patients) {
p->accept(print\_male);
}
std::cout << std::endl;
}
```
Upvotes: 0 <issue_comment>username_2: I think this question might be similar to [How do I check if an object's type is a particular subclass in C++?](https://stackoverflow.com/questions/307765/how-do-i-check-if-an-objects-type-is-a-particular-subclass-in-c) .
I would propose something like:
```
Class Patient{
virtual bool display(string filter);
};
Class OutPatient : Patient {
bool display(string filter) override;
};
bool OutPatient::display(string filter) {
if (filter != "OutPatient")
return false;
//Do stuff
return true;
}
Class InPatient : Patient {
bool display(string filter) override;
};
// You could just make this the default definition on display on Patient
bool InPatient::display(string filter) {
return false;
}
```
And then:
```
void Hospital::display(string type)
{
for(auto& patient: patients)
patient->display(type);
}
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 319 | 1,125 | <issue_start>username_0: Is it possible to write a SQL query that does the following:
```
Select * From Table1
```
if there are results, return them. Otherwise, use an alternative query and return it's results:
Select \* From Table2
I came ups with the following, but it does not seem to work:
```
IF EXISTS(select * From TableA)
begin
Select * from TableA
end
else
Select * from TableB
```
Is there a simple elegant way of accomplishing this?<issue_comment>username_1: You can do a `UNION` query with `NOT EXISTS`:
```
SELECT * FROM TABLE1
UNION ALL
SELECT * FROM TABLE2 WHERE NOT EXISTS (SELECT * FROM TABLE1)
```
\*Assuming the columns and types are the same
Upvotes: 3 [selected_answer]<issue_comment>username_2: If both tables have same number of columns and the column names are same then you use Union, like below.
```
Select * from TableA
Union
Select * from TableB
```
If they have different column names or different number of columns then you can use below code.
```
Select Col_1 as col1, col_2 as col2.... From TableA
Union
Select col_a as Col1, col_b as Col2..... From TableB
```
Upvotes: 0 |
2018/03/19 | 383 | 1,314 | <issue_start>username_0: I have a list with the months of the year,
i have a second list that is empty called sales
how would i go about asking a user to enter the slate for each month.
ie.
```
Jan>>>user enters sales
Feb>>>user enters sales
```
etc.
the amounts that the user enters should be added to the sales list.
im new to python
Thanks<issue_comment>username_1: If I understood your question correctly, you are looking for something like this:
```
months = ["Jan", "Feb", "Mar"] # and so on
sales = []
for month in months:
sales.append(input("Enter sales for %s" % month))
```
I recommend checking out a simple tutorial on python programming.
Upvotes: 1 <issue_comment>username_2: You can iterate the months lists through a for loop and prompt the user for input. for example take a look at the following code.
```
months = ['jan', 'feb', 'mar', 'aprl']
sales = []
for idx, month in enumerate(months):
sales.append(int(input('enter sale')))
print(sales)
```
Upvotes: 1 <issue_comment>username_3: ```
months = ["January", "Febuary", "March","April","May","June","July","August","September","October","November","December"]
sales = []
for month in months:
sales.append(input(month+"> "))
for i in range(0, len(months)):
print(months[i] + " Sales " + sales[i])
```
Upvotes: 0 |
2018/03/19 | 403 | 1,368 | <issue_start>username_0: I want to create a clustered columnstore index in a table using the following query:
```
CREATE CLUSTERED COLUMNSTORE INDEX cci
ON agl_20180319_bck
```
And I am getting this error:
>
> Msg 35343, Level 16, State 1, Line 6
>
> The statement failed. Column 'memberOf' has a data type that cannot participate in a columnstore index. Omit column 'memberOf'.
>
>
>
The 'memberOf' is in this type: `memberOf nvarchar(max)`.
How to overcome/ignore this error and what does it mean?<issue_comment>username_1: You'll need to specify the participating columns individually, excluding memberOf and any other columns that can't be used in a columnStore index
Upvotes: 2 <issue_comment>username_2: As per [documentation](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-columnstore-index-transact-sql):
>
> Columns that use any of the following data types cannot be included in
> a columnstore index:
>
>
> nvarchar(max), varchar(max), and varbinary(max) (Applies to SQL Server
> 2016 and prior versions, and nonclustered columnstore indexes)
>
>
>
Either change the type of the column (if you can) or just don't have a columnstore index on this specific column.
Upvotes: 5 [selected_answer]<issue_comment>username_3: just specify the length of the varchar variables instead of using max. Did the trick for me!
Upvotes: 0 |
2018/03/19 | 427 | 1,413 | <issue_start>username_0: I would like to read and store a `BMP` file in a `QuadTree`:
An example of the `BMP` file would be:
```
P1
4 4
1 0 1 1
0 1 0 0
1 1 0 0
1 1 0 0
```
and the structure of the `QuadTree` I have thought of is:
```
struct QuadTreeNode{
int size;
struct QuadTreeNode *children[4];
int color; //0 white, 1 black, -1 div
};
```
I am having trouble thinking of a way to build the `QuadTree`. What would a good way be to build the `QuadTree` as the file is read? Should I start with the `leaves` or with the main `QuadTree`?<issue_comment>username_1: You'll need to specify the participating columns individually, excluding memberOf and any other columns that can't be used in a columnStore index
Upvotes: 2 <issue_comment>username_2: As per [documentation](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-columnstore-index-transact-sql):
>
> Columns that use any of the following data types cannot be included in
> a columnstore index:
>
>
> nvarchar(max), varchar(max), and varbinary(max) (Applies to SQL Server
> 2016 and prior versions, and nonclustered columnstore indexes)
>
>
>
Either change the type of the column (if you can) or just don't have a columnstore index on this specific column.
Upvotes: 5 [selected_answer]<issue_comment>username_3: just specify the length of the varchar variables instead of using max. Did the trick for me!
Upvotes: 0 |
2018/03/19 | 1,094 | 3,758 | <issue_start>username_0: I'm trying to get today's date using time function of jmeter with the format "${\_\_time(yyyy-MM-dd)}" in BeanShell postprocessor. But after executing the Beanshell postprocessor the result shows as "1996". Basically the "time" function is displaying result by subtracting the values like "2018-03-19"=1996.
Please help me to resolve this issue so that i can get current date and time.
Beanshell code as below
```
import org.apache.jmeter.gui.GuiPackage;
import org.apache.commons.io.FilenameUtils;
String testPlanFile = GuiPackage.getInstance().getTestPlanFile();
String testPlanFileDir = FilenameUtils.getFullPathNoEndSeparator(testPlanFile);
vars.put("testPlanFileDir", testPlanFileDir);
//create the file in test plan file dir and print current time and Date
FileOutputStream f = new FileOutputStream(testPlanFileDir+"/CurrentDate.txt", true);
PrintStream p = new PrintStream(f);
this.interpreter.setOut(p);
//current date and time;
print("Current date is:"+${__time(yyyy-MM-dd)});
f.close();
```<issue_comment>username_1: You should move to JSR223 postprocessor according to JMeter [Best Practices](http://jmeter.apache.org/usermanual/best-practices.html#bsh_scripting):
>
> Since JMeter 3.1, we advise switching from BeanShell to JSR223 Test Elements
>
>
>
Until then you can fix it by quoting the function call as
```
print("Current date is:"+"${__time(yyyy-MM-dd)})";
```
This fix will treat the function's return value as string.
Currenty it treat it as a numeric substraction: 2018-3-19=1996 and then convert it to string
Upvotes: 0 <issue_comment>username_2: Set time function call as parameter of your PreProcessor (**by the way migrate to JSR223 + Groovy** for performances)
And use it then with variable **Parameters**:
[](https://i.stack.imgur.com/ANLcE.png)
Upvotes: 3 [selected_answer]<issue_comment>username_3: 1. Performance anti-pattern #1: given you use [GuiPackage](https://jmeter.apache.org/api/org/apache/jmeter/gui/GuiPackage.html) class you won't be able to execute your test in [non-GUI mode](http://jmeter.apache.org/usermanual/get-started.html#non_gui), consider migrating to [FileServer](https://jmeter.apache.org/api/org/apache/jmeter/services/FileServer.html) instead
2. Performance anti-pattern #2: using Beanshell is not recommended as in case of high loads it might become the bottleneck. Since [JMeter 3.1 it is recommended to use JSR223 Test Elements](http://jmeter.apache.org/usermanual/best-practices.html#bsh_scripting) [and Groovy language](https://www.blazemeter.com/blog/groovy-new-black) for any form of scripting
3. Performance anti-pattern #3: don't inline [JMeter Variables or Functions](https://jmeter.apache.org/usermanual/functions.html) in script body they break Groovy compiled scripts caching function and might resolve into something which will cause unexpected behaviour (like in your case), compilation failure or even data loss.
So:
* Add [JSR223 PostProcessor](http://jmeter.apache.org/usermanual/component_reference.html#JSR223_PostProcessor) instead of the Beanshell one
* Put the following code into "Script" area:
```
String testPlanDir = org.apache.jmeter.services.FileServer.getFileServer().getBaseDir()
File currentDate = new File(testPlanDir + File.separator + "CurrentDate.txt")
currentDate << new Date().format("yyyy-MM-dd")
```
Upvotes: 0 <issue_comment>username_4: Try this with **JSR223 PostProcessor** and language **Groovy** and put this into script area:
```
def a = new Date().format('yyyy-MM-dd')
new File('Example.txt').withWriter('utf-8') {
writer -> writer.writeLine 'Current date is : ' + a.toString() }
```
(It works on **JMeter 4.0**)
Upvotes: 1 |
2018/03/19 | 397 | 1,465 | <issue_start>username_0: I have created a GCP VM instance, with option `Deploy as Container` pointing to an image in my private GCR(nginx customized).
Also while creating the instance, I had given allow 'https' and 'http' traffic.
Though the application is working fine, on connecting the instance via `ssh` and inspecting docker containers
(`docker ps`)
I see the container ports are not exposed. Wondering how the http/https request are handled by the container here via the instance??<issue_comment>username_1: When you use the deploying containers option in GCE it runs docker with access to the host network.
From the relevant [gcp docs](https://cloud.google.com/compute/docs/containers/deploying-containers) :
>
> Containerized VMs launch containers with the network set to host mode.
> A container shares the host network stack, and all interfaces from the
> host are available to the container.
>
>
>
More detailed info on the different network modes [here](https://docs.docker.com/engine/reference/run/#network-settings).
Upvotes: 4 [selected_answer]<issue_comment>username_2: Other than what @username_1 has told, you should also use PORT number greater than 1000 as auto deployed container images aren't run as root and hence can't access privileged ports.
<https://www.staldal.nu/tech/2007/10/31/why-can-only-root-listen-to-ports-below-1024/>
<https://www.google.co.in/search?q=privileged+ports+linux&oq=privileged+ports+linux>
Upvotes: 0 |
2018/03/19 | 1,358 | 3,613 | <issue_start>username_0: I'm trying to run geodjango application on heroku and i added a build pack to make `gdal` available
<https://github.com/cyberdelia/heroku-geo-buildpack.git>. During push it's says that `gdal` and other geotools successfully installed
```
remote: -----> geos/gdal/proj app detected
remote: Using geos version: 3.6.1
remote: Using gdal version: 2.1.3
remote: Using proj version: 4.9.3
remote: -----> Vendoring geo libraries done
remote: -----> Python app detected
remote: ! The latest version of Python 3 is python-3.6.4 (you are using python-3.6.2, which is unsupported).
remote: ! We recommend upgrading by specifying the latest version (python-3.6.4).
remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes
remote: -----> Installing requirements with pip
remote:
remote: -----> $ python manage.py collectstatic --noinput
remote: 1018 static files copied to '/tmp/build_2e0a13e9519778105269a34/test/staticfiles', 1158 post-processed.
remote:
remote: -----> Discovering process types
remote: Procfile declares types -> web
remote:
remote: -----> Compressing...
remote: Done: 235.8M
remote: -----> Launching...
remote: Released v60
remote: https://test.herokuapp.com deployed to Heroku
remote:
remote: Verifying deploy... done.
```
When i request page it says that application error.
from `heroku logs`
```
2018-03-19T14:25:00.614100+00:00 app[web.1]: from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi
2018-03-19T14:25:00.614103+00:00 app[web.1]: from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal
2018-03-19T14:25:00.614104+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/gis/gdal/libgdal.py", line 43, in
2018-03-19T14:25:00.614106+00:00 app[web.1]: % '", "'.join(lib\_names)
2018-03-19T14:25:00.614813+00:00 app[web.1]: [2018-03-19 14:25:00 +0000] [9] [INFO] Worker exiting (pid: 9)
2018-03-19T14:25:00.746744+00:00 app[web.1]: [2018-03-19 14:25:00 +0000] [4] [INFO] Shutting down: Master
2018-03-19T14:25:00.746839+00:00 app[web.1]: [2018-03-19 14:25:00 +0000] [4] [INFO] Reason: Worker failed to boot.
2018-03-19T14:25:00.614110+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, try setting GDAL\_LIBRARY\_PATH in your settings.>
```
Should i specify some path in settings or may be i'm using incompatible versions? (i'm using `Django==2.0.2`)<issue_comment>username_1: When you use the deploying containers option in GCE it runs docker with access to the host network.
From the relevant [gcp docs](https://cloud.google.com/compute/docs/containers/deploying-containers) :
>
> Containerized VMs launch containers with the network set to host mode.
> A container shares the host network stack, and all interfaces from the
> host are available to the container.
>
>
>
More detailed info on the different network modes [here](https://docs.docker.com/engine/reference/run/#network-settings).
Upvotes: 4 [selected_answer]<issue_comment>username_2: Other than what @username_1 has told, you should also use PORT number greater than 1000 as auto deployed container images aren't run as root and hence can't access privileged ports.
<https://www.staldal.nu/tech/2007/10/31/why-can-only-root-listen-to-ports-below-1024/>
<https://www.google.co.in/search?q=privileged+ports+linux&oq=privileged+ports+linux>
Upvotes: 0 |
2018/03/19 | 2,904 | 8,602 | <issue_start>username_0: Using [parallel-ssh](https://github.com/ParallelSSH/parallel-ssh) module I'm trying to run SSH commands using Natinve Client but getting `SessionHandshakeError`. And if I use Paramiko Client instead, everything works fine. I met the [requirement](http://parallel-ssh.readthedocs.io/en/latest/quickstart.html#native-client) of `my_pkey.pub` being in the same directory as `my_pkey`.
Here is my code which uses Native Client (changed real IPs to `'ip1'` and `'ip2'`):
```
from pssh.pssh2_client import ParallelSSHClient
pkey = os.path.dirname(os.path.abspath(__file__)) + '/my_pkey'
hosts = ['ip1', 'ip2']
client = ParallelSSHClient(hosts, user='root', pkey=pkey)
output = client.run_command('hostname')
for host, host_output in output.items():
for line in host_output.stdout:
print(line)
```
Getting this error:
```
Traceback (most recent call last):
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\ssh2_client.py", line 123, in _init
self.session.handshake(self.sock)
File "ssh2\session.pyx", line 81, in ssh2.session.Session.handshake
ssh2.exceptions.SessionHandshakeError: ('SSH session handshake failed with error code %s', -5)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\ssh2_client.py", line 123, in _init
self.session.handshake(self.sock)
File "ssh2\session.pyx", line 81, in ssh2.session.Session.handshake
ssh2.exceptions.SessionHandshakeError: ('SSH session handshake failed with error code %s', -5)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\ssh2_client.py", line 123, in _init
self.session.handshake(self.sock)
File "ssh2\session.pyx", line 81, in ssh2.session.Session.handshake
ssh2.exceptions.SessionHandshakeError: ('SSH session handshake failed with error code %s', -5)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/NazimokPP/Desktop/AnchorFree/QA-Automation/nodetest/nodetest.py", line 57, in
main(args.server\_domain, args.test\_type)
File "C:/Users/NazimokPP/Desktop/AnchorFree/QA-Automation/nodetest/nodetest.py", line 45, in main
output = client.run\_command('hostname')
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\pssh2\_client.py", line 182, in run\_command
encoding=encoding, use\_pty=use\_pty, timeout=timeout)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\base\_pssh.py", line 91, in run\_command
self.get\_output(cmd, output)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\base\_pssh.py", line 136, in get\_output
(channel, host, stdout, stderr, stdin) = cmd.get()
File "C:\Program Files (x86)\Python36-32\lib\site-packages\gevent\greenlet.py", line 482, in get
self.\_raise\_exception()
File "C:\Program Files (x86)\Python36-32\lib\site-packages\gevent\greenlet.py", line 159, in \_raise\_exception
reraise(\*self.exc\_info)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\gevent\\_compat.py", line 33, in reraise
raise value.with\_traceback(tb)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\gevent\greenlet.py", line 536, in run
result = self.\_run(\*self.args, \*\*self.kwargs)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\pssh2\_client.py", line 188, in \_run\_command
self.\_make\_ssh\_client(host)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\pssh2\_client.py", line 313, in \_make\_ssh\_client
allow\_agent=self.allow\_agent, retry\_delay=self.retry\_delay)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\ssh2\_client.py", line 107, in \_\_init\_\_
THREAD\_POOL.apply(self.\_init)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\gevent\pool.py", line 325, in apply
return self.spawn(func, \*args, \*\*kwds).get()
File "C:\Program Files (x86)\Python36-32\lib\site-packages\gevent\event.py", line 385, in get
return self.get(block=False)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\gevent\event.py", line 375, in get
return self.\_raise\_exception()
File "C:\Program Files (x86)\Python36-32\lib\site-packages\gevent\event.py", line 355, in \_raise\_exception
reraise(\*self.exc\_info)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\gevent\\_compat.py", line 33, in reraise
raise value.with\_traceback(tb)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\gevent\threadpool.py", line 211, in \_worker
value = func(\*args, \*\*kwargs)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\ssh2\_client.py", line 126, in \_init
return self.\_connect\_init\_retry(retries)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\ssh2\_client.py", line 116, in \_connect\_init\_retry
return self.\_init(retries=retries)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\ssh2\_client.py", line 126, in \_init
return self.\_connect\_init\_retry(retries)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\ssh2\_client.py", line 116, in \_connect\_init\_retry
return self.\_init(retries=retries)
File "C:\Program Files (x86)\Python36-32\lib\site-packages\pssh\ssh2\_client.py", line 128, in \_init
raise SessionError(msg, self.host, self.port, ex)
pssh.exceptions.SessionError: ('Error connecting to host %s:%s - %s', 'ip1', 22, SessionHandshakeError('SSH session handshake failed with error code %s', -5))
Process finished with exit code 1
```
Here is my code which uses Paramiko Client (changed real IPs to 'ip1' and 'ip2'):
```
from pssh.pssh_client import ParallelSSHClient
from pssh.utils import load_private_key
key_path = os.path.dirname(os.path.abspath(__file__)) + '/my_pkey'
pkey = load_private_key(key_path)
hosts = ['ip1', 'ip2']
client = ParallelSSHClient(hosts, user='root', pkey=pkey)
output = client.run_command('hostname')
for host, host_output in output.items():
for line in host_output.stdout:
print(line)
```
And it works. Here's the output (should I care about warnings?):
```
C:\Program Files (x86)\Python36-32\lib\site-packages\paramiko\ecdsakey.py:202: CryptographyDeprecationWarning: signer and verifier have been deprecated. Please use sign and verify instead.
signature, ec.ECDSA(self.ecdsa_curve.hash_object())
C:\Program Files (x86)\Python36-32\lib\site-packages\paramiko\rsakey.py:110: CryptographyDeprecationWarning: signer and verifier have been deprecated. Please use sign and verify instead.
algorithm=hashes.SHA1(),
ip1.hostname
ip2.hostname
Process finished with exit code 0
```
What am I doing wrong with Native Client?<issue_comment>username_1: Some explanations which I got from Panos in Google Groups thread. It didn't help me, but maybe it will be helpful for somebody else.
>
> A `-5` error is defined as a key exchange error in libssh2. It sounds
> like the key type is not supported by libssh2 and paramiko shows
> 'ecdsakey.py' being used. ECDSA keys are not currently supported by
> libssh2 (PR pending).
>
>
> The warning are from paramiko itself, can't say if they matter.
>
>
> Better exceptions for native client errors are being worked on for
> next release.
>
>
>
\_
>
> So for a private key 'my\_pkey', there should be a 'my\_pkey.pub' in
> same directory.
>
>
> It may also be a case of the SSH server's key not being supported by
> the native client (same limitations as user keys) which would explain
> the key exchange error. Can check the type of key configured for the
> server in /etc/ssh/sshd\_config, `HostKey` entry. There should be at
> least one non-ECDSA key configured, eg:
>
>
> HostKey /etc/ssh/ssh\_host\_rsa\_key HostKey /etc/ssh/ssh\_host\_dsa\_key
> HostKey /etc/ssh/ssh\_host\_ecdsa\_key
>
>
> If there is only a ECDSA key entry, the native client will not be able
> to connect.
>
>
>
Upvotes: 0 <issue_comment>username_2: This error was tracked down to the WinCNG back-end used for `libssh2` on Windows - it does not support SHA-256 host key hashes which is now the default in recent versions of OpenSSH server.
The [latest version](https://pypi.org/project/parallel-ssh/) of `parallel-ssh`, `1.6.0`, fixes this issue by switching the Windows back-end to OpenSSL for better compatibility and to match the OSX and Linux binary wheels.
See [release notes](https://github.com/ParallelSSH/parallel-ssh/releases/tag/1.6.0) for more details.
Upvotes: 2 [selected_answer] |
2018/03/19 | 1,800 | 8,027 | <issue_start>username_0: I'm trying to learn how to use bound services. Whenever I click the Start/Pause button I would like for the timer to change as desired. However, clicking these buttons will kill the program. I'm not sure why this TextView object is giving a NullPointerException error in my service class. Could someone please help me with this?
```
public class LocalService extends Service {
//Binder
private final IBinder mBinder = new LocalBinder();
Button btnStart,btnPause,btnLap;
TextView txtTimer;
Handler customHandler = new Handler();
LinearLayout container;
long startTime=0L,timeInMilliseconds=0L,timeSwapBuff=0L,updateTime=0L;
public class LocalBinder extends Binder {
LocalService getService() {
//Return this instance of LocalService so public methods can be called
return LocalService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
Runnable updateTimerThread = new Runnable() {
@Override
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis()-startTime;
updateTime = timeSwapBuff+timeInMilliseconds;
int secs=(int)(updateTime/1000);
int mins=secs/60;
secs%=60;
int milliseconds=(int)(updateTime%1000);
txtTimer.setText(""+mins+":"+String.format("%02d",secs)+":"
+String.format("%03d",milliseconds));
customHandler.postDelayed(this,0);
}
};
}
```
This object has already been initialized in my Main class here:
```
public class MainActivity extends AppCompatActivity {
LocalService mService = new LocalService();
boolean mBound = false;
Button btnStart, btnPause, btnLap;
TextView txtTimer;
LinearLayout container;
Handler customHandler = new Handler();
long startTime=0L,timeInMilliseconds=0L,timeSwapBuff=0L,updateTime=0L;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button)findViewById(R.id.btnStart);
btnPause = (Button)findViewById(R.id.btnPause);
btnLap = (Button)findViewById(R.id.btnLap);
txtTimer = (TextView)findViewById(R.id.timerValue);
container = (LinearLayout)findViewById(R.id.container);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(mService.updateTimerThread,0);
}
});
btnPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
timeSwapBuff=+timeInMilliseconds;
customHandler.removeCallbacks(mService.updateTimerThread);
}
});
btnLap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View addView = inflater.inflate(R.layout.row,(ViewGroup)null);
TextView txtValue = (TextView)addView.findViewById(R.id.textContent);
txtValue.setText(txtTimer.getText());
container.addView(addView);
}
});
}
@Override
protected void onStart() {
super.onStart();
//Bind to LocalService
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
unbindService(mConnection);
mBound = false;
}
//Define callbacks for service binding, passed to bindService()
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName mainActivity, IBinder service) {
//We've bound to LocalService, cast the IBinder and get LocalService instance
LocalService.LocalBinder binder = (LocalService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
}
```
When this service is running I would like for the txtTimer in my main activity to be updated with the bound service values. I'm getting a NullPointer error code taking me to LocalService class around line 56:
```
txtTimer.setText(""+mins+":"+String.format("%02d",secs)+":"
+String.format("%03d",milliseconds));
```
Whats the best way to update this so that txtTimer is able to show the changing value? I would really appreciate some help<issue_comment>username_1: Define this constuctor on `LocalService` class :
```
public LocalService(TextView textView){
txtTimer = textView;
super();
}
```
and add this line before `btnStart.setOnClickListener(new View ...` :
```
mService = new LocalService(txtTimer);
```
Hope it will help
Upvotes: 3 [selected_answer]<issue_comment>username_2: The problem is that your `txtTimer` object is never initialized in your service. Modifying UI elements from a service is tricky, and best not actually done directly from the service itself.
Generally, the solution to this is to implement a `BroadcastReceiver`. You'll simply send whatever data you want (in this case, a string) to your activity, which will then act upon receiving that data.
First, in your service, you create an `Intent` object, in which you'll put a `Bundle` with whatever data you want to send to the activity:
```
Runnable updateTimerThread = new Runnable() {
@Override
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis()-startTime;
updateTime = timeSwapBuff+timeInMilliseconds;
int secs=(int)(updateTime/1000);
int mins=secs/60;
secs%=60;
int milliseconds=(int)(updateTime%1000);
// Get the data to send
String string = ""+mins+":"+String.format("%02d",secs)+":"
+String.format("%03d",milliseconds);
Intent intent = new Intent("MainActivityListener");
Bundle bundle = new Bundle();
bundle.putString("txtTimerString", string);
intent.putExtras(bundle);
// Send broadcast
getApplicationContext().sendBroadcast(intent);
customHandler.postDelayed(this,0);
}
};
```
Then in your activity, you'll need to create your `BroadcastReciever`, which will receive the string you want from the service and set your TextView accordingly:
```
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String txtTimerString = extras.getString("txtTimerString");
if (txtTimerString != null) {
txtTimer.setText(txtTimerString);
}
}
}
};
```
And then finally, you'll need to register the `BroadcastReciever` in the `onResume` method of the activity:
```
@Override
public void onResume() {
super.onResume();
getApplicationContext().registerReceiver(mMessageReceiver,
new IntentFilter("MainActivityListener"));
}
```
This is a lot safer than trying to find a way to pass the TextView directly into the service, since the service can run independently of the activity. If the service were to try to modify the TextView and the activity isn't currently running, you'd likely crash. This way, the service simply puts out a broadcast - and if the activity isn't running, it doesn't matter.
Upvotes: 1 |
2018/03/19 | 663 | 2,506 | <issue_start>username_0: Trying to upload a large Acumatica company snapshot file (1.3 GB) and I am getting an error as soon as I hit the upload button.
**What setting (if any) can I change in my local Acumatica site or web.config to allow the large file import?**
As a work around I am requesting a snapshot file without file attachments as the file attachments data is about 95% of the snapshot file size.
My file upload preferences are currently set to 25000 KB if that helps any. (I assume this setting is not used for snapshot imports.)
The error occurs after I select the file and click ok (before being able to click the upload button). I am using 2017R2 Update 4.
Image of error:
[](https://i.stack.imgur.com/AaaIa.png)<issue_comment>username_1: Modifying your web.config might work, but I think Sergey Marenich alternative is better. He did an excellent post on his blog on how to do this.
<http://asiablog.acumatica.com/2017/12/restore-large-snapshot.html>
The idea is :
1. Get a snapshot of your site in xml
2. Extract and put the folder in C:\Program Files (x86)\Acumatica ERP\Database\Data
3. Use the Configuration Wizard to deploy a site and select your snapshot data, just like you would when choosing demo data.
Upvotes: 3 [selected_answer]<issue_comment>username_2: If your on SaaS then you may request a copy of database and be able to restore the database for offsite instance.
If your on PCS/PCP then you have couple of options you could modify the Web.config to allow bigger files to process as detailed in this blog <https://acumaticaclouderp.blogspot.com/2017/12/acumatica-snapshots-uploading-and.html>
If you have larger files then you can't do it coz of IIS constraint and you can certainly use Sergey's method but that would be creating for new instance only or simple approach is to take a SQL .bak file and restore to new database.
I think Acumatica shld provide a mechanism to split these large files and have them processed into multiple uploads to accomplish but again very few customers might face this issue too.
Upvotes: 1 <issue_comment>username_3: I had this same problem. I tried to modify the web.config but, that gave me an error that said that the file didn't exist or I didn't have permissions when I tried to import the snapshot file into Acumatica again.
Turns out, I had a table that has image blobs stored inside of it so, it wouldn't compress. Watch out for that one.
Upvotes: 1 |
2018/03/19 | 1,217 | 3,770 | <issue_start>username_0: I have two divs:
1. top div contains a long text that takes up several lines
2. lower div has `min-height` and `flex-grow: 1`
When I reducing the window to the scroll appeared, then in chrome everything is displayed correctly. But in IE11 top div is reduced to one line, and its text is on top of the bottom div.
I can fix it only with set some width for content of top div (it work with fixed width, or calc width, but not work with percentage width)
How can I fix it without setting width or with percentage width (`width:100%`)?
```css
body,
html {
height: 99%;
padding: 0;
margin: 0;
}
.flexcontainer {
width: 25%;
display: flex;
flex-direction: column;
height: 100%;
border: 1px solid lime;
}
.allspace {
flex-grow: 1;
min-height: 300px;
background-color: yellow;
}
.longtext {
background-color: red;
}
.textcontainer {
border: 1px solid magenta;
/*IE work correctly only when specified width. by example: width:calc(25vw - 2px);*/
}
```
```html
section 1 with long name section 1 with long name section 1 with long name
all space
```
jsfiddle: <https://jsfiddle.net/tkuu28gs/14/>
Chrome:
[](https://i.stack.imgur.com/4ydOT.png)
IE11:
[](https://i.stack.imgur.com/caEqf.png)<issue_comment>username_1: problem solved:
```
body, html {
height: 100vh;
padding:0;
margin:0;
}
.flexcontainer{
width:25%;
display: flex;
height: 100%;
flex-flow: column;
border: 1px solid lime;
}
.allspace{
flex-grow:1;
background-color: yellow;
}
.longtext{
background-color: red;
//EDIT
flex-grow: 0;
min-height: 100px;
}
.textcontainer{
border:1px solid magenta;
/*IE work correctly only when specified width. by example: width:calc(25vw - 2px);*/
}
```
**EDIT (screenshots on IE11)**
[](https://i.stack.imgur.com/1Wpfh.png)
[](https://i.stack.imgur.com/WdfoY.png)
Upvotes: -1 <issue_comment>username_2: IE11 is full of flex bugs and inconsistencies with other browsers.
In this case, the source of the problem is `flex-shrink`.
IE11 is rendering flex items oddly after applying `flex-shrink: 1` (a default setting), which causes the lower item to overlap its sibling above. This problem doesn't occur in other major browsers.
The solution is to disable `flex-shrink`. It fixes the problem in IE11 without changing anything in other browsers.
Add this to your code:
```
.longtext {
flex-shrink: 0;
}
```
[**revised fiddle**](https://jsfiddle.net/tkuu28gs/16/)
---
You may also want to look into:
* setting `min-width: auto` on flex items, as IE11 has a different minimum size default than newer browsers. See the "Browser Rendering Notes" section in my answer here: [Why don't flex items shrink past content size?](https://stackoverflow.com/q/36247140/3597276)
* setting the container to `width: 100%`, as IE11 may not do this automatically to block-level flex containers. [Text in a flex container doesn't wrap in IE11](https://stackoverflow.com/q/35111090/3597276)
Upvotes: 6 [selected_answer]<issue_comment>username_3: The use of `flex-shrink: 0;` mentioned in the accepted answer works to prevent overlapping. However, I'm using like `flex: 0 1 15%` as I intend to allow shrinking and this renders nicely in other browsers like MS Edge, Chrome, and Firefox, but not in IE 11.
To apply no shrinking (`flex-shrink: 0`) only for IE 11, I used the following instead as the `-ms-` is vendor-specific:
```
-ms-flex-negative: 0 !important;
```
Upvotes: 1 |
2018/03/19 | 287 | 1,102 | <issue_start>username_0: For embedding Vimeo videos on the web, I just need to set up my Vimeo video to allow embedding for a specific URL (eg. www.myapp.com) and then it works. When I try to view the same video in a React Native app with a web view I get a `NSUrlErrorDomain` exception.
I've gone through the Vimeo documentation and can't find the answer. Is it possible to do this? Or do I need to make my videos public for it to work?<issue_comment>username_1: Domain privacy for Vimeo embeds requires the HTTP referer to be passed back to the iframe so the Player can determine if the domain where its embedded can play back the video. If you're on a local page without an HTTP referer, then the domain privacy feature will not work.
You'll need to set the video's embed privacy to "Embed anywhere", or use direct video file links (as a PRO or Business member) with the platform's native media player. More info here: <https://help.vimeo.com/hc/en-us/articles/224823567-Third-party-player-links>
Upvotes: 0 <issue_comment>username_2: Domain privacy is on and just like that;
```
```
Upvotes: 2 |
2018/03/19 | 336 | 946 | <issue_start>username_0: I would like check whether we can't rewrite `map (f.g.h) x` with `$` without parentheses as I didn't find a way.
Here are my trials:
```
map (f.g.h) x
-> map (f.g.h) $ x -- OK, no benefit
-> map $ f.g.h $ x -- wrong as map doesn't take one parameter
-> (map $ f.g.h) x -- Ok, no benefit, ugly :-)
```
Only elegant option I found was to use
```
negate . sum . tail <$> [[1..5], [3..6]]]
```
but I would like to be sure that I didn't skip some options above.
Thank you<issue_comment>username_1: If you define the function
```
map (f.g.h) x
```
You thus process *each* element of `x` with `f . g . h`, this means that we first apply `h` on it, then `g` on the result, and finally `f` on that result.
But we can also work with three separate `map`s, like:
```
map f $ map g $ map h x
```
Upvotes: 3 <issue_comment>username_2: how about?
```
let u = f.g.h in map u x
```
no parenthesis, no `$`
Upvotes: 3 |
2018/03/19 | 1,311 | 5,209 | <issue_start>username_0: It seems protractor doesn't provide any out of the box solution for starting a server before it runs. Having to run multiple commands before functional tests will run is a bad user experience and bad for automated testing.
Angular-cli has its own solution that is rather complicated, which this plugin claims to duplicate, although it doesn't work for me and may be unmaintained. <https://www.npmjs.com/package/protractor-webpack>
EDIT: BETTER SOLUTION ACCEPTED BELOW
I came up with a solution using child\_process.exec that seems to work well, although I don't like it very much. I'd like to share it in case anyone needs it and to see if anyone can come up with a better solution.
Launch the process in the beforeLaunch hook of protractor:
```
beforeLaunch: () => {
webpackServerProcess = exec(`webpack-dev-server --port=3003 --open=false`, null, () => {
console.log(`Webpack Server process reports that it exited. Its possible a server was already running on port ${port}`)
});
},
```
Then above the configuration block we set up the exit handlers to make positively sure that server gets killed when we are done.
```
let webpackServerProcess; // Set below in beforeLaunch hook
function cleanUpServer(eventType) {
console.log(`Server Cleanup caught ${eventType}, killing server`);
if (webpackServerProcess) {
webpackServerProcess.kill();
console.log(`SERVER KILLED`);
}
}
[`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`].forEach((eventType) => {
process.on(eventType, cleanUpServer.bind(null, eventType));
})
```
The various event listeners are needed to handle cntrl+c events and situations where the process is killed by ID. Strange that node does not provide an event to encompass all of these.<issue_comment>username_1: Protractor also has `onCleanUp` that will run after all the specs in the file have finished.
And you are doing the right thing by keeping a reference to your process so that you can kill it later.
```
let webpackServerProcess;
beforeLaunch: () {
webpackServerProcess = exec('blah'); // you could use spawn instead of exec
},
onCleanUp: () {
process.kill(webpackServerProcess.pid);
// or webpackServerProcess.exit();
}
```
Since you are launching the serverProcess with child\_process.exec, and not in a detached state, it should go away if the main process is killed with SIGINT or anything else. So you might not even have to kill it or cleanup.
Upvotes: 1 <issue_comment>username_2: I found a much more reliable way to do it using the webpack-dev-server node api. That way no separate process is spawned and we don't have to clean anything. Also, it blocks protractor until webpack is ready.
```
beforeLaunch: () => {
return new Promise((resolve, reject) => {
new WebpackDevServer(webpack(require('./webpack.config.js')()), {
// Do stuff
}).listen(APP_PORT, '0.0.0.0', function(err) {
console.log('webpack dev server error is ', err)
resolve()
}).on('error', (error) => {
console.log('dev server error ', error)
reject(error)
})
})
},
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: ```
// conf.js
var jasmineReporters = require('jasmine-reporters');
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
const path = require('path');
const WebpackDevServer = require('webpack-dev-server');
const webpack = require('webpack');
let webpackServerProcess;
beforeLaunch: () => {
return new Promise(resolve => {
setTimeout(() => {
const compiler = webpack(require('./webpack.config.js'));
const server = new WebpackDevServer(compiler, {
stats: 'errors-only'
});
server.listen(0, 'localhost', () => {
// `server.listeningApp` will be returned by `server.listen()`
// in `webpack-dev-server@~2.0.0`
const address = server.listeningApp.address();
config.baseUrl = `http://localhost:${address.port}`;
resolve();
});
}, 5000);
});
};
exports.config = {
framework: 'jasmine',
//seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['Test/spec.js'],
directConnect: true,
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'/*,
chromeOptions: {
args: [ '--headless','--log-level=1', '--disable-gpu', '--no-sandbox', '--window-size=1920x1200' ]
}*/
},
onPrepare: function() {
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
filePrefix: 'guitest-xmloutput',
savePath: 'reports'
}));
jasmine.getEnv().addReporter(new Jasmine2HtmlReporter({
savePath: 'reports/',
screenshotsFolder: 'images',
takeScreenshots: true,
takeScreenshotsOnlyOnFailures: true,
cleanDestination: false,
fileName: 'TestReport'
}));
},
}
onCleanUp: ()=> {
//process.kill(webpackServerProcess.pid);
webpackServerProcess.exit();
}
```
Upvotes: 0 |
2018/03/19 | 1,660 | 4,847 | <issue_start>username_0: How to solve the below mentioned cmake error while installing the face\_recognition library?
```
Collecting face_recognition
Using cached face_recognition-1.2.1-py2.py3-none-any.whl
Requirement already satisfied: face-recognition-models>=0.3.0 in ./anaconda/lib/python3.6/site-packages (from face_recognition)
Requirement already satisfied: Pillow in ./anaconda/lib/python3.6/site-packages (from face_recognition)
Requirement already satisfied: Click>=6.0 in ./anaconda/lib/python3.6/site-packages (from face_recognition)
Requirement already satisfied: scipy>=0.17.0 in ./anaconda/lib/python3.6/site-packages (from face_recognition)
Collecting dlib>=19.7 (from face_recognition)
Using cached dlib-19.10.0.tar.gz
Requirement already satisfied: numpy in ./anaconda/lib/python3.6/site-packages (from face_recognition)
Requirement already satisfied: olefile in ./anaconda/lib/python3.6/site-packages (from Pillow->face_recognition)
Building wheels for collected packages: dlib
Running setup.py bdist_wheel for dlib ... error
Complete output from command /Users/muralidharan/anaconda/bin/python -u -c "import setuptools, tokenize;__file__='/<KEY>pip-build-5zqyoigf/dlib/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /<KEY>pip-wheel- --python-tag cp36:
running bdist_wheel
running build
running build_py
package init file 'dlib/__init__.py' not found (or not a regular file)
running build_ext
Invoking CMake setup: 'cmake /<KEY>pip-build-5zqyoigf/dlib/tools/python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=/<KEY>dlib/build/lib.macosx-10.7-x86_64-3.6 -DPYTHON_EXECUTABLE=/Users/muralidharan/anaconda/bin/python -DCMAKE_BUILD_TYPE=Release'
error: [Errno 2] No such file or directory: 'cmake'
----------------------------------------
Failed building wheel for dlib
Running setup.py clean for dlib
Failed to build dlib
Installing collected packages: dlib, face-recognition
Running setup.py install for dlib ... error
Complete output from command /Users/muralidharan/anaconda/bin/python -u -c "import setuptools, tokenize;__file__='/<KEY>pip-build-5zqyoigf/dlib/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/<KEY>/pip-qhc3clwr-record/install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
package init file 'dlib/__init__.py' not found (or not a regular file)
running build_ext
Invoking CMake setup: 'cmake /<KEY>pip-build-5zqyoigf/dlib/tools/python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=/<KEY>pip-<KEY>/dlib/build/lib.macosx-10.7-x86_64-3.6 -DPYTHON_EXECUTABLE=/Users/muralidharan/anaconda/bin/python -DCMAKE_BUILD_TYPE=Release'
error: [Errno 2] No such file or directory: 'cmake'
----------------------------------------
Command "/Users/muralidharan/anaconda/bin/python -u -c "import setuptools, tokenize;__file__='/private/<KEY>pip-build-5zqyoigf/dlib/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/<KEY>pip-qhc3clwr-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/<KEY>/pip-build-5zqyoigf/dlib/
```<issue_comment>username_1: As to me, I install face\_recognition in ubuntu16 python2.7, I write a shell to install it.
```
#!/bin/bash
# This shell script install face_recognition in ubuntu16 python2.7
apt-get -y install git
apt-get -y install cmake
# install dlib without cuda
git clone https://github.com/davisking/dlib.git
cd dlib
mkdir build; cd build; cmake .. ; cmake --build .
# install dlib python interface
cd -
apt-get -y install python-setuptools
apt-get -y install python-dev
python setup.py install
# install face_recognition
apt-get -y install python-pip
pip install face_recognition
```
Upvotes: 1 <issue_comment>username_2: ```
error: [Errno 2] No such file or directory: 'cmake'
```
I ran into the same problem recently, I resolved it downloading CMAKE.
[Here is the link to download it for each OS](https://cmake.org/download/)
Upvotes: 0 |
2018/03/19 | 1,026 | 3,470 | <issue_start>username_0: I want to integrate ckfinder with my laravel but I am stuck with authentication.
I found many ways but there were for older laravel versions and none are working for 5.6.
I found this:
```
require '../../vendor/autoload.php';
$app = require_once '../../bootstrap/app.php';
$app->make('Illuminate\Contracts\Http\Kernel')
->handle(Illuminate\Http\Request::capture());
```
But I am getting Invalid request from Ckfinder when I put it in config.php
I would like to access Auth::check() and return it in authentication
```
require __DIR__ . '/../../vendor/autoload.php';
$app = require_once __DIR__ . '/../../bootstrap/app.php';
$request = Illuminate\Http\Request::capture();
$request->setMethod('GET');
$app->make('Illuminate\Contracts\Http\Kernel')
->handle($request);
$config['authentication'] = function () {
return auth()->check();
};
```
**EDIT**
So I had a look at index.php and copied this into config.php:
```
define('LARAVEL_START', microtime(true));
require '/Applications/MAMP/htdocs/laravel-dealer/vendor/autoload.php';
$app = require_once '/Applications/MAMP/htdocs/laravel-dealer/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
```
But I am getting runtime exceptions for $acl argument.
>
> Fatal error: Uncaught RuntimeException: Controller
> "CKSource\CKFinder\Command\Init::execute()" requires that you provide
> a value for the "$acl" argument. Either the argument is nullable and
> no null value has been provided, no default value has been provided or
> because there is a non optional argument after this one. in
> /Applications/MAMP/htdocs/laravel-dealer/vendor/symfony/http-kernel/Controller/ArgumentResolver.php:78
> Stack trace: #0
> /Applications/MAMP/htdocs/laravel-dealer/vendor/symfony/http-kernel/HttpKernel.php(141):
> Symfony\Component\HttpKernel\Controller\ArgumentResolver->getArguments(Object(Symfony\Component\HttpFoundation\Request),
> Array) #1
> /Applications/MAMP/htdocs/laravel-dealer/vendor/symfony/http-kernel/HttpKernel.php(66):
> Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request),
> 1) #2
> /Applications/MAMP/htdocs/laravel-dealer/public/ckfinder/core/connector/php/vendor/cksource/ckfinder/src/CKSource/CKFinder/CKFinder.php(610):
> Symfony\Component\HttpKernel\HttpKernel- in
> /Applications/MAMP/htdocs/laravel-dealer/vendor/symfony/http-kernel/Controller/ArgumentResolver.php
> on line 78
>
>
>
Thanks for any help<issue_comment>username_1: As to me, I install face\_recognition in ubuntu16 python2.7, I write a shell to install it.
```
#!/bin/bash
# This shell script install face_recognition in ubuntu16 python2.7
apt-get -y install git
apt-get -y install cmake
# install dlib without cuda
git clone https://github.com/davisking/dlib.git
cd dlib
mkdir build; cd build; cmake .. ; cmake --build .
# install dlib python interface
cd -
apt-get -y install python-setuptools
apt-get -y install python-dev
python setup.py install
# install face_recognition
apt-get -y install python-pip
pip install face_recognition
```
Upvotes: 1 <issue_comment>username_2: ```
error: [Errno 2] No such file or directory: 'cmake'
```
I ran into the same problem recently, I resolved it downloading CMAKE.
[Here is the link to download it for each OS](https://cmake.org/download/)
Upvotes: 0 |
2018/03/19 | 776 | 2,180 | <issue_start>username_0: Good morning, I have a head the end of the week with an error in the project that I'm doing for the study of springboot + angular + jpa.
At the time of doing a service management class, I used it according to the tutorial of an extended class of class JpaRepository.
But a project error that I can not solve.
Follow the pom.xml and some images of the project, if anyone can help I thank you!
```
xml version="1.0" encoding="UTF-8"?
4.0.0
marco.prova
apiweb
0.0.1-SNAPSHOT
war
apiweb
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.0.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.data
spring-data-jpa
2.0.5.RELEASE
org.springframework.boot
spring-boot-starter-tomcat
provided
org.springframework.boot
spring-boot-starter-test
test
org.springframework.data
spring-data-jpa
org.springframework.boot
spring-boot-maven-plugin
```
Project images in STS.
<https://uploaddeimagens.com.br/imagens/1-png-6e078f12-f26b-4266-8030-520f0f0fe7d1>
<https://uploaddeimagens.com.br/imagens/2-png-2224373b-2cec-46dc-b986-e68876ef57db>
<https://uploaddeimagens.com.br/imagens/3-png-740ac73d-5bd4-4f45-9394-c2717d4a9423>
<https://uploaddeimagens.com.br/imagens/4-png-9202635e-5a30-4f58-a862-70d3e9034ec6>
I'm waiting! Thank you!<issue_comment>username_1: >
> the type
> org.springframework.data.repository.query.QueryByExampleExecutor
> cannot be resolved. It is indirectly referenced from required .class
> files
>
>
>
You need to download [Spring data commons jar](https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons/2.0.5.RELEASE) and keep it in your classpath.
Or add the following dependency in your POM:
```
org.springframework.data
spring-data-commons
2.0.5.RELEASE
```
Upvotes: 3 <issue_comment>username_2: Or You can try to delete org.springframework.data folder from C:\Users\User\.m2 folder and update Maven project
Upvotes: 5 [selected_answer]<issue_comment>username_3: You should use the `spring-boot-starter-data-jpa` starter instead:
```
org.springframework.boot
spring-boot-starter-data-jpa
```
Upvotes: 1 |
2018/03/19 | 287 | 1,250 | <issue_start>username_0: I have two buttons. How to show the visual effect of clicking both buttons, actually pressing only one of them?<issue_comment>username_1: If you only want only the animation effect you can try this :
```
buttonLeft = findViewById(R.id.left);
buttonRight = findViewById(R.id.right);
buttonLeft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonRight.setPressed(true);
buttonRight.setPressed(false);
}
});
}
```
It's working, but maybe there's a better way to this,
Hope it will help
Upvotes: 0 <issue_comment>username_2: If you want to show effects on button press and button release, you can use this code.
```
button1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
button2.setPressed(true);
break;
case MotionEvent.ACTION_UP:
button2.setPressed(false);
break;
}
return false;
}
});
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 2,061 | 7,063 | <issue_start>username_0: How do I change the string representation of an object instance in nodejs debug console. Is there a method (like `toString()` in .NET) I can override?
[](https://i.stack.imgur.com/KkLOV.png)
Consider the following code:
```
class SomeObject{
constructor(){
this._varA = "some text";
this._varB = 12345;
this._varC = "some more text";
this._varD = true;
this._varE = 0.45;
}
toString(){
return "custom textual rapresentation of my object";
}
}
var array = [];
array.push(new SomeObject());
array.push(new SomeObject());
array.push(new SomeObject());
console.log(array);
```
This produces the following:
[](https://i.stack.imgur.com/obIn9.png)
However in other environments and programming languages I have worked on, overriding the `toString()` method would show the result of `toString()` (in the example above `"custom textual representation of my object"`) instead of the dynamic textual representation created by the debugger (in the example code above this is: `SomeObject {_varA: "some text", _varB: 12345, _varC: "some more text", …}`) - which I don't doubt for one minute it is very useful when a custom alternative is not defined.
I also realise that `console.log(array.toString());` or even `console.log(array.map(t=>t.toString()));` will produce something similar to what I am after, however this then prevents me to navigate through the objects using the debug navigation ie. drill into the object graph.
If this is not possible, would others benefit from this? If there is enough interest, I can look into defining and implementing it as a feature.<issue_comment>username_1: There is a toString() method that you call on another string.
`terms[200]._text.toString()`
You may also be looking for `JSON.stringify()` which I find extremely useful in debugging. Since JavaScript objects are literally JSON, this will make printing them out to the console simpler.
`console.log(JSON.stringify(terms[200]))`
Upvotes: -1 <issue_comment>username_2: When you do `console.log` it internally calls `formatValue` in `util.js`, which has a below check
```
const maybeCustomInspect = value[customInspectSymbol] || value.inspect;
```
Which means if your value has a `inspect` method it gets called and then you can return the `toString` in the same. So change your code to
```
class SomeObject{
constructor(){
this._varA = "some text";
this._varB = 12345;
this._varC = "some more text";
this._varD = true;
this._varE = 0.45;
}
inspect(depth, opts) {
return this.toString();
}
toString(){
return "custom textual rapresentation of my object";
}
}
var array = [];
array.push(new SomeObject());
array.push(new SomeObject());
array.push(new SomeObject());
console.log(array);
```
Makes it print
```
[ custom textual rapresentation of my object,
custom textual rapresentation of my object,
custom textual rapresentation of my object ]
```
Nodejs has documentation on the same too
<https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_custom_inspection_functions_on_objects>
The `inspect` method I used is deprecated as per documentation and the correct way to do it is below
```
const util = require('util');
class SomeObject{
constructor(){
this._varA = "some text";
this._varB = 12345;
this._varC = "some more text";
this._varD = true;
this._varE = 0.45;
}
[util.inspect.custom](depth, options) {
return this.toString();
}
toString(){
return "custom textual rapresentation of my object";
}
}
var array = [];
array.push(new SomeObject());
array.push(new SomeObject());
array.push(new SomeObject());
console.log(array);
```
**Edit: 28th-Mar-2018**
So I launched the script using below
```
$ node --inspect-brk=54223 test.js
Debugger listening on ws://127.0.0.1:54223/81094440-716b-42a5-895e-4ea2008e0dff
For help see https://nodejs.org/en/docs/inspector
```
And then ran a `socat` forwarder using below
```
$ socat -v TCP-LISTEN:54222,fork TCP:127.0.0.1:54223
```
When you debug the variable `array` in debugger, you get below output on the `socat` terminal
[](https://i.stack.imgur.com/EYR9R.jpg)
The information is that reconstructed by debugger to give you a meaningful representation.
Now the `v8` debug api has no idea that we want to represent it differently, like we did for `console.log`. Now there may be something similar in `V8` code that does something similar, but looking at the source code, I was not able to figure out there exists such a thing. So you may need to confirm from someone who has V8 debugger api knowledge, if something of this sort exists
If not the you need to construct something at the IDE level, which again is not a a easy thing to do
Upvotes: 4 <issue_comment>username_3: My two cents:
How about overriding the console.log function to do what you want to.
Here is the POC which needs a \_toString function in any object to change the way it appears in the log.
create a file logger.js with the following content:
```
const getUpdatedLogObj = function(x){
if(x && typeof x == 'object'){
if(typeof x._toString === 'function'){
return x._toString()
} else {
for(let i in x){
x[i] = getUpdatedLogObj(x[i])
}
}
}
return x;
}
console._log = console.log
console.log = function(x){console._log(getUpdatedLogObj({...x}))}
```
import it in index.js
```
require('./logger')
console.log({a: 1, b: 2, c: {d: 5, e: 6, _toString: function(){return 'fromToString'}}})
```
And you still get the navigaion:
[](https://i.stack.imgur.com/kNkNL.png)
Upvotes: 0 <issue_comment>username_4: ```
const util = require('util');
class SomeObject{
constructor(){
this._varA = "some text";
this._varB = 12345;
this._varC = "some more text";
this._varD = true;
this._varE = 0.45;
}
[util.inspect.custom](depth, options) {
return this.toString();
}
toString(){
return "custom textual rapresentation of my object";
}
}
var array = [];
array.push(new SomeObject());
array.push(new SomeObject());
array.push(new SomeObject());
console.log(array);
```
Upvotes: -1 <issue_comment>username_5: There has been a new option added to VS Code to enable tweaking the debugger output: simply add the below to your launch configuration
```
"customDescriptionGenerator": "function (def) { if (this.toString) { const _v = this.toString(); if (_v.indexOf(\"[object Object]\") < 0) return _v; } return def; }",
```
Viola: your entities viewed with "toString" in watch, retaining the ability to drill down etc.
Upvotes: 3 [selected_answer] |
2018/03/19 | 774 | 2,755 | <issue_start>username_0: I am making a system and I came across the following doubt .. I have two being the first to select the brand of the vehicle and the second would be to select the model of the vehicle. but I would like to select the brand of the vehicle and the of the model to load the models of the vehicles for the selected brand.
i have onde archive .json with brand and models of cars.
exemple format json
```
"value":"ACURA","title":"Acura","models":[{"value":"CL_MODELS","title":"CL Models (4)"}]}
```
so I populate the first with the tags so the second would be populated with the models referring to the selected brand.
I need it when I select, for example BMW, the second select only the models referring to BMW, and not all models.
How do you do this?
thanks :)<issue_comment>username_1: ```js
//YOUR_JSON_DATA
//{"value":"ACURA","title":"Acura","models":[{"value":"CL_MODELS","title":"CL Models (4)"}]}
$.get( YOUR_JSON_DATA, function( data ) {
// Did you want data to be an array of brands?
for (let brand of data) {
$("#brand").append(`${ brand.value }`)
for (let models of brand.models) {
$("#models").append(` ${ models.value } `)
}
}
});
```
```html
```
Here is an example code snippet for ya. I hope it provides some clarity. Did you want the JSON data be an array?
Upvotes: 0 <issue_comment>username_2: I don't know enough about how the data is being fetched, but I believe you're asking about manipulating it in a way that makes it usable by the 2 selects. Take a look at the example below:
```js
var json = [{
"value": "ACURA",
"title": "Acura",
"models": [{
"value": "CL_MODELS",
"title": "CL Models (4)"
}]
},
{
"value": "TOYOTA",
"title": "Toyota",
"models": [{
"value": "TOYOTA_MODELS",
"title": "Toyota Models (4)"
}]
}
];
$(document).ready(function() {
$('#models').prop('disabled', true);
$('#brand')
.append($("")
.attr("value", "")
.text(""));
$.each(json, function(index) {
$('#brand')
.append($("")
.attr("value", json[index]["value"])
.text(json[index]["title"]));
});
$('#brand').change(function() {
process($(this).children(":selected").html());
});
});
function process(brand) {
$('#models').prop('disabled', false).find('option')
.remove()
.end();
var models = $.map(json, function(entry) {
if (entry["title"] === brand) {
return entry["models"];
}
});
$.each(models, function(index) {
$('#models')
.append($("")
.attr("value", models[index]["value"])
.text(models[index]["title"]));
});
};
```
```html
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 649 | 1,960 | <issue_start>username_0: Is there a method to make the first delimiter in an observation different to the rest? In Microsoft SQL Server Integration Services (SSIS), there is an option to set the delimiter per column. I wonder if there is a similar way to achieve this in SAS with an amendment to the below code, whereby the first delimiter would be tab instead and the rest pipe:
```
proc export
dbms=csv
data=mydata.dataset1
outfile="E:\OutPutFile_%sysfunc(putn("&sysdate9"d,yymmdd10.)).txt"
replace
label;
delimiter='|';
run;
```
For example
From:
```
var1|var2|var3|var4
```
to
```
var1 var2|var3|var4
```
...Where the large space between var1 and var2 is a tab.
Many thanks in advance.<issue_comment>username_1: Sounds like you just want to make a new variable that has the first two variables combined and then write that out using tab delimiter.
```
data fix ;
length new1 $50 ;
set have ;
new1=catx('09'x,var1,var2);
drop var1 var2 ;
run;
proc export data=fix ... delimiter='|' ...
```
Note that you can reference a variable in the `DLM=` option on the `FILE` statement in a data step.
```
data _null_;
dlm='09'x ;
file 'outfile.txt' dsd dlm=dlm ;
set have ;
put var1 @ ;
dlm='|' ;
put var2-var4 ;
run;
```
Or you could use the `catx()` trick in a `data _null` step. You also might want to use `vvalue()` function to insure formats are applied.
```
data _null_;
length newvar $200;
file 'outfile.txt' dsd dlm='|' ;
set have ;
newvar = catx('09'x,vvalue(var1),vvalue(var2));
put newvar var3-var4 ;
run;
```
**Updated** Fixed order of delimiters to match question.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Final code based on the marked answer by username_1:
```
data _null_;
dlm='09'x ;
file "E:\outputfile_%sysfunc(putn("&sysdate9"d,yymmdd10.)).txt" dsd dlm=dlm ;
set work.have;
put
var1 @ ;
dlm='|';
put var2 var3 var4;
run;
```
Upvotes: 0 |
2018/03/19 | 537 | 1,713 | <issue_start>username_0: if I have a jquery namespace like so:
```
var sc = {
calcResult: function(){
//do stuff
},
initialise: function () {
$('#myid').click(function(){
//would like to call calcResult() here
}
}
```
How do I call calcResult from within the initialise function? I tried `this.calcResult()` and `sc.calcResult()` but both complain with undefined error.<issue_comment>username_1: Sounds like you just want to make a new variable that has the first two variables combined and then write that out using tab delimiter.
```
data fix ;
length new1 $50 ;
set have ;
new1=catx('09'x,var1,var2);
drop var1 var2 ;
run;
proc export data=fix ... delimiter='|' ...
```
Note that you can reference a variable in the `DLM=` option on the `FILE` statement in a data step.
```
data _null_;
dlm='09'x ;
file 'outfile.txt' dsd dlm=dlm ;
set have ;
put var1 @ ;
dlm='|' ;
put var2-var4 ;
run;
```
Or you could use the `catx()` trick in a `data _null` step. You also might want to use `vvalue()` function to insure formats are applied.
```
data _null_;
length newvar $200;
file 'outfile.txt' dsd dlm='|' ;
set have ;
newvar = catx('09'x,vvalue(var1),vvalue(var2));
put newvar var3-var4 ;
run;
```
**Updated** Fixed order of delimiters to match question.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Final code based on the marked answer by username_1:
```
data _null_;
dlm='09'x ;
file "E:\outputfile_%sysfunc(putn("&sysdate9"d,yymmdd10.)).txt" dsd dlm=dlm ;
set work.have;
put
var1 @ ;
dlm='|';
put var2 var3 var4;
run;
```
Upvotes: 0 |
2018/03/19 | 743 | 2,924 | <issue_start>username_0: I am getting this error, I am new in react. I have seen other posts but still could not resolve the issue. help will be appreciated. thanks
>
> Warning: A component is changing an uncontrolled input of type email to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info
> in input (created by Edit)
> in div (created by Edit)
> in div (created by Edit)
> in form (created by Edit)
> in div (created by Edit)
> in Edit
>
>
>
```
import React from 'react'
import ReactDom from 'react-dom'
export default class Edit extends React.Component{
constructor(){
super();
this.state={
name: '',
email: '',
password: '',
};
}
componentWillMount(){
let id=this.props.id;
axios.get('/api/users/'+id).then(response => {
var user= response.data;
this.setState({
name: user.name,
email: user.email,
})
}).catch(error => {
console.log(error)
})
}
handleNameChange(e){
this.setState({
name: e.target.value
})
}
handleEmailChange(e){
this.setState({
email: e.target.value
})
}
handlePasswordChange(e){
this.setState({
password: e.target.value
})
}
handleSubmit(e){
e.preventDefault();
console.log(this.state)
axios.post('/api/users',this.state).then(response => {
console.log(response)
}).then(error => {
console.log(error)
})
}
render(){
return(
Add New User
-------------
Name:
Email:
Password:
Update
)
}
}
if (document.getElementById('edit')) {
var id=$("#edit").data("id");
ReactDom.render(, document.getElementById('edit'))
}
```<issue_comment>username_1: The error is occuring because when you're doing `setState` inside componentDidMount, the value returned seems to be `undefined`.
```
if(user.name!==undefined && user.email!==undefined){
this.setState({
name: user.name,
email: undefined,
})
}
```
This will prevent the values in the state from becoming undefined and you won't have that error anymore.
Upvotes: 2 <issue_comment>username_2: You are using value attribute to set default value while rendering, it makes your input controlled input, then when updating your states you are trying to change your input values again which will make it uncontrolled one. basically for your code to succeed you need to use defaultValue attribute in your rendered code instead of value attr. because when you are setting value to input from html it can't be later changed.
do this instead for your input elements:
```
```
here is a source from react docs on issue:
<https://reactjs.org/docs/uncontrolled-components.html>
Upvotes: 2 |
2018/03/19 | 2,125 | 6,010 | <issue_start>username_0: Im working on a transpiler in python right now and one function of my code is to find certain symbols and to place spaces around them so theyre easier to parse later.
This is the code that initially places to the spaces around the chars
```
def InsertSpaces(string):
to_return = list(string)
for i, char in enumerate(to_return):
if char == '?' or char == '#' or char == '@':
to_return[i] = (to_return[i] + ' ')[::-1]
to_return[i] += ' '
print(''.join(to_return))
```
Although this worked, it created an annoying problem
It created spaces right after the newlines, which could cause problems later on and is just ugly.
So this:
```
'@0x0D?0A\n@0x1f?@0x2f?48#65#6C#6C#6F#2C#20#57#6F#72#6C#64#21'
```
Becomes this:
```
' @ 0x0D ? 0A
@ 0x1f ? @ 0x2f ? 48 # 65 # 6C # 6C # 6F # 2C # 20 # 57 # 6F # 72 # 6C # 64 # 21'
```
(Keep in mind this splits up the string into a list)
So I wrote this to detect newlines inside the list in which I would remove the spaces afterwards.
```
for char in to_return:
char_next = to_return[to_return.index(char) + 1]
if (char + char_next) == '':
print('found a newline')
```
The issue is that it does not detect any newlines.
Printing the pairs of characters you can see the newline character but it cant be found by the code since it turns into a newline which is not readable by a simple string I believe.
```
@ 0
0x
x0
0x
D ?
? 0
0x
A
@
@ 0
0x
x0
1f
f ?
? 0
@ 0
0x
x0
2f
f ?
? 0
48
8 #
# 6
65
5 #
# 6
65
C #
# 6
65
C #
# 6
65
F #
# 6
2f
C #
# 6
2f
0x
# 6
5 #
7 #
# 6
65
F #
# 6
7 #
2f
# 6
65
C #
# 6
65
48
# 6
2f
1f
```
Is there a way to detect a newline character while iterating through a list of strings?<issue_comment>username_1: Iterate over both the current char and the next and use `'\n'`:
```
for char, char_next in zip(to_return, to_return[1:]):
if char + char_next == '\n ':
print('found a newline')
```
Upvotes: 1 <issue_comment>username_2: First off, this is kind of a strange line of code:
```
to_return[i] = (to_return[i] + ' ')[::-1]
```
`to_return[i]` is one character long, so this line is equivalent to:
```
to_return[i] = ' ' + to_return[i]
```
Second of all, if you're just trying to pad all the '?', '#', and '@' with spaces, why not try a simple replace:
```
def InsertSpaces(string):
return string.replace("?"," ? ").replace("#", " # ").replace("@", " @ ")
```
or even shorter if you use the `re` (regex) module:
```
def InsertSpace(string):
return re.sub("(#|\?|@)",r" \1 ", string)
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Here's a way to modify your function to solve your problem without regex.
In each iteration check to see if the previous or next characters are new lines. In those cases, do not add a space:
```
def InsertSpaces(s):
to_return = []
for i, char in enumerate(s):
if char in {'?', '#', '@'}:
val = ' ' if ((i-1) > 0) and s[i-1] != '\n' else ''
val += char
val += ' ' if ((i+1) < len(s)) and s[i+1] != '\n' else ''
else:
val = char
to_return.append(val)
return ''.join(to_return)
s = '@0x0D?0A\n@0x1f?@0x2f?48#65#6C#6C#6F#2C#20#57#6F#72#6C#'
print(repr(InsertSpaces(s)))
#'@ 0x0D ? 0A\n@ 0x1f ? @ 0x2f ? 48 # 65 # 6C # 6C # 6F # 2C # 20 # 57 # 6F # 72 # 6C #'
```
The key is this part:
```
val = ' ' if ((i-1) > 0) and s[i-1] != '\n' else '' #1
val += char #2
val += ' ' if ((i+1) < len(s)) and s[i+1] != '\n' else '' #3
```
* Line 1: Add either `' '` or `''` to the beginning of the string based on the conditional. We check to see if the previous char `s[i-1]` is not a newline character `\n`. We also have to check that the index is inbounds (`(i-1) > 0`)
* Line 2: Always add the current `char`
* Line 3: Similar logic as Line 1, but check the next character and make sure you're not at the end of the string.
This will also **not** add a space after the special character if it is at the end of the string (or at the start). If you want that to happen, you'd have to slightly modify the conditional.
A couple of other changes that I made:
* Renamed the input variable `s` because `string` is the name of a class
* Initialized `to_return` to an empty list which will be appended to and `enumerate(s)` (instead of `to_return`) because bad things can happen when you modify the object over which you are iterating
* Using `in {set}` instead of checking for all characters individually
Upvotes: 1 <issue_comment>username_4: You don't have to "scan" for a newline, as long as you only add a space when there is a character which is not a space, either before or after, your current character.
I don't think it can be done with a single regular expression, but with two you can add just spaces where needed. It needs *two* lookbehinds/lookaheads, because there are two conditions:
1. There must be at least one character before/after the `@`, `#`, or `?`;
2. It must not be a newline.
I added a third condition for consistency:
3. .. this character must not be a space.
so there won't be a space added when there already is one. (It's only a convenience addition, because `\S` happens to match "everything that is not space-like".)
Why do you need two lookbehinds? Because one of them will match if there is a character (which must not be a space-like) and another will match if there is "not" a newline, which includes start and end of the string itself.
The following code, with a slightly altered input string to show off that it works at edge cases,
```
import re
str = '@0x0D?0A\n@0x1f?@0x2f?48# 65#6C#6C#6F#2C#20#57#6F#72#6C#64#21@'
str = re.sub(r'(?<=\S)(?
```
results in
```
"@ 0x0D ? 0A
@ 0x1f ? @ 0x2f ? 48 # 65 # 6C # 6C # 6F # 2C # 20 # 57 # 6F # 72 # 6C # 64 # 21 @"
```
where the double quotes are only added to show begin and end of the result string.
Upvotes: 1 |
2018/03/19 | 503 | 1,802 | <issue_start>username_0: I tried to integrate an existing table to my extension. The problem is that the content of the table isn't taken over.
I created a new model with the name of the existing table and named the properties according to the existing column names. I also implemented the corresponding getters and setters of the properties.
[Extension](https://i.stack.imgur.com/wQVlD.png)
The name of the existing table is `tx_institutsseminarverwaltung_domain_model_event`.<issue_comment>username_1: How are you trying to "consume" or access the data from the other table in your extension?
Do you have a repository for the existing table (maybe there is already an existing repository, that you can reuse)?
See [german typo3 board mapping existing tables](https://www.typo3.net/forum/thematik/zeige/thema/118413/seite/2/) and [SO thread TYPO3 / How to make repository from existing table fe\_users?](https://stackoverflow.com/questions/18254124/typo3-how-to-make-repository-from-existing-table-fe-users)
This question is most likely a duplicate of [this question](https://stackoverflow.com/questions/49380221/typo3-accessing-an-existing-table-to-consume-data-of-it)
Upvotes: 1 <issue_comment>username_2: The solution for this issues is:
First get the Typo3 query settings
```
$querySettings = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Typo3QuerySettings');
```
Set RespectStoragePage to false
```
$querySettings->setRespectStoragePage(FALSE);
```
Fetch your repository
```
$theRepository = $this->objectManager->get('TYPO3\\institutsseminarverwaltung\\Domain\\Repository\\EventRepository');
```
And set the query settings to your repository.
```
$theRepository->setDefaultQuerySettings($querySettings);
```
Upvotes: 1 [selected_answer] |
2018/03/19 | 603 | 1,758 | <issue_start>username_0: I am trying to enter a value in a cell based on the results in 2 different cells. if cell 1 is blank then refer to cell 2, based on what's in cell 2 return X value.
If cell 1 is NOT blank, based on what's in cell 1 return X value.
here is what I have so far, so far everything that looks in cell 1 returns a FALSE.
```
=IF(ISBLANK(E8),IF(D8="401K Employer Match","Match",IF(D8="401K Percentage","4K",IF(D8="ROTH 401K %","4R",IF(D8="Life Employee","LIE",IF(D8="Life Spouse","LIS",IF(D8="Life Child(ren)","LIC",IF(D8="Life Employer","LE",IF(D8="Life Employer X 2","LE2",IF(D8="Short Term Disabilty Base Pay","STDB",IF(D8="Short Term Disability Gross Wages","STDG",IF(D8="Short Term Disability Over 60K","STDB",IF(D8="Long Term Disability Base Salary","LTDB",IF(D8="Long Term Disability Gross Wages","LTDG",IF(D8="Long Term Disability Over 60K","D")))))))))))))),If(E8="Reliance Dental","DE"))
```<issue_comment>username_1: When you are trying to put 3+ nested ifs, it is a good idea to use a LookUp Table. Like this:
[](https://i.stack.imgur.com/MfzEV.png)
Then you simply look for the value in column `A` and return the value in Column `B`. And you save yourself all the problems that a long Excel formula causes.
This is how a formula looks like:
```
"=INDEX(A2:B4,MATCH(D2,A2:A4,0),2)"
```
Just put it somewhere and make sure that you change `D2` correspondingly:
[](https://i.stack.imgur.com/zztuY.png)
Upvotes: 2 [selected_answer]<issue_comment>username_2: Also consider using IFS() statements.
=IFS(*condition*, then do XYZ, *different condition*, then do ABC, etc.)
Upvotes: 0 |
2018/03/19 | 986 | 4,121 | <issue_start>username_0: I am looking into django middleware codebase. I looked into following diagram[](https://i.stack.imgur.com/iKDL1.png)
So, the diagram is quite clear.
But I have some questions
1. What happens when exception comes in process\_request() middleware ? How is it handled ? Will the response\_middleware be invoked ? Eg. if exception comes in `process_view()` of `AuthenticationMiddleware`, then will `process_response()` of `MessageMiddleware` be invoked ?
2. What happens when in process\_response() middleware returns response? Eg. if `process_view()` of `AuthenticationMiddleware` returns respones, then will `process_response()` of `MessageMiddleware` be invoked ? OR it'll turn back from `AuthenticationMiddleware`(ie, it'll invoke `process_response()` of `AuthenticationMiddleware`, but will not invoke `process_response()` of `MessageMiddleware`)
I have debugged the behaviour of django in 1.10 where new style middleware classes are used, but I am not familiar about old `MIDDLEWARE_CLASSES` settings ?
For django 1.10:-
1) If `process_request()` for `AuthenticationMiddleware` returns response, then `process_template_response()` and `process_response()` will be invoked as show in the figure given below for all the middlewares.
2) If `process_request()` for `AuthenticationMiddleware` raises exception, then also the behavior will be the same.
Correct me, If I am wrong.
Thanks in Advance.<issue_comment>username_1: For 2), you are right. Function `convert_exception_to_response()` will catch the exceptions which `process_request()` raises.
See the source:
<https://github.com/django/django/blob/master/django/core/handlers/base.py>
<https://github.com/django/django/blob/master/django/core/handlers/exception.py>
Upvotes: 0 <issue_comment>username_2: [The official documentation](https://docs.djangoproject.com/en/dev/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware) could answer your first question if you work on django project before the version 1.10.
please read the paragraph : behavioral differences between using MIDDLEWARE and MIDDLEWARE\_CLASSES
>
> Under MIDDLEWARE\_CLASSES, every middleware will always have its process\_response method called, even if an earlier middleware short-circuited by returning a response from its process\_request method. Under MIDDLEWARE, middleware behaves more like an onion: the layers that a response goes through on the way out are the same layers that saw the request on the way in. If a middleware short-circuits, only that middleware and the ones before it in MIDDLEWARE will see the response.
>
>
>
However `MIDDLEWARE_CLASSES` has been removed since django v1.10, and new style of middleware workflow (using `__call__()` instead) has been introduced since then, this allows each middleware (applied in `MIDDLEWARE`) to internally determine whether to short-circuit by returning response back (with error status) and not invoking subsequent middlewares and view middleware on exception handling, in such case, the diagram in the question may not be always the case, especially if your project includes custom middlewares.
[side note], a middleware with short-circuiting on exception may look like this :
```py
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
try:
# Code to be executed for each request before
# the view (and later middleware) are called.
do_something_but_raise_exception()
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
except WHATEVER_EXCEPTION as e:
# short-circuiting, because self.get_response() is not invoked,
response = generate_custom_response(e)
return response
```
[Side note]:
For what it's worth , middlewares in FastAPI are also structured in similar way.
Upvotes: 1 |
2018/03/19 | 677 | 2,804 | <issue_start>username_0: just a question, is a good idea to host machines with HyperV on a DC?
This is my Idea.
if the answer is no, can you explain why?
Thanks
Have a nice day<issue_comment>username_1: For 2), you are right. Function `convert_exception_to_response()` will catch the exceptions which `process_request()` raises.
See the source:
<https://github.com/django/django/blob/master/django/core/handlers/base.py>
<https://github.com/django/django/blob/master/django/core/handlers/exception.py>
Upvotes: 0 <issue_comment>username_2: [The official documentation](https://docs.djangoproject.com/en/dev/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware) could answer your first question if you work on django project before the version 1.10.
please read the paragraph : behavioral differences between using MIDDLEWARE and MIDDLEWARE\_CLASSES
>
> Under MIDDLEWARE\_CLASSES, every middleware will always have its process\_response method called, even if an earlier middleware short-circuited by returning a response from its process\_request method. Under MIDDLEWARE, middleware behaves more like an onion: the layers that a response goes through on the way out are the same layers that saw the request on the way in. If a middleware short-circuits, only that middleware and the ones before it in MIDDLEWARE will see the response.
>
>
>
However `MIDDLEWARE_CLASSES` has been removed since django v1.10, and new style of middleware workflow (using `__call__()` instead) has been introduced since then, this allows each middleware (applied in `MIDDLEWARE`) to internally determine whether to short-circuit by returning response back (with error status) and not invoking subsequent middlewares and view middleware on exception handling, in such case, the diagram in the question may not be always the case, especially if your project includes custom middlewares.
[side note], a middleware with short-circuiting on exception may look like this :
```py
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
try:
# Code to be executed for each request before
# the view (and later middleware) are called.
do_something_but_raise_exception()
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
except WHATEVER_EXCEPTION as e:
# short-circuiting, because self.get_response() is not invoked,
response = generate_custom_response(e)
return response
```
[Side note]:
For what it's worth , middlewares in FastAPI are also structured in similar way.
Upvotes: 1 |
2018/03/19 | 261 | 910 | <issue_start>username_0: I am sending mail through my emailer and in my email i am sending an image with the background hyperlink, the email showing normal but in system configured outlook showing the link of URL of the hyperlink.
Please visit below mention URL
<https://prnt.sc/itb5wq>
I am trying to hide URL using placing span or p tag before hyperlink.
**Source code:**
```
Text Something
```<issue_comment>username_1: Your approach was not that bad, here's the correct syntax for a HTML hyperlink:
```html
[I am a link and you can't see my destination!](https://www.google.com)
```
Or in your case:
```html
[Text Something](#)
```
Upvotes: 0 <issue_comment>username_2: Put your span in your hyperlink ...
```
[Please Visit](#)
```
Upvotes: 0 <issue_comment>username_3: I tried this code and worked for me perfectly:
```
Text Here
[](#)
```
Upvotes: 1 |
2018/03/19 | 807 | 3,151 | <issue_start>username_0: I am currently working on a C# project using v4.6.2 and Visual Studio just suggested a code change to the code below.
My question is, I have never seen the `is` keyword used to create a new variable instance in this manner.
The original code was:
```
var authInfo = inputs.FirstOrDefault(i =>
typeof(SoapAuthenticationBase).IsAssignableFrom(i.GetType()));
if (authInfo is SoapAuthenticationBase)
```
Visual Studio 2017 suggested this:
```
if (inputs.FirstOrDefault(i =>
typeof(SoapAuthBase).IsAssignableFrom(i.GetType()))
is SoapAuthBase authenticationContract)
```
I checked Microsoft's documentation on the ['is' keyword](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is) and found nothing that explained this syntax.
What version of C# was 'is' added in this way?<issue_comment>username_1: While the suggestion is creating a new variable, it is scoped to the `if` (i.e. much narrower).
```
var authInfo = inputs.FirstOrDefault(i =>
typeof(SoapAuthenticationBase).IsAssignableFrom(i.GetType()));
if (authInfo is SoapAuthenticationBase){
// authInfo exists
}
// authInfo exists
```
It's basically suggesting you drop the existing `authInfo` instance you're declaring.
```
if (inputs.FirstOrDefault(i =>
typeof(SoapAuthBase).IsAssignableFrom(i.GetType()))
is SoapAuthBase authenticationContract){
// authenticationContract exists
}
// authenticationContract does not exist
```
Upvotes: 1 <issue_comment>username_2: In your first snipper, the `is` keyword checks whether the thing on the left is an instance of the type on the right. `is` returns a boolean, the `FirstOrDefault` call is returning either null or an instance of `SoapAuthenticationBase` which is being assigned to your variable.
As @Ashley Medway pointed out, the second code snippet is actually an example of C# pattern matching. `authenticationContract` is an instance of `SoapAuthBase` that will only have a value if the thing on the left is an instance of it. If not, the entire statement will return false.
That said, personally i find your original code more readable. I would be inclined to ignore VS, and let the compiler sort it all out later.
Upvotes: 2 <issue_comment>username_3: This feature is called *pattern matching* and it was introduced in the c# language in version 7. In your example its not very clear, but consider the following canonical example of `Equals` overriding:
```
public override bool Equals(obj other)
{
if (obj is Foo)
{
return Equals((Foo)obj);
}
return false;
}
```
This is essentially wasteful because you are checking the type twice: once to see if its in fact a `Foo`, and then again when performing the cast. It seems unnecessarily verbose.
Pattern matching allows a much more concise syntax:
```
public override bool Equals(obj other)
{
if (obj is Foo foo)
{
return Equals(foo);
}
return false;
}
```
You can read more on this feature [here](https://blogs.msdn.microsoft.com/seteplia/2017/10/16/dissecting-the-pattern-matching-in-c-7/).
Upvotes: 5 [selected_answer] |
2018/03/19 | 934 | 3,466 | <issue_start>username_0: I write a dog-classifier in a Jupyter notebook that, every time a dog is detected in an image, should show the image and print some text describing it. Somehow, the images are always displayed after all the text was printed, no matter in which order I put `plt.imshow()` and `print()`. Does anybody know why this is the case?
Thank you!
Here is my code-snippet:
```
for i in range (0, 1,1):
all_counter+=1
if dog_detector(dog_files_short[i]):
img = image.load_img(dog_files_short[i], target_size=(224, 224))
plt.show()
plt.imshow(img)
time.sleep(5)
print("That's a dog!!!!")
dog_counter+=1
print("______________")
else:
print("______________")
img = image.load_img(dog_files_short[i], target_size=(224, 224))
plt.show()
plt.imshow(img)
print("No Doggo up here :(")
print(ResNet50_predict_labels(dog_files_short[i]))
print("______________")
print((dog_counter/all_counter)*100, "% of the dog pictures are classified as dogs")
```
The output is like this:
<issue_comment>username_1: While the suggestion is creating a new variable, it is scoped to the `if` (i.e. much narrower).
```
var authInfo = inputs.FirstOrDefault(i =>
typeof(SoapAuthenticationBase).IsAssignableFrom(i.GetType()));
if (authInfo is SoapAuthenticationBase){
// authInfo exists
}
// authInfo exists
```
It's basically suggesting you drop the existing `authInfo` instance you're declaring.
```
if (inputs.FirstOrDefault(i =>
typeof(SoapAuthBase).IsAssignableFrom(i.GetType()))
is SoapAuthBase authenticationContract){
// authenticationContract exists
}
// authenticationContract does not exist
```
Upvotes: 1 <issue_comment>username_2: In your first snipper, the `is` keyword checks whether the thing on the left is an instance of the type on the right. `is` returns a boolean, the `FirstOrDefault` call is returning either null or an instance of `SoapAuthenticationBase` which is being assigned to your variable.
As @Ashley Medway pointed out, the second code snippet is actually an example of C# pattern matching. `authenticationContract` is an instance of `SoapAuthBase` that will only have a value if the thing on the left is an instance of it. If not, the entire statement will return false.
That said, personally i find your original code more readable. I would be inclined to ignore VS, and let the compiler sort it all out later.
Upvotes: 2 <issue_comment>username_3: This feature is called *pattern matching* and it was introduced in the c# language in version 7. In your example its not very clear, but consider the following canonical example of `Equals` overriding:
```
public override bool Equals(obj other)
{
if (obj is Foo)
{
return Equals((Foo)obj);
}
return false;
}
```
This is essentially wasteful because you are checking the type twice: once to see if its in fact a `Foo`, and then again when performing the cast. It seems unnecessarily verbose.
Pattern matching allows a much more concise syntax:
```
public override bool Equals(obj other)
{
if (obj is Foo foo)
{
return Equals(foo);
}
return false;
}
```
You can read more on this feature [here](https://blogs.msdn.microsoft.com/seteplia/2017/10/16/dissecting-the-pattern-matching-in-c-7/).
Upvotes: 5 [selected_answer] |
2018/03/19 | 713 | 2,806 | <issue_start>username_0: I have to make request with only one parameter for example:
>
> example.com/confirm/{unique-id-value}
>
>
>
I don't expect to get any data in body, only interested in Response Code.
Need advice which method to use GET or POST
GET i think is also OK because, making request with pathparam, but on the other hand POST is also right to use, because i don't expect to receive any data from body, just making informative request and interested in only status code of request result.<issue_comment>username_1: While the suggestion is creating a new variable, it is scoped to the `if` (i.e. much narrower).
```
var authInfo = inputs.FirstOrDefault(i =>
typeof(SoapAuthenticationBase).IsAssignableFrom(i.GetType()));
if (authInfo is SoapAuthenticationBase){
// authInfo exists
}
// authInfo exists
```
It's basically suggesting you drop the existing `authInfo` instance you're declaring.
```
if (inputs.FirstOrDefault(i =>
typeof(SoapAuthBase).IsAssignableFrom(i.GetType()))
is SoapAuthBase authenticationContract){
// authenticationContract exists
}
// authenticationContract does not exist
```
Upvotes: 1 <issue_comment>username_2: In your first snipper, the `is` keyword checks whether the thing on the left is an instance of the type on the right. `is` returns a boolean, the `FirstOrDefault` call is returning either null or an instance of `SoapAuthenticationBase` which is being assigned to your variable.
As @Ashley Medway pointed out, the second code snippet is actually an example of C# pattern matching. `authenticationContract` is an instance of `SoapAuthBase` that will only have a value if the thing on the left is an instance of it. If not, the entire statement will return false.
That said, personally i find your original code more readable. I would be inclined to ignore VS, and let the compiler sort it all out later.
Upvotes: 2 <issue_comment>username_3: This feature is called *pattern matching* and it was introduced in the c# language in version 7. In your example its not very clear, but consider the following canonical example of `Equals` overriding:
```
public override bool Equals(obj other)
{
if (obj is Foo)
{
return Equals((Foo)obj);
}
return false;
}
```
This is essentially wasteful because you are checking the type twice: once to see if its in fact a `Foo`, and then again when performing the cast. It seems unnecessarily verbose.
Pattern matching allows a much more concise syntax:
```
public override bool Equals(obj other)
{
if (obj is Foo foo)
{
return Equals(foo);
}
return false;
}
```
You can read more on this feature [here](https://blogs.msdn.microsoft.com/seteplia/2017/10/16/dissecting-the-pattern-matching-in-c-7/).
Upvotes: 5 [selected_answer] |
2018/03/19 | 582 | 2,158 | <issue_start>username_0: In the Grafana documentation, I found that I should be able to query my Prometheus server for all instances delivering monitoring data using the `label_values` query.
The query I'm using in Grafana is:
```
label_values(up, instance)
```
Unfortunately, Prometheus tells me that it is not aware of label\_values:
```sh
Error executing query: parse error at char 13: unknown function with name "label_values"
```
I am using Prometheus 2.0.0 and Grafana 5.
What am I doing wrong?<issue_comment>username_1: `label_values()` is only a valid function within [templating](https://grafana.com/docs/grafana/latest/features/datasources/prometheus/#templating). You can use it to populate a template dropdown with e.g. a list of available instances or available metrics but you can't use it within a dashboard or when querying Prometheus directly.
Upvotes: 5 <issue_comment>username_2: By looking into Grafana's template code for Prometheus in [grafana/public/app/plugins/datasource/prometheus/metric\_find\_query.ts](https://github.com/grafana/grafana/blob/ce8df91cc9574eec9c7e6f12e5cc4bb6322e20dc/public/app/plugins/datasource/prometheus/metric_find_query.ts) you can see that they do not use PromQL, but visit certain endponts to the get the label values, so for `label_values(instance)` the URL would be something like this:
```
http://localhost:9090/api/v1/label/instance/values
```
This one however returns all labels called `instance` from every metric in the TSDB. If the label is unique for one particular metric, then you have your answer. Otherwise the template code for something like `label_values(up, instance)` it is slightly more complicated and it seems like it actually downloads the whole series for the metric from:
```
http://localhost:9090/api/v1/series?match[]=up
```
also adding time range parameters `start` and `end` which I omitted for clarity, then finds the label values by parsing the JSON output.
I would also like to do the same in PromQL, but I have not figured out whether it is possible or not.
Upvotes: 4 <issue_comment>username_3: `labels(pg_up,instances)` this is correct syntax
Upvotes: -1 |
2018/03/19 | 670 | 2,523 | <issue_start>username_0: I am trying to create editable listview dynamically. Need to display array of string as source. when we are clicking on the item it should be editable.
Problem: No errors but no items are displaying.
```
Style tableStyle = _resourceDictionary["TableStyle"] as Style;
ItemsPanelTemplate itemsPanelTemplate = _resourceDictionary["ItemsPanelTemplate"] as ItemsPanelTemplate;
FrameworkElementFactory factoryPanel = new FrameworkElementFactory(typeof(UniformGrid));
factoryPanel.SetValue(UniformGrid.ColumnsProperty, 5);
ItemsPanelTemplate template = new ItemsPanelTemplate();
template.VisualTree = factoryPanel;
ListView simpleTable = new ListView();
// simpleTable.Columns.Add(new DataGridTextColumn { Header = "Values" });
simpleTable.Style = tableStyle;
simpleTable.ItemsPanel = template;
_table = simpleTable;
string aa = "aa,xx,cc,vv,bbb,hh,gg,rr,tt,yy,uu,ooo";
_table.ItemsSource = aa.ToString().Split(',');
```
Xaml
```
<Setter Property="Background" Value="{StaticResource ControlBackgroundBrush}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListView}">
<ListView>
<ListView.View>
<GridView >
<GridViewColumn Header="Databases" Width="498">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding .}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</ControlTemplate>
</Setter.Value>
</Setter>
```<issue_comment>username_1: I think the datatype you are using is wrong
If you want your list can have a edit function you should use the observableCollection in this case
Upvotes: -1 <issue_comment>username_2: If you want to be able to edit data in a tabular grid you should use the [DataGrid](https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/datagrid) control. It is basically an editable `GridView`.
Create a class that represents a row:
```
public class Item
{
public string Value { get; set; }
}
```
And set the `ItemsSource` property of the `DataGrid` to a collection of such objects:
```
string aa = "aa,xx,cc,vv,bbb,hh,gg,rr,tt,yy,uu,ooo";
_table.ItemsSource = aa.Split(',').Select(x => new Item() { Value = x });
```
**XAML:**
```
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: You are creating another `ListView` inside the `ControlTemplate` of the first one and that's what creates the confusion:
```
```
Upvotes: 1 |
2018/03/19 | 420 | 1,392 | <issue_start>username_0: How do I modify this snippet. Right now it is working good and if $thisorthat = "1" it executes a function for all the ones labelled 1, If I change it to "2" it executes a function for all labelled 2. How do I say 1 AND 2, or 1, 2, and 4, etc. What is the proper format for that?
```
foreach ($values as $v) {
$thisorthat = $v[$thisorthatKey];
if ($thisorthat = "1") {
continue;
}
```<issue_comment>username_1: I think the datatype you are using is wrong
If you want your list can have a edit function you should use the observableCollection in this case
Upvotes: -1 <issue_comment>username_2: If you want to be able to edit data in a tabular grid you should use the [DataGrid](https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/datagrid) control. It is basically an editable `GridView`.
Create a class that represents a row:
```
public class Item
{
public string Value { get; set; }
}
```
And set the `ItemsSource` property of the `DataGrid` to a collection of such objects:
```
string aa = "aa,xx,cc,vv,bbb,hh,gg,rr,tt,yy,uu,ooo";
_table.ItemsSource = aa.Split(',').Select(x => new Item() { Value = x });
```
**XAML:**
```
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: You are creating another `ListView` inside the `ControlTemplate` of the first one and that's what creates the confusion:
```
```
Upvotes: 1 |
2018/03/19 | 686 | 2,071 | <issue_start>username_0: I am using angular material in an angular 2 project.
I want to put a static image (html element) in the selected value of mat-select.
But i didn't find a solution.
Can someone help me?<issue_comment>username_1: By simply adding `![]()` tag inside . For the selected option use `ngClass` to set the image as background. You must use one class by option:
**HTML**
```
None
Option 1

Option 2

Option 3
```
**CSS:**
```
.option1{
background: url("https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg") center / contain no-repeat;
white-space: nowrap
}
.option2{
background: url("https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg") center / contain no-repeat;
white-space: nowrap;
display:inline
}
```
**[DEMO](https://stackblitz.com/edit/angular-ydugqt?file=src/app/select-overview-example.ts)**
Upvotes: 5 [selected_answer]<issue_comment>username_2: 
when it comes to this or similar situation, I did it that:
```
```
of course, inside tags and ` can be any tags as well img, and they work !!
Upvotes: 5 <issue_comment>username_3: I recommend putting a within the and/or elements, then binding html to it after the fashion precribed by [this answer](https://stackoverflow.com/a/58741354/507721).
```html
```
Upvotes: 0 <issue_comment>username_4: [](https://i.stack.imgur.com/uHq2N.png)
Use Mat Select Trigger check: <https://material.angular.io/components/select/api#MatSelectTrigger>
```
....

{{fromControl.value}}

...
```
Upvotes: 0 |
2018/03/19 | 747 | 2,362 | <issue_start>username_0: I want to performance test a web application. My scenario is to take the metrics for multiple users (say 10) with cache. So i have added HTTP cache manager, but cache work per individual users. Is there any way to cache the files once and use it for 'n' number of users in jmeter. Even i tried to put cache manager outside thread group but it dint work.
It should work like cache the files once and use the cache for all the threads in jmeter. Is there any workaround for this ?<issue_comment>username_1: By simply adding `![]()` tag inside . For the selected option use `ngClass` to set the image as background. You must use one class by option:
**HTML**
```
None
Option 1

Option 2

Option 3
```
**CSS:**
```
.option1{
background: url("https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg") center / contain no-repeat;
white-space: nowrap
}
.option2{
background: url("https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg") center / contain no-repeat;
white-space: nowrap;
display:inline
}
```
**[DEMO](https://stackblitz.com/edit/angular-ydugqt?file=src/app/select-overview-example.ts)**
Upvotes: 5 [selected_answer]<issue_comment>username_2: 
when it comes to this or similar situation, I did it that:
```
```
of course, inside tags and ` can be any tags as well img, and they work !!
Upvotes: 5 <issue_comment>username_3: I recommend putting a within the and/or elements, then binding html to it after the fashion precribed by [this answer](https://stackoverflow.com/a/58741354/507721).
```html
```
Upvotes: 0 <issue_comment>username_4: [](https://i.stack.imgur.com/uHq2N.png)
Use Mat Select Trigger check: <https://material.angular.io/components/select/api#MatSelectTrigger>
```
....

{{fromControl.value}}

...
```
Upvotes: 0 |
2018/03/19 | 1,001 | 3,831 | <issue_start>username_0: Right now, on the "All releases" page of the Python Software Foundation website, the "Download latest release" links to the Python 3.6.4 version.
However, you can find on the page that the release is from the 2017-12-19 and there has been two others release since, for Python 3.5.5 and Python 3.4.8 .
I understand why there is two parallel version of Python with 3 and 2.7, but I do not understand why they are multiple versions of Python 3, as it should be backward compatible with Python 3 code.<issue_comment>username_1: Python 3.x is not nesscarily backward compatible. For instance in python 3.6, string interpolation was introduced, aka f-string.
In python 3.5 type hints were introduced which would not be backwards compatible with older 3.x versions.
Upvotes: 1 <issue_comment>username_2: x.y.Z point releases are usually *bug fix releases*.
x.Y releases are usually feature releases, but might contain *minor* backwards incompatibilities.
X releases are large changes possibly breaking a lot of existing code.
In practice you cannot always upgrade your x.Y version immediately; reasons range from actual code incompatibilities which cannot be fixed quickly to internal deployment limitations to scheduling reasons. Linux distributions also often distribute one specific x.Y version and will pick up the next version only a year later in their annual release cycle or so. However, x.y.Z versions are often picked up soon and can typically be installed without breaking existing code.
The reason several x.y.Z versions are maintained in parallel is that users want to reap the benefits of bug fixes without being forced to upgrade to a new major version.
Upvotes: 4 [selected_answer]<issue_comment>username_3: The Python [Development Cycle](https://devguide.python.org/devcycle/) page describes how python maintains versions. Here are some snippets:
>
> 17.1.1. In-development (main) branch
>
>
> The master branch is the branch for the next feature release; it is under active development for all kinds of changes: new features, semantic changes, performance improvements, bug fixes.
>
>
> 17.1.2. Maintenance branches
>
>
> A branch for a previous feature release, currently being maintained for bug fixes. There are usually two maintenance branches at any given time: one for Python 3.x and one for Python 2.x.
>
>
> 17.1.3. Security branches
>
>
> A branch less than 5 years old but no longer in maintenance mode is a security branch. The only changes made to a security branch are those fixing issues exploitable by attackers such as crashes, privilege escalation and, optionally, other issues such as denial of service attacks.
>
>
>
So in addition to the main branch receiving new feature updates, there is a maintenance branch receiving general bugfixes for each of Python 2 and 3, and a number of other branches receiving security fixes. When bug/security fixes are applied, the micro/patch version (the third number in the version) is incremented. Here's a snapshot of what it looks like as of when this was written, from the same document:
>
> 17.1.4. Summary
>
>
> There are 6 open branches right now in the Git repository:
>
>
> * the master branch accepts features and bugs fixes for the future 3.8.0 feature release (RM: Łukasz Langa)
> * the 3.7 branch accepts bug, regression, and doc fixes for the upcoming 3.7.0 feature release (RM: Ned Deily)
> * the 3.6 branch accepts bug fixes for future 3.6.x maintenance releases (RM: Ned Deily)
> * the 3.5 branch accepts security fixes for future 3.5.x security releases (RM: Larry Hastings)
> * the 3.4 branch accepts security fixes for future 3.4.x security releases (RM: Larry Hastings)
> * the 2.7 branch accepts bug fixes for future 2.7.x maintenance releases (RM: <NAME>)
>
>
>
Upvotes: 1 |
2018/03/19 | 802 | 2,997 | <issue_start>username_0: I upload and save uploaded file to firebase database using this code.
html
```
Enter a description for image
![image]()
Enter a description for image
```
Js
```
function showMainImage(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img = document.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
firebase.auth().onAuthStateChanged((user) => {
if (user) {
database = firebase.database();
var Cataloguedatabase = HoneyBox_CatalogueDB.database();
var Cataloguestorage = HoneyBox_CatalogueDB.storage();
var metadata = {
'contentType': file.type
};
// Push to child path.
// [START oncomplete]
var storageRef = Cataloguestorage.ref(ProductID + "/ProductImages/" + file.name);
storageRef.put(file, metadata).then(function(snapshot) {
var url = snapshot.downloadURL;
itemImageUrl.push(url);
var catalogueupdates = {};
var updates = {};
return Cataloguedatabase.ref().update(catalogueupdates);
})
}
})
}
```
I deleted some of the code to only show what I think its minimal and important.
The code works perfectly however, the image size are usually very large and when they are retrieve they take some time to download. I want to resize the uploaded image and create three different image sizes before sending to firebase storage. For example I want to resize the image to
thumbnail (136 X 136)
singleimage (454 X 527)
Since file is what is being put in firebase storage, how can I change the file width and height to match the above dimensions?
How can I achieve that in the code above?<issue_comment>username_1: You could [use a canvas](https://stackoverflow.com/a/24015367/1052033) or [use a library](https://www.npmjs.com/package/pica) (or [this one](https://github.com/powerbot15/image-compressor) maybe).
Upvotes: 0 <issue_comment>username_2: Even if you will change the size of an image, it's good to think about App Engine's get\_serving\_url. You can do it by setting your own microservice for generating these links.
Thanks to that you won't need to have different thumbnail sizes - it all can be achieved by a suffix to your URL.
[Clear example of using Google App Engine Images get\_serving\_url()](https://stackoverflow.com/questions/6566383/clear-example-of-using-google-app-engine-images-get-serving-url)
[List of all the App Engine images service get\_serving\_url() URI options](https://stackoverflow.com/questions/25148567/list-of-all-the-app-engine-images-service-get-serving-url-uri-options)
Upvotes: -1 |
2018/03/19 | 818 | 3,222 | <issue_start>username_0: Say I want to implement a TCP/UDP connection between two computers.
I know how to do this if I know computer's IPs and they are in the same LAN. But what if they are in different LANs?
P. S. it would be great if someone showed me the code on how to connect two computers in the same LAN if they don't know each others IPs.
P. P. S. I would prefer using stdlib and sockets library<issue_comment>username_1: If your hosts are on different subnets, you cannot connect them without knowing their IP Addresses. They are isolated from each other, you must forward the ports to their IPs from your router configuration panel or set them up as DMZ hosts. I suppose you could setup a local DNS server and assign your hosts human-readable hostnames and resolve those IPs dynamically to jump this hurdle, but the ports must still be opened or the router firewall will not forward the traffic. And you'll need to add your local DNS server to the whichever host is initiating the connection's name server list. And.. the DNS server still needs to know what the IP of the hosts expecting connections are, so if they change, this needs to be updated somehow.
For TCP: On the SAME subnet, you can use SSDP: <https://pypi.python.org/pypi/ssdp/1.0.1>
SSDP is a protocol of UPNP that uses UDP multicast, which essentially sends UDP packets to a special ip:port that your router will broadcast to all connected clients, such that all hosts will receive datagrams. The hosts can then send their IPs back to the server and you'll be able to create TCP connections.
For UDP: I'm not sure what you want, UDP already has a facility (multicast) for sending data to any arbitrary host.
As for code: Please do your own work and research, this isn't a free code writing service. To get you started, you can check out the python api code examples: <https://wiki.python.org/moin/UdpCommunication#Multicasting.3F>
Upvotes: 2 <issue_comment>username_2: To put it really simply, if they are in different LAN, meaning networks, you will need a layer 3 device (typically a router) to route the traffic between the devices.
Say device A IP is 192.168.3.3/24 (subnet mask 255.255.255.0 /24) and device B is 192.168.4.4/24. If A wants to send to B, he won't know how to send this as the device will check it's subnet mask and see that the network portion is not the same.
Thus you will need what we call a default gateway or a static route. To make it easier we will stick with a default gateway (and check the static route usage if you need this specifically). This means for the device: if you don't know where the other network is, send this packet to the default gateway (router) he will deal with this and find the way to the end device.
Technically speaking it doesn't really matter to be on the WAN or LAN, in the end it's a different network and packet needs to be routed.
One important point, you will need to know the IP at some point. Either you, the app or whatever. One previous comment mentioned the use of DNS, this can be a solution but you still need to know an IP address.
In a way it's like saying I will send you a letter but I don't know your address. This won't be delivered.
Upvotes: 3 [selected_answer] |
2018/03/19 | 960 | 3,487 | <issue_start>username_0: Am trying to add a random number of flops in the range between 0-10 flops. But facing an issue while the random number is 0.
Expecting data shouldn't be flopped if the random value is 0. Can you please suggest your comments.
Code:
```
module tx_delay_bmod_1(clk, i_tx_data,o_tx_data);
parameter CH_NUM = 4;
input clk;
input i_tx_data;
output reg o_tx_data;
int DELAY;
bit o_tx_data_tmp[100];
int random_flop_cnt;
int seed_num,ntb_random_seed;
initial
random_flop_cnt = (($urandom(CH_NUM )%10) + ((CH_NUM/4)*10));
always@(negedge clk) begin
if (random_flop_cnt==0) o_tx_data = i_tx_data;
else begin
for(int i=0; i
```<issue_comment>username_1: If your hosts are on different subnets, you cannot connect them without knowing their IP Addresses. They are isolated from each other, you must forward the ports to their IPs from your router configuration panel or set them up as DMZ hosts. I suppose you could setup a local DNS server and assign your hosts human-readable hostnames and resolve those IPs dynamically to jump this hurdle, but the ports must still be opened or the router firewall will not forward the traffic. And you'll need to add your local DNS server to the whichever host is initiating the connection's name server list. And.. the DNS server still needs to know what the IP of the hosts expecting connections are, so if they change, this needs to be updated somehow.
For TCP: On the SAME subnet, you can use SSDP: <https://pypi.python.org/pypi/ssdp/1.0.1>
SSDP is a protocol of UPNP that uses UDP multicast, which essentially sends UDP packets to a special ip:port that your router will broadcast to all connected clients, such that all hosts will receive datagrams. The hosts can then send their IPs back to the server and you'll be able to create TCP connections.
For UDP: I'm not sure what you want, UDP already has a facility (multicast) for sending data to any arbitrary host.
As for code: Please do your own work and research, this isn't a free code writing service. To get you started, you can check out the python api code examples: <https://wiki.python.org/moin/UdpCommunication#Multicasting.3F>
Upvotes: 2 <issue_comment>username_2: To put it really simply, if they are in different LAN, meaning networks, you will need a layer 3 device (typically a router) to route the traffic between the devices.
Say device A IP is 192.168.3.3/24 (subnet mask 255.255.255.0 /24) and device B is 192.168.4.4/24. If A wants to send to B, he won't know how to send this as the device will check it's subnet mask and see that the network portion is not the same.
Thus you will need what we call a default gateway or a static route. To make it easier we will stick with a default gateway (and check the static route usage if you need this specifically). This means for the device: if you don't know where the other network is, send this packet to the default gateway (router) he will deal with this and find the way to the end device.
Technically speaking it doesn't really matter to be on the WAN or LAN, in the end it's a different network and packet needs to be routed.
One important point, you will need to know the IP at some point. Either you, the app or whatever. One previous comment mentioned the use of DNS, this can be a solution but you still need to know an IP address.
In a way it's like saying I will send you a letter but I don't know your address. This won't be delivered.
Upvotes: 3 [selected_answer] |
2018/03/19 | 632 | 1,634 | <issue_start>username_0: I scraped Twitter media with `simple_html_dom` and got this array result:
```
Array
(
[0] => https://pbs.twimg.com/media/DWyUfBdVwAE9bmJ.jpg
[1] => https://pbs.twimg.com/media/DWyUgBUVMAASB_g.jpg
[2] => https://pbs.twimg.com/media/DWyUg-xU0AEHdyL.jpg
)
Array
(
[0] => https://pbs.twimg.com/media/CYba_z2UwAAoSuC.jpg
)
Array
(
[0] => https://pbs.twimg.com/media/CTyJ52dUEAAirWw.jpg
[1] => https://pbs.twimg.com/media/CTyJ5yMUkAAbvZq.jpg
[2] => https://pbs.twimg.com/media/CTyJ5k4VEAAC4f7.jpg
[3] => https://pbs.twimg.com/media/CTyJ5f4VAAAZ08g.jpg
)
Array
(
[0] => https://pbs.twimg.com/media/CTyJJyeUcAAo8kt.jpg
[1] => https://pbs.twimg.com/media/CTyJJ2KUkAIKOPa.jpg
[2] => https://pbs.twimg.com/media/CTyJJycUkAAL29J.jpg
)
```
How can I access every `$value[0]` for each array?
this is my code based on <https://github.com/alexroan/twitter-scraper> :
```
php
require 'TwitterScraper.php';
$feed = TwitterScraper::get_feed('maretaso_u');
foreach($feed as $tweet){
$media = $tweet-media;
echo "
```
";
print_r($media);
echo "
```
";
}
```
```
```<issue_comment>username_1: I had to make some guesses based on the info you gave. But this is what I did:
```
php
$feed = TwitterScraper::get_feed('maretaso_u');
$filtered = array_map(function($tweet) {
return $tweet-media[0];
}, $feed);
var_dump($filtered);
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: Example:
```
$filtered = [];
foreach ($list as $values) {
$filtered[] = $values[0];
}
var_dump($filtered);
```
Upvotes: 1 |
2018/03/19 | 615 | 2,002 | <issue_start>username_0: I am trying to run my report with VBA rowsource using a query.
I have a problem replacing the inbuilt access query to VBA because of double quotes.
I have tried replacing the double quotes with & CHR(34) but unsuccessful.
```
TRANSFORM Count(History_query.WAS) AS CountOfWAS
SELECT History_query.Datum
FROM History_query
WHERE (((History_query.Datum) Between [Forms]![fr_M-Shiftreport]![Text72] And [Forms]![fr_M-Shiftreport]![Text81]) AND ((History_query.WAS)=[Forms]![fr_M-Shiftreport]![Combo186]))
GROUP BY History_query.Datum
PIVOT History_query.Status In ("erledigt","offen","in Bearbeitung","abgearbeitet / beobachten");
```
above query works perfect in Access datasheet view und report chart is also generated.
I want to transform this query in VBA.<issue_comment>username_1: Try using *single quotes*:
```
PIVOT History_query.Status In ('erledigt','offen','in Bearbeitung','abgearbeitet / beobachten');
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: I'm guessing you are running into issues escaping the quotes in vba. You would need to double up the double quotes to escape them. If you could post any errors you are getting that would be helpful. The below will get your query results into a recordset.
```
Sub run()
Dim strSQL As String
Dim db As Database: Set db = CurrentDb
Dim rs As Recordset
strSQL = "TRANSFORM Count(History_query.WAS) AS CountOfWAS " & _
"SELECT History_query.Datum " & _
"FROM History_query " & _
"WHERE (((History_query.Datum) Between [Forms]![fr_M-Shiftreport]![Text72] And [Forms]![fr_M-Shiftreport]![Text81]) " & _
"AND ((History_query.WAS)=[Forms]![fr_M-Shiftreport]![Combo186])) " & _
"GROUP BY History_query.Datum " & _
"PIVOT History_query.Status In (""erledigt"",""offen"",""in Bearbeitung"",""abgearbeitet / beobachten"");"
Set rs = db.OpenRecordset(strSQL)
'do vba stuff...
EXIT_PROC:
Set rs = Nothing
Set db = Nothing
End Sub
```
Upvotes: 0 |
2018/03/19 | 443 | 1,421 | <issue_start>username_0: Is the following:
```
$arr = [
foo => 'bar',
bar => 'foo'
];
```
The same as:
```
$arr = [
'foo' => 'bar',
'bar' => 'foo'
];
```
In other words, is putting quotes on named indexes unnecessary? When would be the only times when putting quotes on string indexes be really needed?<issue_comment>username_1: Your first example should throw a *NOTICE*. If you do not use quotes then PHP will look for a constant with that name.
```
php > $myArr = [abc => 'hello'];
PHP Notice: Use of undefined constant abc - assumed 'abc' in php shell code on line 1
PHP Stack trace:
PHP 1. {main}() php shell code:0
Notice: Use of undefined constant abc - assumed 'abc' in php shell code on line 1
Call Stack:
9.7779 350840 1. {main}() php shell code:0
```
---
I ran this example in PHP 7.1.8, however in PHP 7.2 [this has been deprecated](https://wiki.php.net/rfc/deprecate-bareword-strings).
Upvotes: 4 [selected_answer]<issue_comment>username_2: PHP converts "bare strings" into proper strings, but will give you a warning. It is likely that this functionality will disappear in future.
If you really, really want to do this (you shouldn't), it will work as log as the string matches the [format for a constant](http://php.net/manual/en/language.constants.php), which is the regex
```
[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
```
(Don't do it. Just don't.)
Upvotes: 0 |
2018/03/19 | 596 | 1,898 | <issue_start>username_0: Tables 1 as below
```
User_Option_Experience
user_id | teaching_in
|
111 | 1,2,3
112 | 1,4
113 | 4,2
```
Tables 2 as below
```
Teaching_in
IdTeaching | name
|
1 | Biology
2 | Chemistry
3 | Mathematics
```
Now what i want is to have an output of all the names of subjects a User (Teacher) teaches in because one user as seen from the table can teach many subjects
For example I want all the subjects for user with id 111
I tried this but no success as it returns only one record
```
select teaching_in.name
from teaching_in
left
join users_options_experience
on user_options_experience.teaching_in = teaching_in.IdTeachingin
where user_options_experience.user_id = 15605
```<issue_comment>username_1: Your first example should throw a *NOTICE*. If you do not use quotes then PHP will look for a constant with that name.
```
php > $myArr = [abc => 'hello'];
PHP Notice: Use of undefined constant abc - assumed 'abc' in php shell code on line 1
PHP Stack trace:
PHP 1. {main}() php shell code:0
Notice: Use of undefined constant abc - assumed 'abc' in php shell code on line 1
Call Stack:
9.7779 350840 1. {main}() php shell code:0
```
---
I ran this example in PHP 7.1.8, however in PHP 7.2 [this has been deprecated](https://wiki.php.net/rfc/deprecate-bareword-strings).
Upvotes: 4 [selected_answer]<issue_comment>username_2: PHP converts "bare strings" into proper strings, but will give you a warning. It is likely that this functionality will disappear in future.
If you really, really want to do this (you shouldn't), it will work as log as the string matches the [format for a constant](http://php.net/manual/en/language.constants.php), which is the regex
```
[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
```
(Don't do it. Just don't.)
Upvotes: 0 |
2018/03/19 | 526 | 1,877 | <issue_start>username_0: I have a pyspark dataframe with a column `FullPath`.
How can I use the function `os.path.splitext(FullPath)` to extract the extension of each entry in the `FullPath` column and put them in a new column?
Thanks.<issue_comment>username_1: There is a split function the SQL functions module, so you can split your full path on the "." character and take the last element. Assuming that there is only one "." in each filepath string.
```
import pyspark.sql.functions as F
myDataFrame = myDataFrame.withColumn("pathArray", F.split(myDataFrame.FullPath, ".")
myDataFrame = myDataFrame.withColumn("FileExtension", myDataFrame.pathArray.getItem(1))
```
Upvotes: 0 <issue_comment>username_2: You can use [`pyspark.sql.functions.regexp_extract()`](http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.functions.regexp_extract) to [extract the file extension](https://stackoverflow.com/questions/6582171/javascript-regex-for-matching-extracting-file-extension):
```python
import pyspark.sql.functions as f
data = [
('/tmp/filename.tar.gz',)
]
df = sqlCtx.createDataFrame(data, ["FullPath"])
df.withColumn("extension", f.regexp_extract("FullPath", "\.[0-9a-z]+$", 0)).show()
#+--------------------+---------+
#| FullPath|extension|
#+--------------------+---------+
#|/tmp/filename.tar.gz| .gz|
#+--------------------+---------+
```
However if you wanted to use `os.path.splittext()`, you would need to use a `udf` (which will be slower than the above alternative):
```python
import os
splittext = f.udf(lambda FullPath: os.path.splitext(FullPath)[-1], StringType())
df.withColumn("extension", splittext("FullPath")).show()
#+--------------------+---------+
#| FullPath|extension|
#+--------------------+---------+
#|/tmp/filename.tar.gz| .gz|
#+--------------------+---------+
```
Upvotes: 2 |
2018/03/19 | 3,575 | 12,174 | <issue_start>username_0: First, a puzzle:
What does the following code print?
```
public class RecursiveStatic {
public static void main(String[] args) {
System.out.println(scale(5));
}
private static final long X = scale(10);
private static long scale(long value) {
return X * value;
}
}
```
Answer:
>
> 0
>
>
>
Spoilers below.
---
If you print `X` in scale(long) and redefine `X = scale(10) + 3`,
the prints will be `X = 0` then `X = 3`.
This means that `X` is temporarily set to `0` and later set to `3`.
This is a violation of `final`!
>
> The static modifier, in combination with the final modifier, is also used to define constants.
> The final modifier indicates that the value of **this field cannot change**.
>
>
>
Source: <https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html> [emphasis added]
---
My question:
Is this a bug?
Is `final` ill-defined?
---
Here is the code that I am interested in.
`X` is assigned two different values: `0` and `3`.
I believe this to be a violation of `final`.
```
public class RecursiveStatic {
public static void main(String[] args) {
System.out.println(scale(5));
}
private static final long X = scale(10) + 3;
private static long scale(long value) {
System.out.println("X = " + X);
return X * value;
}
}
```
---
This question has been flagged as a possible duplicate of [Java static final field initialization order](https://stackoverflow.com/questions/27859435/).
I believe that this question is **not** a duplicate since
the other question addresses the order of initialization while
my question addresses a cyclic initialization combined with the `final` tag.
From the other question alone, I would not be able to understand why the code in my question does not make an error.
This is especially clear by looking at the output that ernesto gets:
when `a` is tagged with `final`, he gets the following output:
```
a=5
a=5
```
which does not involve the main part of my question: How does a `final` variable change its variable?<issue_comment>username_1: **Not a bug.**
When the first call to `scale` is called from
```
private static final long X = scale(10);
```
It tries to evaluate `return X * value`. `X` has not been assigned a value yet and therefore the default value for a `long` is used (which is `0`).
So that line of code evaluates to `X * 10` i.e. `0 * 10` which is `0`.
Upvotes: 4 <issue_comment>username_2: Nothing to do with final here.
Since it is at instance or class level, it holds the default value if nothing gets assigned yet. That is the reason you seeing `0` when you accessing it without assigning.
If you access `X` without completely assigning, it holds the default values of long which is `0`, hence the results.
Upvotes: 5 <issue_comment>username_3: A very interesting find. To understand it we need to dig into the Java Language Specification ([JLS](https://docs.oracle.com/javase/specs/jls/se9/html)).
The reason is that `final` only allows one *assignment*. The default value, however, is no *assignment*. In fact, every *such variable* (class variable, instance variable, array component) points to its *default value* from the beginning, before *assignments*. The first assignment then changes the reference.
---
Class variables and default value
---------------------------------
Take a look at the following example:
```
private static Object x;
public static void main(String[] args) {
System.out.println(x); // Prints 'null'
}
```
We did not explicitly assign a value to `x`, though it points to `null`, it's default value. Compare that to [§4.12.5](https://docs.oracle.com/javase/specs/jls/se9/html/jls-4.html#jls-4.12.5):
>
> Initial Values of Variables
>
>
> Each **class variable**, instance variable, or array component is initialized with a **default value** when it is **created** ([§15.9](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.9), [§15.10.2](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.10.2))
>
>
>
Note that this only holds for those kind of variables, like in our example. It does not hold for local variables, see the following example:
```
public static void main(String[] args) {
Object x;
System.out.println(x);
// Compile-time error:
// variable x might not have been initialized
}
```
From the same JLS paragraph:
>
> A **local variable** ([§14.4](https://docs.oracle.com/javase/specs/jls/se9/html/jls-14.html#jls-14.4), [§14.14](https://docs.oracle.com/javase/specs/jls/se9/html/jls-14.html#jls-14.14)) must be **explicitly given a value** before it is used, by either initialization ([§14.4](https://docs.oracle.com/javase/specs/jls/se9/html/jls-14.html#jls-14.4)) or assignment ([§15.26](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.26)), in a way that can be verified using the rules for definite assignment ([§16 (Definite Assignment)](https://docs.oracle.com/javase/specs/jls/se9/html/jls-16.html)).
>
>
>
---
Final variables
---------------
Now we take a look at `final`, from [§4.12.4](https://docs.oracle.com/javase/specs/jls/se9/html/jls-4.html#jls-4.12.4):
>
> *final* Variables
>
>
> A variable can be declared *final*. A *final* variable may only be **assigned to once**. It is a compile-time error if a *final* variable is assigned to unless it is **definitely unassigned immediately prior to the assignment** ([§16 (Definite Assignment)](https://docs.oracle.com/javase/specs/jls/se9/html/jls-16.html)).
>
>
>
---
Explanation
-----------
Now coming back to the your example, slightly modified:
```
public static void main(String[] args) {
System.out.println("After: " + X);
}
private static final long X = assign();
private static long assign() {
// Access the value before first assignment
System.out.println("Before: " + X);
return X + 1;
}
```
It outputs
```
Before: 0
After: 1
```
Recall what we have learned. Inside the method `assign` the variable `X` was **not assigned** a value to yet. Therefore, it points to its default value since it is an **class variable** and according to the JLS those variables always immediately point to their default values (in contrast to local variables). After the `assign` method the variable `X` is assigned the value `1` and because of `final` we can't change it anymore. So the following would not work due to `final`:
```
private static long assign() {
// Assign X
X = 1;
// Second assign after method will crash
return X + 1;
}
```
---
Example in the JLS
------------------
Thanks to @Andrew I found a JLS paragraph that covers exactly this scenario, it also demonstrates it.
But first let's take a look at
```
private static final long X = X + 1;
// Compile-time error:
// self-reference in initializer
```
Why is this not allowed, whereas the access from the method is? Take a look at [§8.3.3](https://docs.oracle.com/javase/specs/jls/se9/html/jls-8.html#jls-8.3.3) which talks about when accesses to fields are restricted if the field was not initialized yet.
It lists some rules relevant for class variables:
>
> For a reference by simple name to a class variable `f` declared in class or interface `C`, it is a **compile-time error if**:
>
>
> * The reference appears either in a class variable initializer of `C` or in a static initializer of `C` ([§8.7](https://docs.oracle.com/javase/specs/jls/se9/html/jls-8.html#jls-8.7)); and
> * The reference appears either in the initializer of `f`'s own declarator or at a point to the left of `f`'s declarator; and
> * The reference is not on the left hand side of an assignment expression ([§15.26](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.26)); and
> * The innermost class or interface enclosing the reference is `C`.
>
>
>
It's simple, the `X = X + 1` is caught by those rules, the method access not. They even list this scenario and give an example:
>
> Accesses by methods are not checked in this way, so:
>
>
>
> ```
> class Z {
> static int peek() { return j; }
> static int i = peek();
> static int j = 1;
> }
> class Test {
> public static void main(String[] args) {
> System.out.println(Z.i);
> }
> }
>
> ```
>
> produces the output:
>
>
>
> ```
> 0
>
> ```
>
> because the variable initializer for `i` uses the class method peek to access the value of the variable `j` before `j` has been initialized by its variable initializer, at which point it **still has its default value** ([§4.12.5](https://docs.oracle.com/javase/specs/jls/se9/html/jls-4.html#jls-4.12.5)).
>
>
>
Upvotes: 9 [selected_answer]<issue_comment>username_4: It's not a bug at all, simply put it is not an *illegal form* of forward references, nothing more.
```
String x = y;
String y = "a"; // this will not compile
String x = getIt(); // this will compile, but will be null
String y = "a";
public String getIt(){
return y;
}
```
It's simply allowed by the Specification.
To take your example, this is exactly where this matches:
```
private static final long X = scale(10) + 3;
```
You are doing a *forward reference* to `scale` that is not illegal in any way as said before, but allows you to get the default value of `X`. again, this is allowed by the Spec (to be more exact it is not prohibited), so it works just fine
Upvotes: 4 <issue_comment>username_5: Reading an uninitialized field of an object ought to result in a compilation error. Unfortunately for Java, it does not.
I think the fundamental reason why this is the case is "hidden" deep within the definition of how objects are instantiated and constructed, though I don't know the details of the standard.
In a sense, final is ill-defined because it doesn't even accomplish what its stated purpose is due to this problem. However, if all your classes are properly written, you don't have this problem. Meaning all fields are always set in all constructors and no object is ever created without calling one of its constructors. That seems natural until you have to use a serialization library.
Upvotes: 2 <issue_comment>username_6: Class level members can be initialized in code within the class definition. The compiled bytecode cannot initialize the class members inline. (Instance members are handled similarly, but this is not relevant for the question provided.)
When one writes something like the following:
```
public class Demo1 {
private static final long DemoLong1 = 1000;
}
```
The bytecode generated would be similar to the following:
```
public class Demo2 {
private static final long DemoLong2;
static {
DemoLong2 = 1000;
}
}
```
The initialization code is placed within a static initializer which is run when the class loader first loads the class. With this knowledge, your original sample would be similar to the following:
```
public class RecursiveStatic {
private static final long X;
private static long scale(long value) {
return X * value;
}
static {
X = scale(10);
}
public static void main(String[] args) {
System.out.println(scale(5));
}
}
```
1. The JVM loads the RecursiveStatic as the jar's entry point.
2. The class loader runs the static initializer when the class definition is loaded.
3. The initializer calls the function `scale(10)` to assign the `static final` field `X`.
4. The `scale(long)` function runs while the class is partially initialized reading the uninitialized value of `X` which is the default of long or 0.
5. The value of `0 * 10` is assigned to `X` and the class loader completes.
6. The JVM runs the public static void main method calling `scale(5)` which multiplies 5 by the now initialized `X` value of 0 returning 0.
The static final field `X` is only assigned once, preserving the guarantee held by the `final` keyword. For the subsequent query of adding 3 in the assignment, step 5 above becomes the evaluation of `0 * 10 + 3` which is the value `3` and the main method will print the result of `3 * 5` which is the value `15`.
Upvotes: 2 |
2018/03/19 | 482 | 1,264 | <issue_start>username_0: I'm wondering how to turn the color of the *y-axis label* for the **first** and the **last** label to `"red"` (*see picture below*)?
Here is what I tried without success:
```
plot(1:5, yaxt = "n")
axis(2, at = 1:5, labels = paste0("case ", 1:5), col.axis = c(2, rep(1, 3), 2))
```
[](https://i.stack.imgur.com/OkiFG.png)<issue_comment>username_1: `col.axis` isn't vectorised, so you'd need to do it as two commands. First I've done all the annotations in black, then overplotted the ends in red.
```
plot(1:5, yaxt = "n")
axis(2, at = 1:5, labels = paste0("case ", 1:5), col.axis = 1)
axis(2, at = range(1:5), labels = paste0("case ", range(1:5)), col.axis = 2)
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: here is a more generic example:
```
palette ( c ( "steelblue", "orange" ))
X <- 1:5
Cols <- rep ( 1, length ( X ))
Cols [ c ( 1, length ( X ))] <- 2
plot ( X, yaxt = "n" )
axis ( 2, at = X, labels = FALSE )
mtext ( paste ( "Case", X ), at = pretty ( X ),
side = 2, line = 1, col = Cols )
```
[](https://i.stack.imgur.com/xrkKh.png)
I hope it helps.
David
Upvotes: 1 |
2018/03/19 | 375 | 1,284 | <issue_start>username_0: From graphviz import Digraph, Graph
```
dot = Digraph(comment='First ')
dot.attr(rankdir='LR') # Left to Right
dot.node('A', 'Tax')
```
I tried to add a hyperlink to the node with label Tax using URL and href but it is not working. Could you please advise me the solution as i am a beginner in garphviz.
Thanks in advance<issue_comment>username_1: According to the graphviz documentation of [`URL`](https://graphviz.gitlab.io/_pages/doc/info/attrs.html#d:URL) and the [python graphviz manual](http://graphviz.readthedocs.io/en/stable/manual.html), the following may work (no python user here):
```
dot = Digraph(comment='First ')
dot.attr(rankdir='LR') # Left to Right
dot.attr('node', URL='https://stackoverflow.com')
dot.node('A', 'Tax')
```
This may only be useful when choosing svg output.
Upvotes: 1 <issue_comment>username_2: Use href instead of URL as the parameter.
Upvotes: 1 <issue_comment>username_3: I am using Google Colab (a Jupyter notebook server)
Nothing here seemed to work, but gave me ideas. Here is what worked for me.
```
import graphviz
from graphviz import Digraph
toc = Digraph('…',
engine='dot')
toc.node('Name',href="https://...")
display(toc)
```
I am still working on exporting the image
Upvotes: -1 |
2018/03/19 | 1,342 | 4,733 | <issue_start>username_0: first of all I am pretty new to javascript/jQuery. But I did make a code that show's an image when a specific option is selected. But the code is very long and I am asking myself if I can make my code shorter.
Here is the HTML:
```
Ik ben op zoek naar een:
Selecteer een optie
Greenline veranda
Profiline veranda
Highline veranda
Aluminium tuinkamer
Glasschuifwanden
Carport gebogen
Carport vlak
Aluminium schutting
Composiet schutting
```
And here is the jQuery behind it:
```
$('[name=inputType]').change(function(){
if($(this).val() === 'greenlineveranda') {
$('#greenlinePicture').css("display","block");
}
else {
$('#greenlinePicture').css("display","none");
}
if($(this).val() === 'profilineveranda') {
$('#profilinePicture').css("display","block");
}
else {
$('#profilinePicture').css("display","none");
}
if($(this).val() === 'highlineveranda') {
$('#highlinePicture').css("display","block");
}
else {
$('#highlinePicture').css("display","none");
}
if($(this).val() === 'aluminiumtuinkamer') {
$('#aluminiumtuinkamerPicture').css("display","block");
}
else {
$('#aluminiumtuinkamerPicture').css("display","none");
}
if($(this).val() === 'glasschuifwanden') {
$('#glasschuifwandenPicture').css("display","block");
}
else {
$('#glasschuifwandenPicture').css("display","none");
}
if($(this).val() === 'carportgebogen') {
$('#carportgebogenPicture').css("display","block");
}
else {
$('#carportgebogenPicture').css("display","none");
}
if($(this).val() === 'carportvlak') {
$('#carportvlakPicture').css("display","block");
}
else {
$('#carportvlakPicture').css("display","none");
}
if($(this).val() === 'aluminiumschutting') {
$('#aluminiumschuttingPicture').css("display","block");
}
else {
$('#aluminiumschuttingPicture').css("display","none");
}
if($(this).val() === 'composietschutting') {
$('#composietschuttingPicture').css("display","block");
}
else {
$('#composietschuttingPicture').css("display","none");
}
});
```
Can I make the jQuery function shorter?
Thanks for your time!<issue_comment>username_1: add a class "pics" to every pictures.
```

```
and set an id for each picture
```



```
So, on change hide all pictures
```
$('.pics').css("display","none");
```
and show only the selected one:
```
$('[name=inputType]').change(function(){
var selected_id = $(this).val()
$('#pic_' + selected_id).css("display","block");
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: One way you could do this would be to map the values to the ids, and use the object to lookup which id to show.
```js
var pictures = {
'greenlineveranda': '#greenlinePicture',
'profilineveranda': '#profilinePicture',
'highlineveranda': '#highlinePicture'
};
$('[name=inputType]').change(function() {
$(Object.values(pictures).join(',')).css('display', none');
$(pictures[this.value]).css('display', block');
});
```
Upvotes: 0 <issue_comment>username_3: I do in this way if u want to use id no problem, just add class to make images visible. Sorry for my bad English.
```js
$(document).ready(function(){
$('select[name="inputType"]').on('change', function(e) {
var v = $(this).val();
$('img').removeClass('show').filter('#' + v + 'Picture').addClass('show');
});
});
```
```css
img{ display: none;}
img.show{ display: inline;}
```
```html
Ik ben op zoek naar een:
Selecteer een optie
Greenline veranda
Profiline veranda
Highline veranda
Aluminium tuinkamer
Glasschuifwanden
Carport gebogen
Carport vlak
Aluminium schutting
Composiet schutting









```
Upvotes: 0 |
2018/03/19 | 1,657 | 6,938 | <issue_start>username_0: There is one big phenomena in the spring environment or I am terribly wrong.
But the default spring @Transactional annotation is not ACID but only ACD lacking the isolation. That means that if you have the method:
```
@Transactional
public TheEntity updateEntity(TheEntity ent){
TheEntity storedEntity = loadEntity(ent.getId());
storedEntity.setData(ent.getData);
return saveEntity(storedEntity);
}
```
What would happen if 2 threads enter with different planned updates. They both load the entity from the db, they both apply their own changes, then the first is saved and commit and when the second is saved and commit the first UPDATE IS LOST. Is that really the case? With the debugger it is working like that.<issue_comment>username_1: You are not terribly wrong, your question is a very interesting observation. I believe (based on your comments) you are thinking about it in your very specific situation whereas this subject is much broader. Let's take it step by step.
**ACID**
*I* in ACID indeed stands for isolation. But it does not mean that two or more transactions need to be executed one after another. They just need to be isolated to some level. Most of the relational databases allow to set an isolation level on a transaction even allowing you to read data from other uncommitted transaction. It is up to specific application if such a situation is fine or not. See for example mysql documentation:
<https://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html>
You can of course set the isolation level to serializable and achieve what you expect.
Now, we also have NoSQL databases that don't support ACID. On top of that if you start working with a cluster of databases you may need to embrace eventual consistency of data which might even mean that the same thread that just wrote some data may not receive it when doing a read. Again this is a question very specific to a particular app - can I afford having inconsistent data for a moment in exchange for a fast write?
You would probably lean towards consistent data handled in serializable manner in banking or some financial system and you would probably be fine with less consistent data in a social app but achieving a higher performance.
**Update is lost - is that the case?**
Yes, that will be the case.
**Are we scared of serializable?**
Yes, it might get nasty :-) But it is important to understand how it works and what are the consequences. I don't know if this is still the case but I had a situation in a project about 10 years ago where DB2 was used. Due to very specific scenario DB2 was performing a lock escalation to exclusive lock on the whole table effectively blocking any other connection from accessing the table even for reads. That meant only a single connection could be handled at a time.
So if you choose to go with serializable level you need to be sure that your transaction are in fact fast and that it is in fact needed. Maybe it is fine that some other thread is reading the data while you are writing? Just imagine a scenario where you have a commenting system for your articles. Suddenly a viral article gets published and everyone starts commenting. A single write transaction for comment takes 100ms. 100 new comments transactions get queued which effectively will block reading the comments for the next 10s. I am sure that going with read committed here would be absolutely enough and allow you achieve two things: store the comments faster and read them while they are being written.
Long story short:
It all depends on your data access patterns and there is no silver bullet. Sometimes serializable will be required but it has its performance penalty and sometimes read uncommitted will be fine but it will bring inconsistency penalties.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Losing data?
------------
You're not losing data. Think of it like changing a variable in code.
```
int i = 0;
i = 5;
i = 10;
```
Did you "lose" the 5? Well, no, you replaced it.
Now, the tricky part that you alluded to with multi-threading is what if these two SQL updates happen at the same time?
From a pure update standpoint (forgetting the read), it's no different. Databases will use a lock to serialize the updates so one will still go before the other. The second one wins, naturally.
But, there is one danger here...
Update based on the current state
---------------------------------
What if the update is conditional based on the current state?
```
public void updateEntity(UUID entityId) {
Entity blah = getCurrentState(entityId);
blah.setNumberOfUpdates(blah.getNumberOfUpdates() + 1);
blah.save();
}
```
Now you have a problem of data loss because if two concurrent threads perform the read (`getCurrentState`), they will each add `1`, arrive at the same number, and the second update will lose the increment of the previous one.
Solving it
----------
There are two solutions.
1. Serializable isolation level - In most isolation levels, reads (`select`s) do not hold any exclusive locks and therefore do not block, regardless of whether they are in a transaction or not. Serializable will actually acquire and hold an exclusive lock for every row read, and only release those locks when the transaction commits or rolls back.
2. Perform the update in a single statement. - A single `UPDATE` statement should make this atomic for us, i.e. `UPDATE entity SET number_of_updates = number_of_updates + 1 WHERE entity_id = ?`.
Generally speaking, the latter is much more scalable. The more locks you hold and the longer you hold them, the more blocking you get and therefore less throughput.
Upvotes: 3 <issue_comment>username_3: To add to the comments above, this situation with `@Transactional` and "lost updates" is not wrong, however, it may seem confusing, because it does not meet our expectations that `@Transactional` protects against "lost updates".
"Lost update" problem **can happen** with the `READ_COMMITED` isolation level, which is the default for most DBs and JPA providers as well.
To prevent it one needs to use `@Transactional(isolation = isolation.REPEATABLE_READ)`. No need for `SERIALIZABLE`, that would overkill.
The very good explanation is given by well known JPA champion <NAME> in his article: <https://vladmihalcea.com/a-beginners-guide-to-database-locking-and-the-lost-update-phenomena/>
It is also worth mentioning that a better solution is to use `@Version` that also can prevent lost updates with an optimistic locking approach.
The problem maybe comes from wiki page <https://en.wikipedia.org/wiki/Isolation_(database_systems)> where it is shown that "lost update" is a "weaker" problem than "dirty reads" and is never a case, however, the text below contradicts:
[](https://i.stack.imgur.com/2FPhG.png)
Upvotes: 2 |
2018/03/19 | 529 | 2,250 | <issue_start>username_0: Please, I need help with are problem, I changing the syntax Swift 3 for swift 4 and now i have many problems for identification of all my bugs.The Error its on the function savePhoto in the last line., completionHandler: { \_ in
```
func takePhoto(_ previewLayer: AVCaptureVideoPreviewLayer, location: CLLocation?, completion: (() -> Void)? = nil) {
guard let connection = stillImageOutput?.connection(with: AVMediaType.video) else { return }
connection.videoOrientation = Helper.videoOrientation()
queue.async {
self.stillImageOutput?.captureStillImageAsynchronously(from: connection) {
buffer, error in
guard let buffer = buffer, error == nil && CMSampleBufferIsValid(buffer),
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer),
let image = UIImage(data: imageData)
else {
DispatchQueue.main.async {
completion?()
}
return
}
self.savePhoto(image, location: location, completion: completion)
}
}
}
func savePhoto(_ image: UIImage, location: CLLocation?, completion: (() -> Void)? = nil) {
PHPhotoLibrary.shared().performChanges({
let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
request.creationDate = Date()
request.location = location
}, completionHandler: { _ in
DispatchQueue.main.async {
completion?()
}
})
}
```<issue_comment>username_1: Rewrite it to:
```
}, completionHandler: { (_, _) in
```
As per [documentation](https://developer.apple.com/documentation/photos/phphotolibrary/1620743-performchanges), completion handler in `performChanges(_:completionHandler:)` accepts two parameters, not just one. `_ in`, what you have used, is a placeholder for a single parameter only.
Upvotes: 2 [selected_answer]<issue_comment>username_2: As you can clearly see in the error message the `completionHandler` passes **two** parameters rather than just one.
So you have to write
```
}, completionHandler: { (_, _) in
```
but you are strongly encouraged to handle the result and a potential error. Ignoring errors causes bad user experience.
Upvotes: 0 |
2018/03/19 | 826 | 2,796 | <issue_start>username_0: I want to disable a certain group of buttons at a specific time. Using this js:
```
document.getElementById("reset").setAttribute('disabled','disabled');
```
But all IDs are different, the buttons is like etc. Can I set some made up variable like
And then do something like this:
```
document.getElementById("group:hello").setAttribute('disabled','disabled');
```
to disable all of the buttons, even though the ID attribute is different from button to button?<issue_comment>username_1: Use class instead of ID.
Code is easy:
```
document.getElementsByClassName("group1").setAttribute('disabled','disabled');
```
Upvotes: 0 <issue_comment>username_2: Since you tagged jquery
```
$(".mybutton").attr("disabled", true);
```
Where mybutton is
```
```
Upvotes: 0 <issue_comment>username_3: Use `class` instead of `id` as follows:
```
var elements = document.getElementsByClassName("{yourClassName}");
var i;
for (i = 0; i < x.length; i++) {
elements[i].setAttribute(“disabled”, “red");
}
<button class="{yourClassName}”>
```
Upvotes: 0 <issue_comment>username_4: You can use `getElementsByTagName` to get all buttons and then You can use `Array.Prototype.forEach` to disable all buttons like below. `forEach` will loop through all element and add desired attribute(in your case disabled) to all found elements.
```js
Array.prototype.forEach.call
(document.getElementsByTagName("button"), function(e) {
e.setAttribute('disabled','disabled');
});
```
```html
12 12
12 12
```
Upvotes: 0 <issue_comment>username_5: You can use wildcards for Id's:
Starts-with selector
```
document.querySelector("[id^=myId]")
```
works for
```
id="myId1"
id="myId2"
...
```
or Ends-with selector
```
document.querySelector("[id$=myId]")
```
works for
```
id="firstMyId"
id="secondMyId",...
```
Hint:
Please don't start Id's with numbers like: id="1myId". That's not w3c conform
Upvotes: 0 <issue_comment>username_6: use class to group buttons, like this:
```
var btnsGroup = document.getElementsByClassName('group');
Array.prototype.forEach.call(btnsGroup, function(button) {
button.setAttribute('disabled','disabled');
});
```
Upvotes: 0 <issue_comment>username_7: what you can do is use the data attribute, see next:
```
test1
test2
test3
```
and the JS
```
document.querySelectorAll('[data-group="hello"]').forEach(function(button) {
button.disabled = true;
});
```
edit, here is the fiddle <https://jsfiddle.net/xycmj4gv/2/>
Upvotes: 1 <issue_comment>username_8: You can do something like this-
```
var buttons = document.querySelectorAll("[reset='true']");
for (i = 0; i < buttons.length; ++i)
{
buttons[i].setAttribute('disabled','disabled');
}
```
And HTML goes like this-
```
1 Candy
2 Candy
```
Upvotes: 0 |
2018/03/19 | 802 | 3,357 | <issue_start>username_0: ```
```
What other value is available? Do I need to include this category and what if I delete it?
I did not find this in the official documentation - <https://developer.android.com/guide/topics/ui/shortcuts.html><issue_comment>username_1: Shortcut category for messaging related actions, such as chat.
Upvotes: 0 <issue_comment>username_2: `categories` tag is used to provide a grouping for the types of actions that your app's shortcuts perform. One of the available groups is `android.shortcut.conversation`, and this is used if you want to add a shortcut to conversation of chat application. For example, a shortcut to the most recent chat head. You would only need to add this in your shortcuts.xml, when you want to provide the said shortcut. Otherwise you don't need it. You can delete it.
For API level 26 or lower this is the only value that is avaliable. But for higher versions there are multiple.
For a list of supported shortcut categories you can see [this](https://developer.android.com/reference/android/content/pm/ShortcutInfo.html) page.
Upvotes: 4 [selected_answer]<issue_comment>username_3: At this moment only one type supported category is `android.shortcut.conversation`. You can find it in `ShortcutInfo`
```
/**
* Shortcut category for messaging related actions, such as chat.
*/
public static final String SHORTCUT_CATEGORY_CONVERSATION = "android.shortcut.conversation";
```
Also in
```
/**
* Sets categories for a shortcut. Launcher apps may use this information to
* categorize shortcuts.
*
* @see #SHORTCUT_CATEGORY_CONVERSATION
* @see ShortcutInfo#getCategories()
*/
@NonNull
public Builder setCategories(Set categories) {
mCategories = categories;
return this;
}
```
Upvotes: 2 <issue_comment>username_4: TL;DR in 2022: Seems like the "category" inner element became a forgotten feature of Android Shortcuts, and there only ended up being that one pre-defined "Conversation" category. Capabilities, on the other hand, are very well fleshed out and fill those boots quite well! Check out the link below for what capabilities can help you unlock!
In more detail as of 2022, Android API Level 25 introduced the ability to define shortcuts, letting you provide the user with a static set of shortcuts into your app for common actions like creating a new email as well as a dynamic set of shortcuts like sending a message to a recent contact.
It seems that the "category" inner element was intended to group certain similar shortcuts together. Unfortunately it seems the idea was abandoned likely due to the limited number of shortcuts that could appear in the small popup menu. These days the most I've seen is 5, and it can definitely vary based on your device. As a result of the limited space, it seems the only category that has been defined, even today with API level 32 available, is the "Conversation" category.
Due to its limited development, I find it best 99% of the time to leave off the "category" inner element in favor of the "capability" inner element which has quite the long list of pre-defined options that correspond to Built-In Intents (which can add amazing Google Assistant actions to your app)!
Here's [the list of all of them!](https://developer.android.com/reference/app-actions/built-in-intents/bii-index)
Upvotes: 1 |
2018/03/19 | 791 | 3,092 | <issue_start>username_0: I'm using Webpack and VueJs 2. I want to use a 3rd party javascript library in my component, such as this:
```
```
I found an article [here](https://vuejsdevelopers.com/2017/04/22/vue-js-libraries-plugins/) about how to do this for npm packages, but that doesn't work for me since this library is not available as npm package.
It's not possible for me to download the file locally and use it since the library might change and stop working. Therefore it has to be loaded from the link every time the page is loaded by the browser.
I found one possible solution [here](https://stackoverflow.com/a/47002863/448625) but that is basically a hack(modify dom to add a `script` element after document is loaded)
I believe there must be a simple good practice solution for this issue since I assume this is a common use-case.
**Update:**
If I put the script inside head tags in my index file, it would be loaded for all the components. For performance reasons, I would want it to be loaded only for a certain component.<issue_comment>username_1: As far as I know, there is no way you could use something better than adding the `script` tag into the head of your page dynamically. However, you could create a little plugin to handle that for you, and trigger the script loading only in the components you want, and just once.
Let's begin with the plugin itself:
```
import Vue from 'vue'
const scriptLoader = {
loaded: [],
load (src) {
if (this.loaded.indexOf(src) !== -1) {
return
}
this.loaded.push(src)
if (document) {
const script = document.createElement('script')
script.setAttribute('src', src)
document.head.appendChild(script)
}
}
}
Vue.use({
install () {
Vue.prototype.$scriptLoader = scriptLoader
}
})
```
As you can see, you create an object `scriptLoader` that contains some sort of cache object `loaded` that will remember what script you already loaded at some point in your application. It also contains a `load()` method that will handle the adding of the script into your head.
The condition `if (document)` is here in case you would server side render your app, `document` would not exist.
You could then load your script into any of your component at creation using the `created` hook:
```
export default {
...
created () {
this.$scriptLoader.load('https://apis.google.com/js/api.js')
}
}
```
This is the cleanest way I came with to handle that kind of script... I hope this can help...
Upvotes: 3 <issue_comment>username_2: Ok, found a solution that satisfies all the requirements.
* Script is downloaded from web, no npm package is needed
* Script is only loaded for certain
components when needed
* No ugly dom-manipulation
Add the script inside index.html with `v-if` directive
```
```
Inside the component file (`.vue`), if you want the script to be loaded set the flag to `true`:
```
export default {
...
loadGoogleAPI: true,
data() {
...
}
};
```
Upvotes: 2 [selected_answer] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.