text:
Q: data.table: How to change column values based on grouped unique row values that contain column names I have a data.table with ~18^6 rows and I need to take the unique values of CLASS, by ID, and set their respective columns to 1, as seen below in a baby example
DT <- data.table::data.table(ID=c("1","1","1","2","2"),
                             CLASS=c("a","a","b","c","b"),
                             a=c(0,0,0,0,0),
                             b=c(0,0,0,0,0),
                             c=c(0,0,0,0,0))

### Start with this
ID CLASS a b c
1      a 0 0 0
1      a 0 0 0
1      b 0 0 0
2      c 0 0 0
2      b 0 0 0

### Want this
ID CLASS a b c
1      a 1 1 0
1      a 1 1 0
1      b 1 1 0
2      c 0 1 1
2      b 0 1 1

My first instinct was to try the code below but found that it will set all columns to 1 because unique(DT$CLASS) inherently includes all unique values for all IDs and is not passed through the "grouping" argument parameter so to say.
### Tried this
DT[,unique(DT$CLASS):=1,by=ID]

### Got this
ID CLASS a b c
1      a 1 1 1
1      a 1 1 1
1      b 1 1 1
2      c 1 1 1
2      b 1 1 1

I've been struggling with utilizing data.table to its full potential and speed and would like to create the desired output only using commands within data.table arguments.
Can someone help me write the proper code, using only data.table commands/arguments,so that my jth index includes only the unique values, by ID, and sets the appropriate columns to 1?

Follow-up Question:

Say that each row also has an associated date to it, RXDATE, and I'd want to create respective column names of all class values that holds the minimum RXDATE by CLASS by ID. Could I also turn to dcast for this?
### Start with this
ID CLASS a b c RXDATE
1      a 1 1 0 1-1-99
1      a 1 1 0 1-2-99
1      b 1 1 0 1-3-99
2      c 0 1 1 5-4-00
2      b 0 1 1 6-5-01

### Want this
ID CLASS a b c RXDATE   a_DT   b_DT   c_DT
1      a 1 1 0 1-1-99 1-1-99 1-3-99     NA
1      a 1 1 0 1-2-99 1-1-99 1-3-99     NA
1      b 1 1 0 1-3-99 1-1-99 1-3-99     NA
2      c 0 1 1 5-4-00     NA 6-5-01 5-4-00
2      b 0 1 1 6-5-01     NA 6-5-01 5-4-00

A: Using dcast and merge you could also do:
DT <- data.table::data.table(ID=c("1","1","1","2","2"),
                             CLASS=c("a","a","b","c","b"),
                             a=c(0,0,0,0,0),
                             b=c(0,0,0,0,0),
                             c=c(0,0,0,0,0))

# dcast to convert to wide
DT_dcast <- dcast(DT[, .(ID, CLASS)], ID ~ CLASS, fun.aggregate = function(x) length(unique(x)), value.var = "CLASS")
DT_dcast
   ID a b c
1:  1 1 1 0
2:  2 0 1 1

# Then merge with the original data.table
DT_m <- merge(DT[, .(ID, CLASS)], DT_dcast, by = "ID")
DT_m
   ID CLASS a b c
1:  1     a 1 1 0
2:  1     a 1 1 0
3:  1     b 1 1 0
4:  2     c 0 1 1
5:  2     b 0 1 1

EDIT
You could still use the same approach with dcast and merge.
I noticed from your 'start with this' data has different RX date for row 2 and from 'want this' data you only kept '1-1-99' for this.
DT2 <- data.table::data.table(ID=c("1","1","1","2","2"),
                             CLASS=c("a","a","b","c","b"),
                             a=c(0,0,0,0,0),
                             b=c(0,0,0,0,0),
                             c=c(0,0,0,0,0),
                             RXDate = c("1-1-99", "1-2-99", "1-3-99", "5-4-00", "6-5-01"))

# 2nd row from the data provided has different RXDate under same ID and Class.
# Use x[1] to pick first
DT_dcast <- dcast(DT2[, .(ID, CLASS, RXDate)], ID ~ CLASS,
                  fun.aggregate = function(x) x[1],
                  value.var = c("CLASS", "RXDate"))
DT_dcast
   ID CLASS.1_a CLASS.1_b CLASS.1_c RXDate_a RXDate_b RXDate_c
1:  1         a         b      <NA>   1-1-99   1-3-99     <NA>
2:  2      <NA>         b         c     <NA>   6-5-01   5-4-00

# Convert 1 or 0 under CLASS
class_cols <- names(DT_dcast)[grepl("CLASS", names(DT_dcast))]
for (col in class_cols) set(DT_dcast, j = col, value = ifelse(is.na(DT_dcast[[col]]), 0, 1))

DT_dcast
ID CLASS.1_a CLASS.1_b CLASS.1_c RXDate_a RXDate_b RXDate_c
1:  1         1         1         0   1-1-99   1-3-99     <NA>
2:  2         0         1         1     <NA>   6-5-01   5-4-00

# Then merge with the original data.table
DT_m <- merge(DT2[, .(ID, CLASS, RXDate)], DT_dcast, by = "ID")
DT_m

   ID CLASS RXDate CLASS.1_a CLASS.1_b CLASS.1_c RXDate_a RXDate_b RXDate_c
1:  1     a 1-1-99         1         1         0   1-1-99   1-3-99     <NA>
2:  1     a 1-2-99         1         1         0   1-1-99   1-3-99     <NA>
3:  1     b 1-3-99         1         1         0   1-1-99   1-3-99     <NA>
4:  2     c 5-4-00         0         1         1     <NA>   6-5-01   5-4-00
5:  2     b 6-5-01         0         1         1     <NA>   6-5-01   5-4-00

If you want to rename the columns then you can do it using setnames

A: Here's one option.
unique_wide <- dcast(DT[, unique(CLASS), by = ID], ID ~ V1, value.var = "V1")

classes <- setdiff(names(unique_wide), "ID")
unique_wide[, (classes) := lapply(.SD, function(col) { ifelse(is.na(col), 0L, 1L) }),
            .SDcols = classes]

DT[, (classes) := unique_wide[.SD, classes, on = "ID", with = FALSE]]
DT[]
   ID CLASS a b c
1:  1     a 1 1 0
2:  1     a 1 1 0
3:  1     b 1 1 0
4:  2     c 0 1 1
5:  2     b 0 1 1

We first get the possible unique values with DT[, unique(CLASS), by = ID].
Note that you can directly reference columns in j without needing $.
We can reshape that to wide format to get something like this:
   ID    a b    c
1:  1    a b <NA>
2:  2 <NA> b    c

The next 2 lines simply transform values into integers,
setting NA to 0 and 1 otherwise.
> unique_wide
   ID a b c
1:  1 1 1 0
2:  2 0 1 1

Afterwards this idiom is applied,
which is like a nested join.
In this case the join is done based on ID,
so all the rows where it matches between DT and unique_wide have the values of non-ID columns updated with what is present in unique_wide.
Also note that with = FALSE is useful to select columns based on a variable holding a character vector.
BTW, note that you don't even need the initial 0 non-ID columns,
if you declare your table as
DT <- data.table::data.table(ID=c("1","1","1","2","2"),
                             CLASS=c("a","a","b","c","b"))

the code above will still work.

A: Another possible approach:
idx <- DT3[, CJ(I=.I, J=match(unique(CLASS), names(DT))), by=ID]
setDF(DT3)
DT3[as.matrix(idx[, .(I, J)])] <- 1L
setDT(DT3)[]


text:
Q: System.Text.Json serialize/deserialize drawing size and point Moving away from BinaryFormaters, I started to use Text.Json.
I'm trying to serialize/deserialize a simple class containing a dynamic object, named 'PropertyValue'. ' PropertyType' is set by the application. In this sample, PropertyValue is a System.Drawing.Point
Public Class FormSetting
    Public Property FormName As String
    Public Property ControlName As String
    Public Property PropertyName As String
    Public Property PropertyType As String
    Public Property PropertyValue As Object
End Class

Serializer:
Using sw As New IO.StreamWriter(SettingLocation, IO.FileMode.Create)
    Dim jsonString = JsonSerializer.Serialize(SettingList, JsonOptions)
    sw.Write(jsonString)
End Using

Deserialize
Using fs As New IO.FileStream(SettingLocation, IO.FileMode.Open)
   Dim FormSettingResult As FormSetting()
   FormSettingResult = JsonSerializer.Deserialize(Of FormSetting())(fs,LoadSettings.AddRange(FormSettingResult)
End Using

The serialized json looks like:
  {
    "FormName": "UnlockForm",
    "ControlName": "UnlockForm",
    "PropertyName": "Location",
    "PropertyType": "Point",
    "PropertyValue": {
      "X": 304,
      "Y": 243
    }
  }

note that the serialized data doesn't save the original type (point in this case), the deserialized PropertyValue value is:
RootElement = ValueKind = Object : "{
      "X": 304,
      "Y": 243
    }"

and not the expected type Drawing.Point, with valued Point(304,243).
Is there a JSON method to convert ValueKind to a the desired object?
for example using something like (a pseudo) json.ConvertObject:
  dim PointLocation = json.ConvertObject(of Drawing.Point)(item.PropertyValue)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can windows DNS server be configured to return a fully qualified DNS alias? Problem
We have a 3rd party web app installed on a windows server. There is an alias DNS record setup so that user can type in to a web browser the app name i.e. "testapp" and get the site. This works well in Chrome browser but does not work as well with Edge Chromium browser. Edge Chromium does not see the web app as a local server so does not trust it to send domain credentials. In Edge browser users are forced to login each time they use the web app whilst if you use Chrome you are auto logged in. In Edge if you use the fully qualified domain name (FQDN) for the alias  such as "testapp.exampledomain.com" Edge browser see's this as a local network server, trusts it, sends the credentials and auto logs the users in. This behaviour was not seen in previous version of Edge.
Desired outcome
Is there a way to configure windows DNS so that when users type in "testapp" it returns the value "testapp.exampledomain.com" for the user?
Other factors

*

*We have tried editing the web app web server (it is 3rd part and was
using Apache tomcat ) to redirect queries to FQDN address if not from
FQDN address however this is not supported by the vendor and lead to other
issues where users had to reload the page after opening website.

*Edge chromium browser configuration is managed centrally using group
policy and cannot be changed as it will affect other apps.

*Edge chromium is the only supported browser by the organisation with
chrome no longer being installed on new computers so we can no longer
recommend user use chrome.

*Vendor supports Edge chromium but says this issue is a problem with
our network configuration and  will not help any more.

A:
Is there a way to configure windows DNS so that when users type in "testapp" it returns the value "testapp.exampledomain.com" for the user?

No, as this is not a Server-Side setting.
Searching for a name in different DNS zones is a Client-Side "DNS Suffix search" decision. Plain hostnames are never sent to the DNS, so DNS can't do anything about that. Imaging a host "first" and a DNS that has host "first" in it's zone example.com and example2.com - which one should be returned? (The argument "there is just one zone" doesn't count on the internet these days).
You will have to provide a DNS Suffix search list on your clients (which your AD admins will hate you for) or -preferably- just use the FQDN like on any other website. This would make the use of TLS possible, enable the Zone-Model correctly, has no problems with double hostnames ...

A: I was thinking your problem might be internet zones, and trusted sites when I found this article explaining the changes in browser behaviour -
Security Zones in Edge
Your machines are already resolving DNS correctly.
I agree the correct solution was the URL re-write, and would suggest some further pressure on your app vendor or, other than that re-educating your users to use the fully qualified address and / or pushing out updated bookmarks or links to assist them.


text:
Q: Multiple PXE server same subnet I've been struggling with this for some time. I have a few test machines that boot from the network, they receive the boot data from the DHCP server, this tells them who is the boot server where is the file they'll boot etc. However, I need to add a second PXE server in the same subnet (create another Vlan is not an option right now).
I read somewhere that I may be able to send certain parameters to certain machines based on their MAC address (this way choosing what computers boot from what server) however I cannot find how to do this, anyone knows how? this will be my solution but I cannot find the answer.
My DHCP is a windows server 2003
I have 2 servers running custom flavors of Linux server as TFTP servers. Some machines use data to boot from server 1, and the others must bu able to boot from server 2.
Thx
EDIT: I already picked answer but if anyone cares, I didn't use chain loading as proposed, but instead wrote a gPXE script and burn it with ISO image in a CD, I boot from it, the script is executed and the PC is redirected to the server stated in the script this is the script I used.
#!gpxe
dhcp net0
set filename pxelinux.0
set next-server 10.225.83.125   #Server your pointing to
set 210:string http://10.225.83.125/fogimg/  #if http the exact http address
imgfetch pxelinux.0       #name of the img file to fetch
imgload pxelinux.0        #name of the img file to load
boot pxelinux.0           #name of the img file to boot from

A: This is possible if you use gPXE. You configure all hosts to boot using gPXE, then use a server script written in PHP or some such to serve up the appropriate image given a MAC address parameter:
chain http://${next-server}/boot.php?mac=${net0/mac}

is the example given here.
You don't have to burn gPXE into your NICs (although that's certainly a valid option): chainloading works great.
Lastly, the page describing the configuration for your gPXE clients on Win2k3 DHCP is here.

A: We use ISC dhcpd3 on our Linux DHCP server, not Server 2003. But we do have two different netboot environments supported there. PXELinux for Linux installations, and Microsoft Deployment Toolkit 2010 for Windows installations.
So, for example, since we TFTP from the DHCP server, our Linux clients have entries like
host linux-host {hardware ethernet 00:01:02:03:04:05;
                 fixed-address A.B.C.D; filename "pxelinux.0";}

and the Windows clients have entries like
host windows-host {hardware ethernet 00:06:07:08:09:10;
                   fixed-address A.B.C.E; use-host-decl-names on;
                   next-server A.B.C.F; option tftp-server-name "A.B.C.F";
                   option bootfile-name "boot\\x86\\wdsnbp.com";}

This is (I think) the setup that Chopper3 is describing above. Personally, I'm never going back to a Windows DHCP server. We have a Python script that can regenerate our DHCP configuration in seconds so we can switch between boot types as needed.

A: What you're after here is the ability to set BOOTP/DHCP options 66 and 67 based on client MAC. While you can easily set these options globally using the default Windows DHCP service there's no option to make this selective, even using reservations.
I'm also unaware of this ability in other DHCP servers so another possibility would be to set MAC-to-IP reservations on your existing DHCP server (so you know what IPs your machine are on) and use option 66 and 67 to hand out the same boot host and file to every machine but then on the machine that's handing out these boot files have it hand out different files based on source IP - does that make sense?


text:
Q: only that ... or only that's ....? I have never seen the following expression : only that's ….. ( I understand "only that" grammatically instead of "only that's "….. )

'Have you seen her yet?'  he asked.
'Not yet.'
'But you've heard something about her?'
'Only that's she's an expert in her line.'
[Source: From Dashiell Hammett, Red Harvest]

I wonder if this is grammatically correct (common usage) or a kind of dialect used among English-speaking people.
I have searched the similar expression on the Internet. And I found some.
So it doesn't seem to be less frequently used. I would appreciate it if you could give me a piece advice on this. (This is way over my head.)

A: A Google books search for the phrase "she's an expert in her line" turns up five matches for Dashiell Hamemett's Red Harvest, ranging across the years of publication 1965, 1972, 1982, 1999, and 2010. In every case, the line of dialogue is given as

"Only that she's an expert in her line."

A search for the phrase "Only that's she's an expert," on the other hand, yields no matches.
Although the evidence would be even more convincing if Google Books offered a match to a version of the book from closer to 1929, when Red Harvest was first published, I consider it highly likely that the contraction that's in the wording "Only that's she's an expert in her line" is simply a typo for that in the edition that you are reading.

A: I may have watched too many loony toons with the rooster "Foghorn Leghorn" as a kid but this is how that decodes in my head:

'Only, that is, she is an expert in her line.'

So it, I say, it is simply missing a few commas, that is.

A: I've never heard/seen that used before. I've lived in the Northeast U.S., the Southeast, and in Texas, and then the Southeast again. So I've heard a "right many" dialects. :)
I think it's just a typo.
Considering: "Only that's she's an expert in her line."
Literally means: "Only that is she is an expert in her line."
(and that doesn't make any sense... in any dialect)


text: Q: Hold and Continue functionality using Android SIP I am developing a VoIP Android Application using the default Android SIP stack. I am able to make and receive and even hold calls correctly. My problem is when I use the built in hold function holdCall provided by SipAudioCall class and then resume the call using continueCall there is no sound whatsoever between the two phones. I have monitored the logs and made sure that the AudioGroup created when the call starts is setting its mode correctly i.e. when held the AudioGroup sets its mode to 0 (MODE_ON_HOLD) and when resumed it sets its mode to 3 (MODE_ECHO_SUPPRESSION). I have even tried to toggle the mute after resuming the call but still no audio whatsoever.


text:
Q: how to show Persian text received from a web service in C# I'm new to Web Services, but I made one like this:
require_once "lib/nusoap.php";

function welcome($name)
{
   return $name . "خوش آمدید";
}

$server = new soap_server();

$server->configureWSDL("testWebService", "urn:testWebService");

$server->register("welcome",
 array("name" => "xsd:string"),
 array("return" => "xsd:string"),
 "urn:testWebService",
 "urn:testWebService#welcome",
 "rpc",
 "encoded",
 "for user login check");

the "welcome" function returns a string that is partially in the Persian language.
I want to use this web service function in my C# application. I've successfully added the web service to my solution in VS and i tried to use it like this:
MessageBox.Show(myWebsrvice.welcome("Mansoor"));

It runs fine but doesn't show the Persian part of the text correctly. What should I do to fix this?

A: First add this to your php code and check your client side
$server->soap_defencoding = 'UTF-8';
$server->decode_utf8 = false;


text:
Q: Jenkins Kubernetes builds fail with Forbidden (user=system:anonymous, verb=get, resource=nodes, subresource=proxy) Exec Summary
Jenkins is running in a Kubernetes cluster just upgrade to 1.19.7 but now jenkins build scripts are failing when running
sh "kubectl --kubeconfig ${args.config} config use-context ${args.context}"

to give error
io.fabric8.kubernetes.client.KubernetesClientException: Forbidden (user=system:anonymous, verb=get, resource=nodes, subresource=proxy)

but what permissions or roles should I change?
MORE DETAIL HERE
Jenkins is running within a Kubernetes cluster, as a master, and it picks up GIT jobs and then creates slave pods which are also supposed to run in the same cluster.   We have a namespace in the cluster called "Jenkins".    As you use Jenkins to creates builds of the microservice applications which are in their own containers, then prompts to have these deployed through the pipeline of test, demo, production.
The cluster has been updated to Kubernetes 1.19.7 using kops.   Everything still deploys, runs and is accessible as normal.   To the user you would not think that there is a problem to the applications which are running internally on the cluster; all are accessible via the browser and PODS show no significant issues.
Jenkins is still accessible (running version 2.278, with Kubernetes plugin 1.29.1, Kubernetes credential 0.8.0, Kubernetes Client API Plugin 4.13.2-1)
I can log into Jenkins, see everything I would normally expect to see
I can use LENS to connect to the cluster and see all the nodes, pods etc as normal.
However, and this is where our problem now lies post upgrading 1.19.7, when a Jenkins job starts it now always fails at the point which it tries to set the kubectl context
We get this error in every build pipeline at the same place...
    [Pipeline] load
[Pipeline] { (JenkinsUtil.groovy)
[Pipeline] }
[Pipeline] // load
[Pipeline] stage
[Pipeline] { (Set-Up and checks)
[Pipeline] withCredentials
Masking supported pattern matches of $KUBECONFIG or $user or $password
[Pipeline] {
[Pipeline] container
[Pipeline] {
[Pipeline] sh
Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.
         Affected argument(s) used the following variable(s): [KUBECONFIG, user]
         See https://****.io/redirect/groovy-string-interpolation for details.
java.net.ProtocolException: Expected HTTP 101 response but was '403 Forbidden'
    at okhttp3.internal.ws.RealWebSocket.checkResponse(RealWebSocket.java:229)
    at okhttp3.internal.ws.RealWebSocket$2.onResponse(RealWebSocket.java:196)
    at okhttp3.RealCall$AsyncCall.execute(RealCall.java:203)
    at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
[Pipeline] }
[Pipeline] // container
[Pipeline] }
[Pipeline] // withCredentials
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] echo
io.fabric8.kubernetes.client.KubernetesClientException: Forbidden (user=system:anonymous, verb=get, resource=nodes, subresource=proxy)
[Pipeline] }
[Pipeline] // podTemplate
[Pipeline] End of Pipeline
[Bitbucket] Notifying commit build result
[Bitbucket] Build result notified

Now I presume this is about security....but I'm unsure what to change
I can see that it's using system:anonymous and this may have been restricted in later Kubernetes versions, but I'm unsure how to either supply another user or allow this to work from the Jenkins master node in this namespace.
As we run jenkins and also have jenkins deploy I can see the following service accounts
kind: ServiceAccount
apiVersion: v1
metadata:
    name: jenkins
    namespace: jenkins
    selfLink: /api/v1/namespaces/jenkins/serviceaccounts/jenkins
    uid: a81a479a-b525-4b01-be39-4445796c6eb1
    resourceVersion: '94146677'
    creationTimestamp: '2020-08-20T13:32:35Z'
    labels:
        app: jenkins-master
        app.kubernetes.io/managed-by: Helm
        chart: jenkins-acme-2.278.102
        heritage: Helm
        release: jenkins-acme-v2
    annotations:
        meta.helm.sh/release-name: jenkins-acme-v2
        meta.helm.sh/release-namespace: jenkins
secrets:
    - name: jenkins-token-lqgk5

and also
kind: ServiceAccount
apiVersion: v1
metadata:
  name: jenkins-deployer
  namespace: jenkins
  selfLink: /api/v1/namespaces/jenkins/serviceaccounts/jenkins-deployer
  uid: 4442ec9b-9cbd-11e9-a350-06cfb66a82f6
  resourceVersion: '2157387'
  creationTimestamp: '2019-07-02T11:33:51Z'
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: >
      {"apiVersion":"v1","kind":"ServiceAccount","metadata":{"annotations":{},"name":"jenkins-deployer","namespace":"jenkins"}}
secrets:
  - name: jenkins-deployer-token-mdfq9

And the following roles
jenkins-role
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: >
      {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","metadata":{"annotations":{"meta.helm.sh/release-name":"jenkins-acme-v2","meta.helm.sh/release-namespace":"jenkins"},"creationTimestamp":"2020-08-20T13:32:35Z","labels":{"app":"jenkins-master","app.kubernetes.io/managed-by":"Helm","chart":"jenkins-acme-2.278.102","heritage":"Helm","release":"jenkins-acme-v2"},"name":"jenkins-role","namespace":"jenkins","selfLink":"/apis/rbac.authorization.k8s.io/v1/namespaces/jenkins/roles/jenkins-role","uid":"de5431f6-d576-4804-b132-6562d0ba7a94"},"rules":[{"apiGroups":["","extensions"],"resources":["*"],"verbs":["*"]},{"apiGroups":[""],"resources":["nodes"],"verbs":["get","list","watch","update"]}]}
    meta.helm.sh/release-name: jenkins-acme-v2
    meta.helm.sh/release-namespace: jenkins
  creationTimestamp: '2020-08-20T13:32:35Z'
  labels:
    app: jenkins-master
    app.kubernetes.io/managed-by: Helm
    chart: jenkins-acme-2.278.102
    heritage: Helm
    release: jenkins-acme-v2
  name: jenkins-role
  namespace: jenkins
  resourceVersion: '94734324'
  selfLink: /apis/rbac.authorization.k8s.io/v1/namespaces/jenkins/roles/jenkins-role
  uid: de5431f6-d576-4804-b132-6562d0ba7a94
rules:
  - apiGroups:
      - ''
      - extensions
    resources:
      - '*'
    verbs:
      - '*'
  - apiGroups:
      - ''
    resources:
      - nodes
    verbs:
      - get
      - list
      - watch
      - update

jenkins-deployer-role
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: jenkins-deployer-role
  namespace: jenkins
  selfLink: >-
    /apis/rbac.authorization.k8s.io/v1/namespaces/jenkins/roles/jenkins-deployer-role
  uid: 87b6486e-6576-11e8-92a9-06bdf97be268
  resourceVersion: '94731699'
  creationTimestamp: '2018-06-01T08:33:59Z'
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: >
      {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","metadata":{"annotations":{},"creationTimestamp":"2018-06-01T08:33:59Z","name":"jenkins-deployer-role","namespace":"jenkins","selfLink":"/apis/rbac.authorization.k8s.io/v1/namespaces/jenkins/roles/jenkins-deployer-role","uid":"87b6486e-6576-11e8-92a9-06bdf97be268"},"rules":[{"apiGroups":[""],"resources":["pods"],"verbs":["*"]},{"apiGroups":[""],"resources":["deployments","services"],"verbs":["*"]}]}
rules:
  - verbs:
      - '*'
    apiGroups:
      - ''
    resources:
      - pods
  - verbs:
      - '*'
    apiGroups:
      - ''
    resources:
      - deployments
      - services

and jenkins-namespace-manager
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: jenkins-namespace-manager
  selfLink: /apis/rbac.authorization.k8s.io/v1/clusterroles/jenkins-namespace-manager
  uid: 93e80d54-6346-11e8-92a9-06bdf97be268
  resourceVersion: '94733699'
  creationTimestamp: '2018-05-29T13:45:41Z'
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: >
      {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"ClusterRole","metadata":{"annotations":{},"creationTimestamp":"2018-05-29T13:45:41Z","name":"jenkins-namespace-manager","selfLink":"/apis/rbac.authorization.k8s.io/v1/clusterroles/jenkins-namespace-manager","uid":"93e80d54-6346-11e8-92a9-06bdf97be268"},"rules":[{"apiGroups":[""],"resources":["namespaces"],"verbs":["get","watch","list","create"]},{"apiGroups":[""],"resources":["nodes"],"verbs":["get","list","watch","update"]}]}
rules:
  - verbs:
      - get
      - watch
      - list
      - create
    apiGroups:
      - ''
    resources:
      - namespaces
  - verbs:
      - get
      - list
      - watch
      - update
    apiGroups:
      - ''
    resources:
      - nodes

and finally jenkins-deployer-role
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: >
      {"apiVersion":"rbac.authorization.k8s.io/v1","kind":"ClusterRole","metadata":{"annotations":{},"creationTimestamp":"2018-05-29T13:29:43Z","name":"jenkins-deployer-role","selfLink":"/apis/rbac.authorization.k8s.io/v1/clusterroles/jenkins-deployer-role","uid":"58e1912e-6344-11e8-92a9-06bdf97be268"},"rules":[{"apiGroups":["","extensions","apps","rbac.authorization.k8s.io"],"resources":["*"],"verbs":["*"]},{"apiGroups":["policy"],"resources":["poddisruptionbudgets","podsecuritypolicies"],"verbs":["create","delete","deletecollection","patch","update","use","get"]},{"apiGroups":["","extensions","apps","rbac.authorization.k8s.io"],"resources":["nodes"],"verbs":["get","list","watch","update"]}]}
  creationTimestamp: '2018-05-29T13:29:43Z'
  name: jenkins-deployer-role
  resourceVersion: '94736572'
  selfLink: /apis/rbac.authorization.k8s.io/v1/clusterroles/jenkins-deployer-role
  uid: 58e1912e-6344-11e8-92a9-06bdf97be268
rules:
  - apiGroups:
      - ''
      - extensions
      - apps
      - rbac.authorization.k8s.io
    resources:
      - '*'
    verbs:
      - '*'
  - apiGroups:
      - policy
    resources:
      - poddisruptionbudgets
      - podsecuritypolicies
    verbs:
      - create
      - delete
      - deletecollection
      - patch
      - update
      - use
      - get
  - apiGroups:
      - ''
      - extensions
      - apps
      - rbac.authorization.k8s.io
    resources:
      - nodes
    verbs:
      - get
      - list
      - watch
      - update

And the following bindings..
Kubernetes bindings
I'm really stuck with this one, I don't want to give system:anonymous access to everything, although guess that could be an option.
The jenkins files which help build this are
JenkinsFile
import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException

def label = "worker-${UUID.randomUUID().toString()}"
def dockerRegistry = "id.dkr.ecr.eu-west-1.amazonaws.com"
def localHelmRepository = "acme-helm"
def artifactoryHelmRepository = "https://acme.jfrog.io/acme/$localHelmRepository"
def jenkinsContext = "jenkins-staging"

def MAJOR = 2 // Change HERE
def MINOR = 278 // Change HERE
def PATCH = BUILD_NUMBER

def chartVersion = "X.X.X"
def name = "jenkins-acme"
def projectName = "$name"
def helmPackageName = "$projectName"
def helmReleaseName = "$name-v$MAJOR"
def fullVersion = "$MAJOR.$MINOR.$PATCH"
def jenkinsVersion = "${MAJOR}.${MINOR}" // Gets passed to Dockerfile for getting image from Docker hub

podTemplate(label: label, containers: [
        containerTemplate(name: 'docker', image: 'docker:18.05-dind', ttyEnabled: true, privileged: true),
        containerTemplate(name: 'perl', image: 'perl', ttyEnabled: true, command: 'cat'),
        containerTemplate(name: 'kubectl', image: 'lachlanevenson/k8s-kubectl:v1.18.8', command: 'cat', ttyEnabled: true),
        containerTemplate(name: 'helm', image: 'id.dkr.ecr.eu-west-1.amazonaws.com/k8s-helm:3.2.0', command: 'cat', ttyEnabled: true),
        containerTemplate(name: 'clair-local-scan', image: '738398925563.dkr.ecr.eu-west-1.amazonaws.com/clair-local-scan:latest', ttyEnabled: true, envVars: [envVar(key: 'DOCKER_HOST', value: 'tcp://localhost:2375')]),
        containerTemplate(name: 'clair-scanner', image: '738398925563.dkr.ecr.eu-west-1.amazonaws.com/clair-scanner:latest', command: 'cat', ttyEnabled: true, envVars: [envVar(key: 'DOCKER_HOST', value: 'tcp://localhost:2375')]),
        containerTemplate(name: 'clair-db', image: "738398925563.dkr.ecr.eu-west-1.amazonaws.com/clair-db:latest", ttyEnabled: true),
        containerTemplate(name: 'aws-cli', image: 'mesosphere/aws-cli', command: 'cat', ttyEnabled: true)
], volumes: [
        emptyDirVolume(mountPath: '/var/lib/docker')
]) {

    try {

        node(label) {
            def myRepo = checkout scm
            jenkinsUtils = load 'JenkinsUtil.groovy'

            stage('Set-Up and checks') {
                jenkinsContext = 'jenkins-staging'
                withCredentials([

                                 file(credentialsId: 'kubeclt-staging-config', variable: 'KUBECONFIG'),
                                 usernamePassword(credentialsId: 'jenkins_artifactory', usernameVariable: 'user', passwordVariable: 'password')]) {

                    jenkinsUtils.initKubectl(jenkinsUtils.appendToParams("kubectl", [
                            namespaces: ["jenkins"],
                            context   : jenkinsContext,
                            config    : KUBECONFIG])
                    )
                    jenkinsUtils.initHelm(jenkinsUtils.appendToParams("helm", [
                            namespace  : "jenkins",
                            helmRepo   : artifactoryHelmRepository,
                            username   : user,
                            password   : password,

                            ])
                    )
                }
            }

            stage('docker build and push') {
                container('perl'){
                    def JENKINS_HOST = "jenkins_api:1Ft38erDFjjfM6q3a6y7@jenkins.acme.com"
                    sh "curl -sSL \"https://${JENKINS_HOST}/pluginManager/api/xml?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins\" | perl -pe 's/.*?<shortName>([\\w-]+).*?<version>([^<]+)()(<\\/\\w+>)+/\\1 \\2\\n/g'|sed 's/ /:/' > plugins.txt"
                    sh "cat plugins.txt"

                }

                container('docker'){
                    sh "ls -la"
                    sh "docker version"
                    // This is because of this annoying "feature" where the command ran from docker contains a \r character which must be removed
                    sh 'eval $(docker run --rm -t $(tty &>/dev/null && echo "-n") -v "$(pwd):/project" mesosphere/aws-cli ecr get-login --no-include-email --region eu-west-1 | tr \'\\r\' \' \')'

                    sh "sed \"s/JENKINS_VERSION/${jenkinsVersion}/g\" Dockerfile > Dockerfile.modified"
                    sh "cat Dockerfile.modified"
                    sh "docker build -t $name:$fullVersion -f Dockerfile.modified ."
                    sh "docker tag $name:$fullVersion $dockerRegistry/$name:$fullVersion"
                    sh "docker tag $name:$fullVersion $dockerRegistry/$name:latest"
                    sh "docker tag $name:$fullVersion $dockerRegistry/$name:${MAJOR}"
                    sh "docker tag $name:$fullVersion $dockerRegistry/$name:${MAJOR}.$MINOR"
                    sh "docker tag $name:$fullVersion $dockerRegistry/$name:${MAJOR}.${MINOR}.$PATCH"

                    sh "docker push $dockerRegistry/$name:$fullVersion"
                    sh "docker push $dockerRegistry/$name:latest"
                    sh "docker push $dockerRegistry/$name:${MAJOR}"
                    sh "docker push $dockerRegistry/$name:${MAJOR}.$MINOR"
                    sh "docker push $dockerRegistry/$name:${MAJOR}.${MINOR}.$PATCH"

                }
            }

            stage('helm build') {
                namespace = 'jenkins'
                jenkinsContext = 'jenkins-staging'
                withCredentials([
                                 file(credentialsId: 'kubeclt-staging-config', variable: 'KUBECONFIG'),
                                 usernamePassword(credentialsId: 'jenkins_artifactory', usernameVariable: 'user', passwordVariable: 'password')]) {

                    jenkinsUtils.setContext(jenkinsUtils.appendToParams("kubectl", [
                            context: jenkinsContext,
                            config : KUBECONFIG])
                    )

                    jenkinsUtils.helmDeploy(jenkinsUtils.appendToParams("helm", [
                            namespace  : namespace,
                            credentials: true,
                            release    : helmReleaseName,
                            args       : [replicaCount        : 1,
                                          imageTag            : fullVersion,
                                          namespace           : namespace,
                                          "MajorVersion"      : MAJOR]])
                    )

                    jenkinsUtils.helmPush(jenkinsUtils.appendToParams("helm", [
                            helmRepo   : artifactoryHelmRepository,
                            username   : user,
                            password   : password,
                            BuildInfo  : BRANCH_NAME,
                            Commit     : "${myRepo.GIT_COMMIT}"[0..6],
                            fullVersion: fullVersion
                    ]))
                }
            }

            stage('Deployment') {
                namespace = 'jenkins'
                jenkinsContext = 'jenkins-staging'
                withCredentials([

                                 file(credentialsId: 'kubeclt-staging-config', variable: 'KUBECONFIG')]) {
                    jenkinsUtils.setContext(jenkinsUtils.appendToParams("kubectl", [
                            context: jenkinsContext,
                            config : KUBECONFIG])
                    )

                    jenkinsUtils.helmDeploy(jenkinsUtils.appendToParams("helm", [
                            dryRun     : false,
                            namespace  : namespace,
                            package    : "${localHelmRepository}/${helmPackageName}",
                            credentials: true,

                            release    : helmReleaseName,
                            args       : [replicaCount        : 1,
                                          imageTag            : fullVersion,
                                          namespace           : namespace,
                                          "MajorVersion"      : MAJOR
                                          ]
                                        ])
                    )
                }
            }
        }
    } catch (FlowInterruptedException e) {
        def reasons = e.getCauses().collect { it.getShortDescription() }.join(",")
        println "Interupted. Reason: $reasons"
        currentBuild.result = 'SUCCESS'
        return
    } catch (error) {
        println error
        throw error
    }
}

And the groovy file
templateMap = [
        "helm"   : [
                containerName: "helm",
                dryRun       : true,
                namespace    : "test",
                tag          : "xx",
                package      : "jenkins-acme",
                credentials  : false,
                ca_cert      : null,
                helm_cert    : null,
                helm_key     : null,
                args         : [
                majorVersion : 0,
                replicaCount : 1
                ]
        ],
        "kubectl": [
                containerName: "kubectl",
                context      : null,
                config       : null,
        ]
]

def appendToParams(String templateName, Map newArgs) {
    def copyTemplate = templateMap[templateName].clone()
    newArgs.each { paramName, paramValue ->
        if (paramName.equalsIgnoreCase("args"))
            newArgs[paramName].each {
                name, value -> copyTemplate[paramName][name] = value
            }
        else
            copyTemplate[paramName] = paramValue
    }
    return copyTemplate
}

def setContext(Map args) {
    container(args.containerName) {
        sh "kubectl --kubeconfig ${args.config} config use-context ${args.context}"
    }
}

def initKubectl(Map args) {
    container(args.containerName) {
        sh "kubectl --kubeconfig ${args.config} config use-context ${args.context}"

        for (namespace in args.namespaces)
            sh "kubectl -n $namespace get pods"
    }
}

def initHelm(Map args) {
    container(args.containerName) {
//        sh "helm init --client-only"

        def command = "helm version --short"
//        if (args.credentials)
//            command = "$command --tls --tls-ca-cert ${args.ca_cert} --tls-cert ${args.helm_cert} --tls-key ${args.helm_key}"
//
//        sh "$command  --tiller-connection-timeout 5 --tiller-namespace tiller-${args.namespace}"

        sh "helm repo add acme-helm ${args.helmRepo} --username ${args.username} --password ${args.password}"
        sh "helm repo update"
    }
}

def helmDeploy(Map args) {
    container(args.containerName) {

        sh "helm repo update"

        def command = "helm upgrade"

//        if (args.credentials)
//            command = "$command --tls --tls-ca-cert ${args.ca_cert} --tls-cert ${args.helm_cert} --tls-key ${args.helm_key}"

        if (args.dryRun) {
            sh "helm lint ${args.package}"
            command = "$command --dry-run --debug"
        }

//        command = "$command --install --tiller-namespace tiller-${args.namespace} --namespace ${args.namespace}"
        command = "$command --install --namespace ${args.namespace}"

        def setVar = "--set "
        args.args.each { key, value -> setVar = "$setVar$key=\"${value.toString().replace(",", "\\,")}\"," }
        setVar = setVar[0..-1]

        sh "$command $setVar --devel ${args.release} ${args.package}"
    }
}

def helmPush(Map args){
    container(args.containerName) {
        sh "helm package ${args.package} --version ${args.fullVersion} --app-version ${args.fullVersion}+${args.BuildInfo}-${args.Commit}"
        sh "curl -u${args.username}:${args.password} -T ${args.package}-${args.fullVersion}.tgz \"${args.helmRepo}/${args.package}-${args.fullVersion}.tgz\""
    }
}

return this

And from the log it seems to be when it runs
sh "kubectl --kubeconfig ${args.config} config use-context ${args.context}"

That it throws the error
io.fabric8.kubernetes.client.KubernetesClientException: Forbidden (user=system:anonymous, verb=get, resource=nodes, subresource=proxy)

but what permissions or roles should I change?
Many thanks,
Nick

A: Take a look at this section of the official kubernetes documentation and this answer provided by Prafull Ladha:

The above error means your apiserver doesn't have the credentials
(kubelet cert and key) to authenticate the kubelet's log/exec
commands and hence the  Forbidden  error message.
You need to provide  --kubelet-client-certificate=<path_to_cert>
and  --kubelet-client-key=<path_to_key>  to your apiserver, this way
apiserver authenticate the kubelet with the certficate and key pair.

Very similar issue was also reported on GitHub in this thread, where you can find the following explanation:

That means the api server has not been given a credential to use to
authenticate to kubelets when proxying log/exec requests.
See apiserver configuration as described in
https://kubernetes.io/docs/admin/kubelet-authentication-authorization/#kubelet-authentication


text:
Q: Открытие нового окна через кнопку При запуске не открывается новое окно.
main.py:
from PyQt5 import QtCore, QtGui, QtWidgets
from test import Ui_Test

class Ui_Login(object):
    def setupUi(self, Login):
        Login.setObjectName("Login")
        Login.resize(1100, 800)
        Login.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.centralwidget = QtWidgets.QWidget(Login)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(280, 120, 581, 41))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
        self.label.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.label.setFont(font)
        self.label.setStyleSheet("background-color: rgb(198, 212, 255);")
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(490, 440, 141, 71))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
        self.pushButton.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("background-color: rgb(198, 212, 255);")
        self.pushButton.setObjectName("pushButton")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(480, 310, 141, 31))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_3.sizePolicy().hasHeightForWidth())
        self.label_3.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("background-color: rgb(198, 212, 255);")
        self.label_3.setObjectName("label_3")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(520, 190, 61, 41))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_2.sizePolicy().hasHeightForWidth())
        self.label_2.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("background-color: rgb(198, 212, 255);")
        self.label_2.setObjectName("label_2")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(380, 260, 331, 31))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth())
        self.lineEdit_2.setSizePolicy(sizePolicy)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setGeometry(QtCore.QRect(380, 360, 331, 31))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit_3.sizePolicy().hasHeightForWidth())
        self.lineEdit_3.setSizePolicy(sizePolicy)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(-4, -8, 1111, 811))
        self.label_4.setAutoFillBackground(False)
        self.label_4.setText("")
        self.label_4.setPixmap(QtGui.QPixmap("images2.jpg"))
        self.label_4.setScaledContents(True)
        self.label_4.setObjectName("label_4")
        self.label_4.raise_()
        self.label.raise_()
        self.pushButton.raise_()
        self.label_3.raise_()
        self.label_2.raise_()
        self.lineEdit_2.raise_()
        self.lineEdit_3.raise_()
        Login.setCentralWidget(self.centralwidget)

        self.retranslateUi(Login)
        QtCore.QMetaObject.connectSlotsByName(Login)

        def opentest():
                global test
                test = QtWidgets.QMainWindow()
                ui = Ui_Test()
                ui.setupUi(test)
                Login.close()
                test.show()
        self.pushButton.clicked.connect(opentest)

    def retranslateUi(self, Login):
        _translate = QtCore.QCoreApplication.translate
        Login.setWindowTitle(_translate("Login", "Авторизация"))
        self.label.setText(_translate("Login", "
Для прохождения теста необходимо заполнить ФИО и номер группы
"))
        self.pushButton.setText(_translate("Login", "Продолжить"))
        self.label_3.setText(_translate("Login", "
Номер группы
"))
        self.label_2.setText(_translate("Login", "
ФИО
"))

test.py :

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Test(object):
    def setupUi(self, Test):
        Test.setObjectName("Test")
        Test.resize(1100, 800)
        Test.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.centralwidget = QtWidgets.QWidget(Test)
        self.centralwidget.setObjectName("centralwidget")
        Test.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(Test)
        self.statusbar.setObjectName("statusbar")
        Test.setStatusBar(self.statusbar)
        self.menubar = QtWidgets.QMenuBar(Test)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1100, 21))
        self.menubar.setObjectName("menubar")
        Test.setMenuBar(self.menubar)

        self.retranslateUi(Test)
        QtCore.QMetaObject.connectSlotsByName(Test)

    def retranslateUi(self, Test):
        _translate = QtCore.QCoreApplication.translate
        Test.setWindowTitle(_translate("Test", "Тест"))

A: НИКОГДА НЕ ИЗМЕНЯЙТЕ код, сгенерированный Qt Designer, НИКОГДА.
Создайте другой класс, который наследуется от соответствующего виджета, и используйте созданный класс для его заполнения.
q1419969_main.py
from PyQt5 import QtCore, QtGui, QtWidgets
from q1419969_test import Ui_Test

class Ui_Login(object):
    def setupUi(self, Login):
        Login.setObjectName("Login")
        Login.resize(1100, 600)
        Login.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.centralwidget = QtWidgets.QWidget(Login)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(280, 120, 581, 41))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
        self.label.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.label.setFont(font)
        self.label.setStyleSheet("background-color: rgb(198, 212, 255);")
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(490, 440, 141, 71))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
        self.pushButton.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("background-color: rgb(198, 212, 255);")
        self.pushButton.setObjectName("pushButton")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(480, 310, 141, 31))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_3.sizePolicy().hasHeightForWidth())
        self.label_3.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("background-color: rgb(198, 212, 255);")
        self.label_3.setObjectName("label_3")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(520, 190, 61, 41))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_2.sizePolicy().hasHeightForWidth())
        self.label_2.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("background-color: rgb(198, 212, 255);")
        self.label_2.setObjectName("label_2")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(380, 260, 331, 31))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth())
        self.lineEdit_2.setSizePolicy(sizePolicy)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setGeometry(QtCore.QRect(380, 360, 331, 31))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit_3.sizePolicy().hasHeightForWidth())
        self.lineEdit_3.setSizePolicy(sizePolicy)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(-4, -8, 1111, 811))
        self.label_4.setAutoFillBackground(False)
        self.label_4.setText("")
        self.label_4.setPixmap(QtGui.QPixmap("images2.jpg"))
        self.label_4.setScaledContents(True)
        self.label_4.setObjectName("label_4")
        self.label_4.raise_()
        self.label.raise_()
        self.pushButton.raise_()
        self.label_3.raise_()
        self.label_2.raise_()
        self.lineEdit_2.raise_()
        self.lineEdit_3.raise_()
        Login.setCentralWidget(self.centralwidget)

        self.retranslateUi(Login)
        QtCore.QMetaObject.connectSlotsByName(Login)

    def retranslateUi(self, Login):
        _translate = QtCore.QCoreApplication.translate
        Login.setWindowTitle(_translate("Login", "Авторизация"))
        self.label.setText(_translate("Login", "
Для прохождения теста необходимо заполнить ФИО и номер группы
"))
        self.pushButton.setText(_translate("Login", "Продолжить"))
        self.label_3.setText(_translate("Login", "
Номер группы
"))
        self.label_2.setText(_translate("Login", "
ФИО
"))

class TestWindow(QtWidgets.QMainWindow, Ui_Test):
    def __init__(self):
        super(TestWindow, self).__init__()
        self.setupUi(self)

class MainWindow(QtWidgets.QMainWindow, Ui_Login):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

        self.pushButton.clicked.connect(self.opentest)

    def opentest(self):
        self.test = TestWindow()
        self.test.show()
        self.hide()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

q1419969_test.py
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Test(object):
    def setupUi(self, Test):
        Test.setObjectName("Test")
        Test.resize(1100, 800)
        Test.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.centralwidget = QtWidgets.QWidget(Test)
        self.centralwidget.setObjectName("centralwidget")
        Test.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(Test)
        self.statusbar.setObjectName("statusbar")
        Test.setStatusBar(self.statusbar)
        self.menubar = QtWidgets.QMenuBar(Test)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1100, 21))
        self.menubar.setObjectName("menubar")
        Test.setMenuBar(self.menubar)

        self.retranslateUi(Test)
        QtCore.QMetaObject.connectSlotsByName(Test)

    def retranslateUi(self, Test):
        _translate = QtCore.QCoreApplication.translate
        Test.setWindowTitle(_translate("Test", "Тест"))


text:
Q: SQL: Selecting from multiple tables in one query or a query for each table? A follow up question concerning the DAL layer part .. The first question about dealing with large objects
I have one table (PlacesTable) that is connected by like 6 other tables (1:Many and Many:Many relations)
In my DAL should I put a big query that join the 6 tables + the m:m reference tables (btw it produces multiple data that I don't need  Please refer to my old question) and place all the data in it's specific object property or, should I use a single query for each table and create an object for each fetched table .. and finally send those to the UI ?
If I wasn't clear enough please let me know what I further information do you need to know!
Thanks in advance for your time and help =)

A: If one big query gives too much duplicate data, and 6 round trips are slow... some options

*

*Use a stored proc to return 6 recordsets in one DB call

*Do some joins on the server to reduce both duplicate data and roundtrips

*

*do both

Have you any performance differences yet? Or is this guess driven optimization?

A: Your question seems to be about whether you should load related entities into your Places object. It sounds like you've got a few classes in your model, which is a great start.
Load only the data you require. Consider your consumer(in this case, the UI). Do you need to display this data? Only query for the data you need. Build multiple methods in your DAL to ensure that the right data is loaded at the time. i.e. GetPlacesSummary() returns your data shaped one way, while GetDetailedPlaces() returns a more granular data set.
Look into a data access component that supports lazy loading. This means that only when you access those properties (like Customer.Invoices.Count) will the data actually be queried from the database.

A: You are better off with a single query returning all the information required for the UI.
Each database connection will be slow and you will have to wait for all of them to finish before having your data ready for the UI.
The slowest thing between the application and the SQL server is the act of establishing connections - the less of them, the better.

A: In general, the database performs much better at joining data from several tables than other technologies. You will get better performance if you make one query than if you make several queries. You will also get the added benefit of not having to have a one-to-one relationship between your tables and your objects.


text:
Q: Kibana меняеть временную зону
Принимаю данные через xml фильтр все даты Logstash принимает все правильно но когда дело доходит до Kibana он меняеть временную зону
Мой config для Logstash
 input {
  http_poller {
    urls => {
        soap_request => {
                    method => post
                    url => "###"
        headers => {
                    "Content-Type" => "text/xml; charset=utf-8"
                    "SOAPAction" => "###"
                    }
                        body => 'request'
                    }
              }
    schedule => { cron => "*/1 * * * * UTC"}
            request_timeout => 60
            codec => multiline {
            pattern => "<m:Document>"
            negate => "true"
            what => "previous"
                                }
             }
       }
filter {
     xml {source => "message"
        store_xml => false
         remove_namespaces => "true"
         xpath => [
            "/Document/Number/text()", "number",
            "/Document/Name/text()", "name",
            "/Document/DataRegistration/text()", "dataregistration"
                   ]
          }

        }
output {
    elasticsearch {
        hosts => ['localhost:9200']
        index => "sdasu2"
        document_type => "calls2"
        document_id=>"%{number}"
                  }
    stdout {
        codec => rubydebug
            }
       }

A: Проблема заключается в часовом поясе. По умолчанию Kibana работает в UTC. Проверьте, совпадает ли часовой пояс в ваших документах ES с часовым поясом Кибаны.
Management Tab ->Advance Settings ->dateFormat:tz
Плюс посмотрите эту дискуссию


text:
Q: ¿Es posible parar la ejecución del código en cliente hasta la finalización de onloadend necesitaría que se ejecutase el código del reader.onloadend con su llamada ajax antes de continuar con la ejecución, este es mi código:
var reader = new FileReader();
reader.readAsDataURL($("#fuAdjuntos")[0].files[0]);
reader.onloadend = function (evt) {
    if (evt.target.readyState == FileReader.DONE) {
        var base64reader = evt.target.result.split("base64,")[1];
        nameAdjunto = $('#fuAdjuntos')[0].files[0].name;
        msg = nameAdjunto;
        $.ajax({
            type: "POST",
            url: 'Chat.aspx/SubirAdjunto',
            data: '{base64reader: "' + base64reader + '",idUsuario: "' + idUsuario + '",nameAdjunto: "' + nameAdjunto + '" }',
            processData: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (response) {
            },
            failure: function (response) {
                alert(response.d);
            }
        });
    }
}

 msg = msg.replace("<", "< ");
 var userName = $('#hdUserName').val();
 var date = GetCurrentDateTime(new Date());
 var usuarioEnvio = usuarioChatSeleccionado;
 if ((usuarioEnvio == null || usuarioEnvio == '') && grupoDestinatarioChat == null) {
 chatHub.server.sendMessageToAll(userName, msg, date, idUsuario, $('#hdId').val(), null, esAdjunto);
                }

El problema es que continúa con la ejecución y finalmente ejecuta el contenido del evento reader.onloadend.
¿Sería posible? (He probado poniendo un "timer", pero al acabar sigue con la ejecución y deja para el final el reader).
Muchas gracias.

A: Me estaba liando un poco, se ha resuelto copiando ese código en el success de la llamada ajax y un else también para ese código. Gracias!!!


text:
Q: Different ways to implement 'dirty'-flag functionality Almost every programmer did it once in his life: setting some flag if a variable's value changed. There's always lots of properties and you want to keep track if something changed

*

*in any property

*in a specific property

*or in some set of properties

I'm interested in different ways to implement the "dirty-flag" functionality for the above situations, besides the standard object wide dirty flag being updated on each property change. There must be something better than putting "dirty = true" in each setter: it just looks ugly and is a tedious work.

A: I've created a class called DirtyValue<T>  which has an original value and a current value.  On its first use it sets both the original value and the current value.  Successive calls only set the current value.
You can tell if it has changed by comparing the two, with a readonly bool property called IsDirty().  Using this technique you can also get access to the original value as well.

A: If you are setting a "dirty" flag realize that you are keeping state. At some point you need to take an action based on that state, otherwise you wouldn't need to keep the flag. So the question then becomes: is there another way to trigger the needed action? Sending messages of some kind? Who consumes the "dirty" state and takes action, and is there a cleaner interface for that notification?

A: In some situations with a data writer task and an independent reader task,  I've given each task an updateCount variable.    The producer increments its count whenever it writes.  Whenever the reader wakes up and finds its count less than the producer's count, it does an update with the current values.  You need a little special handling for counter overflow, but this is pretty simple to implement.
I've successfully used this technique in simulations - where the producer is the physics loop and the reader is the 3d display.

A: I would put changed() in each setter, i.e. call a private method instead of just changing a flag. The method may then set a flag or do whatever processing is needed, e.g. it could also notify any observers.

A: For my DAO I keep a copy of the original values as retrieved from the database. When I send it to be updated, I simply compare the original values with the current. It costs a little in processing but it is a lot better than having a dirty flag per property.
EDIT to further justify not having a dirty flag: if the property returns to its original value, there is no way to reflect that, the dirty flag continues dirty because the original value was lost.

A: An interesting alternative to the explicit dirty=true approach, although it is probably overkill for most situations and often not applicable, would be to use guard pages. Set the memory page as read-only (e.g. with VirtualProtect() on Windows) and catch the signal/exception when the program tries to write to the page. Make a record that the page has been modified, then change the protection flags of the page to writable and resume execution.
This is the technique usually employed by operating systems to determine whether a page needs to be written to the swap file before it is evicted from RAM.

A: I used to have a base Entity class, providing Dirty/Removed Logic.
When writing Entity-subclasses, you could do something like:
public string Name
{
    get { return name; }
    set { setValue("Name", value); }
}

This works fine, but has the 'ugly string' disease...
Today you can use Lambda Expressions to exclude the strings:
set {setValue(x => x.Name, value);}

Or, and I think that this is the best solution, you could use AOP:
https://www.postsharp.net/
This way, you can define actions by Attributes. You create an attribute and specify that when the user changes the associated property, the entity becomes dirty.
Additionally, you can keep a list of properties in your class (base Entity) which will remember the changed properties, and access that list from your AOP Code.

A: You may want to look at overriding the gethashcode and equals methods of your domain objects and storing the original hashcodes in a hashtable by object key. Then create a process that takes an object, find its key in the hashtable and compares hash values.

*

*If hash same, no change. (do not send to repository or database)

*if hash different, object has changes. (update)

*If key not found, object is new. (insert)

*Not sure how to determine if object needs to be deleted other than process delete on request and not using hashcode tracking for them.

I have not tried this and a hashtable may not be the best way to track object keys/hash values. It would save mem by tracking only hash codes and keys only. I am not 100% sure, but I think some orm's may use this method in their data context/tracking objects.


text:
Q: What are the necessary settings for "git configuration"? when I create a project in Xcode 4.3 it keeps on displaying message saying below.I did not get what that means and how to do the necessary settings.
Any help will be greatly appreciated.
Thanks
Baha
Please tell me who you are
Run
git config --global user.email
"you@example.com"
git.config --global user.name"Your
Name"
to set your account's default identity.
Omit --global to say the identity only in
this repository.
fatal:unable to auto-detect email address
(got 'Home@s-imac-3.(none)")`

A: It's telling you literally, exactly what to do.  Open a Terminal session, and run this,  replacing 'you@example.com' with your email address:
git config --global user.email "you@example.com"

This sets your email address for git, it uses this to identify who you are in commits.
Then, run this, replacing 'Your Name' with your name:
git config --global user.name "Your Name"

This sets your name for git commit messages, it uses this to give a more readable name to commits.
If this stuff is not clear to you, you really owe it to yourself to learn git: http://try.github.io

A: Set Name & Email in Xcode preference, this issue will be resolve
Follow these 4 simple steps

*

*Xcode => Preferences => Source control  => Git

*Set ( Author Name ) &  ( Author Email ), just for identify that the code committed by this name/email

*close Xcode and re-open project

*now try to commit code, it should be working fine now.

A: Could be a issue with Xcode. Go to your git directory and set the user locally. See the following help thread at Apple Forum for more info:
https://forums.developer.apple.com/thread/18189

A: I had same issue in xCode 8.3.2, when I tried to create git repository on local machine. And I fixed it by setting local repository name and email. If anyone is having same issue; just run these commands in terminal:

*

*cd my/project/directory (Navigate to project directory)

*git config --local user.email "me@me.com"

*git config --local user.name "myname"

NOTE: This is for local repository, and "--global" flah can be used for remote repositories.


text:
Q: For loop setup with multiple parameters in R I'm trying to figure out how to get a for loop setup in R when I want it to run two or more parameters at once. Below I have posted a sample code where I am able to get the code to run and fill a matrix table with two values. In the 2nd line of the for loop I have
R<-ARMA.var(length(x_global_sample),ar=c(tt[i],-.7))

And what I would like to do is replace the -.7 with another tt[i], example below, so that my for loop would run through the values starting at (-1,-1), then it would be as follows (-1,-.99),
(-1,-.98),...,(1,.98),(1,.99),(1,1) where the result matrix would then be populated by the output of Q and sigma.
R<-ARMA.var(length(x_global_sample),ar=c(tt[i],tt[i]))

or something similar to
R<-ARMA.var(length(x_global_sample),ar=c(tt[i],ss[i]))

It may be very possible that this would be better handled by two for loops however I'm not 100% sure on how I would set that up so the first parameter would be fixed and the code would run through the sequence of the second parameter, once that would get finished the first parameter would now increase by one and fix itself at that increase until the second parameter does another run through.
I've posted some sample code down below where the ARMA.var function just comes from the ts.extend package. However, any insight into this would be great.
Thank you
tt<-seq(-1,1,0.01)
Result<-matrix(NA, nrow=length(tt)*length(tt), ncol=2)
for (i in seq_along(tt)){
R<-ARMA.var(length(x_global_sample),ar=c(tt[i],-.7))
Q<-t((y-X%*%beta_est_d))%*%solve(R)%*%(y-X%*%beta_est_d)+
  lam*t(beta_est_d)%*%D%*%beta_est_d
RSS<-sum((y-X%*%solve(t(X)%*%solve(R)%*%X+lam*D)%*%t(X)%*%solve(R)%*%y)^2)
Denom<-n-sum(diag(X%*%solve(t(X)%*%solve(R)%*%X+lam*D)%*%t(X)%*%solve(R)))
sigma<-RSS/Denom
Result[i,1]<-Q
Result[i,2]<-sigma
rm(Q)
rm(R)
rm(sigma)
}

Edit: I realize that what I have posted above is quite unclear so to simplify things consider the following code,
x<-seq(1,20,1)
y<-seq(1,20,2)
Result<-matrix(NA, nrow=length(x)*length(y), ncol=2)

for(i in seq_along(x)){
  z1<-x[i]+y[i]
  z2<-z1+y[i]
Result[i,1]<-z1
Result[i,2]<-z2
}

So the results table would appear as follow as the following rows,
Row1: 1+1=2, 2+1=3
Row2: 1+3=4, 4+3=7
Row3: 1+5=6, 6+5=11
Row4: 1+7=8, 8+7=15
And this pattern would continue with x staying fixed until the last value of y is reached, then x would start at 2 and cycle through the calculations of y to the point where my last row is as,
RowN: 20+19=39, 39+19=58.
So I just want to know if is there a way to do it in one loop or if is it easier to run it as 2 loops.
I hope this is clearer as to what my question was asking, and I realize this is not the optimal way to do this, however for now it is just for testing purposes to see how long my initial process takes so that it can be streamlined down the road.
Thank you


text:
Q: flutter:: Is it possible to change the timezone of a datetime? I want to represent the time the file was saved as a string. The time in my country is 9 hours ahead of utc time. How can I change the current utc time to 9 hours faster?
  String _getTime({required String filePath}) {
    String fromPath = filePath.substring(
        filePath.lastIndexOf('/') + 1, filePath.lastIndexOf('.'));
    if (fromPath.startsWith("1", 0)) {
      DateTime dateTime =
      DateTime.fromMillisecondsSinceEpoch(int.parse(fromPath));
      var dateLocal = dateTime.toLocal();
      print(dateLocal);
      print(dateTime);
      int year = dateLocal.year;
      int month = dateLocal.month;
      int day = dateLocal.day;
      int hour = dateLocal.hour;
      int min = dateLocal.minute;
      String dato = '$year-$month-$day--$hour:$min';
      return dato;
    } else {
      return "No Date";
    }
  }

A: Use this package ---->>>>> https://pub.dev/packages/flutter_native_timezone
Add the package dependencies to your project, import the package into the file you're working in and write the code below to get your currenTimeZone
final String currentTimeZone = await FlutterNativeTimezone.getLocalTimezone();
debugPrint(currentTimeZone);


text:
Q: Как праивильно использовать gridview с данными в scrollview Вообщем,необходимо сделать так:

как должно работать:
фигуры (круги) должны пролистываться посредством scroll, как  правильно это сделать...пока только тогадки,выручайте
т.е порядок отрисовки и вывода должен быть неизменяемым, т.е сначало 4 круга ниже 3 круга,потом опять 4 и т.д около 40 ш.т. Круги т.е(изображения,Imageview) будт кликабельными и будут выполнять свои уникальные действия, на каждый круг своя опред. задача, отрисовывать думаю через цикл ...но опять проблема в реализации,надеюсь все доступно объяснил.
Добавил разметку:
<ScrollView android:id="@+id/lldinamik"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="0dp"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:paddingTop="3dp"
android:theme="@style/AppTheme.NoActionBar">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center">

    <ImageView
        android:id="@+id/button_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="2dp"
        android:layout_marginRight="5dp"
        android:clickable="true"
        android:src="@drawable/stop_button"/>

    <ImageView
        android:id="@+id/button_play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginRight="5dp"

        android:clickable="true"
        android:src="@drawable/play_button"/>

    <SeekBar
        android:id="@+id/sbar"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:max="100"

        android:progress="0"/>

    <TextView
        android:id="@+id/textPlayer"
        android:layout_width="70dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text=" "
        android:textColor="@color/white"
        android:textSize="20sp"/>
</LinearLayout>

A: Сразу оговорюсь, что исходную задачу решаю с нуля, не используя Ваши «наработки».
Создаете новый проект в Android Studio. Далее подключаете RecyclerView:
File – Project structure – Modules (app) – Dependencies – Add (+) – Library dependency – recyclerview-v7 – Ok – Ok
Это можно сделать по-другому, но в данном случае это не важно.
Добавляете layout-файлы:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/circle_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:scrollbars="vertical">

    </android.support.v7.widget.RecyclerView>

    <Button
        android:id="@+id/add_circle_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Add circle"/>

</LinearLayout>

item_circle.xml – layout одной ячейки:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="16dp">

    <ImageView
        android:id="@+id/item_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

Создаете класс CircleItem – элемент одной ячейки :
public class CircleItem {

    private int mResId;

    public CircleItem(int resId) {
        mResId = resId;
    }

    public int getResId() {
        return mResId;
    }

    public void setResId(int resId) {
        mResId = resId;
    }
}

Создаете ViewHolder:
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

public class CircleViewHolder extends RecyclerView.ViewHolder {

    private ImageView mItemImageView;

    public CircleViewHolder(View itemView) {
        super(itemView);
        mItemImageView = (ImageView) itemView.findViewById(R.id.item_image_view);
    }

    public ImageView getItemImageView() {
        return mItemImageView;
    }
}

Создаете адаптер для RecyclerView:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;

public class CircleAdapter extends RecyclerView.Adapter<CircleViewHolder> {

    private Context mContext;
    private ArrayList<CircleItem> mData;

    public CircleAdapter(Context context) {
        mContext = context;
        mData = new ArrayList<>();
    }

    @Override
    public CircleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        View view = layoutInflater.inflate(R.layout.item_circle, parent, false);
        return new CircleViewHolder(view);
    }

    @Override
    public void onBindViewHolder(CircleViewHolder holder, int position) {
        int resId = mData.get(position).getResId();
        holder.getItemImageView().setImageDrawable(mContext.getDrawable(resId));
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public void addItem(int resId) {
        mData.add(new CircleItem(resId));
        notifyDataSetChanged();
    }
}

И, наконец, MainActivity:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private RecyclerView mCircleRecyclerView;
    private Button mAddCircleButton;

    private Random mRandom;
    private CircleAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRandom = new Random();

        mCircleRecyclerView = (RecyclerView) findViewById(R.id.circle_recycler_view);
        mAddCircleButton = (Button) findViewById(R.id.add_circle_button);

        mAdapter = new CircleAdapter(getApplicationContext());
        GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this, 12);

        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch (position % 7) {
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                        return 3;
                    case 4:
                    case 5:
                    case 6:
                        return 4;
                }
                return 3;
            }
        });

        mCircleRecyclerView.setLayoutManager(gridLayoutManager);
        mCircleRecyclerView.setAdapter(mAdapter);

        mAddCircleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                switch (mRandom.nextInt(6)) {
                    case 0:
                        mAdapter.addItem(R.mipmap.ic_circle_one);
                        break;
                    case 1:
                        mAdapter.addItem(R.mipmap.ic_circle_two);
                        break;
                    case 2:
                        mAdapter.addItem(R.mipmap.ic_circle_three);
                        break;
                    case 3:
                        mAdapter.addItem(R.mipmap.ic_circle_four);
                        break;
                    case 4:
                        mAdapter.addItem(R.mipmap.ic_circle_five);
                        break;
                    case 5:
                        mAdapter.addItem(R.mipmap.ic_circle_six);
                        break;
                    case 6:
                        mAdapter.addItem(R.mipmap.ic_circle_seven);
                        break;
                }
            }
        });
    }
}

В итоге получаете вот что:

По нажатию на кнопку, добавляется новая иконка, в соответствии с желаемым алгоритмом.
Единственное что, строки, которые содержат три элемента, выглядят не очень, но это можно исправить и эту задачу я оставляю Вам.
Можно исправить, но получается не то ,что хотелось бы:


text:
Q: Is there a closed-form solution for the distance to the origin from the midpoint of a line connecting a point on an arc and a point on a tangent? I have a fixed-length line $EF$, whose endpoints run along a track consisting of two straight segments joined by an arc. I'd like to create a polar equation describing the location of the centerpoint of $EF$ as it travels along the track, but I'm having issues finding closed-form solutions for certain areas of the track.

Here, the arc $BC$ has radius $R$ and angle $\alpha$, $DB$ and $DC$ are tangent to the arc $BC$ at $B$ and $C$, respectively, the length of $EF$ is $g$, and $G$ is the midpoint of $EF$.
My current approach is to create a piecewise equation giving the length of $AG$ for a given value of $\theta$. For values of theta such that $E$ and $F$ are both either inside the arc or outside the arc, the equations are fairly straightforward, but I'm having issues finding something that works when one of the two points are on the arc.
What I have so far is:
$
r(\theta) =
\begin{cases}
    \sqrt{R^2 + (R\ \tan(\theta_{\text{arc_min}} - \theta))^2} & \theta_{\text{min}} & \leq \theta & < \theta_{\text{all_out_min}} \\
    ? & \theta_{\text{all_out_min}} & \leq \theta & < \theta_{\text{all_in_min}} \\
    \sqrt{R^2 - \left( \frac{g}{2} \right)^2} & \theta_{\text{all_in_min}} & \leq \theta & \leq \theta_{\text{all_in_max}} \\
    ? & \theta_{\text{all_in_max}} & < \theta & \leq \theta_{\text{all_out_max}} \\
    \sqrt{R^2 + (R\ \tan(\theta - \theta_{\text{arc_max}}))^2} & \theta_{\text{all_out_max}} & < \theta & \leq \theta_{\text{max}}
\end{cases}
$
The variable naming leaves something to be desired, but in any case:

*

*$\theta_{\text{arc_min}}$ is the angle at which the arc starts

*$\theta_{\text{arc_max}}$ is the angle at which the arc ends

*$\theta_{\text{all_out_min}} = \theta_{\text{arc_min}} - \arctan\frac{g/2}{R}$ is the largest angle less than $\pi$ where both $E$ and $F$ are outside the arc

*$\theta_{\text{all_out_max}} = \theta_{\text{arc_max}} + \arctan \frac{g/2}{R}$ is the smallest angle greater than $\pi$ where both $E$ and $F$ are outside the arc

*$\theta_{\text{all_in_min}} = \theta_{\text{arc_min}} + \arcsin \frac{g/2}{R}$ is the largest angle less than $\pi$ where both $E$ and $F$ are inside the arc

*$\theta_{\text{all_in_max}} = \theta_{\text{arc_max}} - \arcsin \frac{g/2}{R}$ is the smallest angle greater than $\pi$ where both $E$ and $F$ are inside the arc

My attempts at solving this problem all seem to run into the same issue, where there just doesn't seem to be enough information to get a useful result. I know the lengths of $FG$ and $GE$, as well as the distance $AF$, but that only gives me two sides of a triangle, and other approaches don't seem to yield better results. I'm going with an iterative solver for now, but a more elegant (and less likely to be buggy) solution would be preferable.
Does a closed-form solution exist? And if so, how would it be derived?

A: It might not be possible to do better than an implicit equation. Here's what I can come up with.
Let's introduce new parameters for the coordinates of $E$ and $F$:

*

*$E=(x,y)$

*$F=(s,t)$
We get three equations relating these parameters:

*

*$s^2+t^2=R^2$

*$(x-s)^2+(y-t)^2=g^2$

*$y=x-\sqrt{2} R$
You can eliminate $y$ to rewrite the second equation, getting

*

*$s^2+t^2=R^2$

*$(x-s)^2 + (x - \sqrt{2} R - t)^2 = g^2$
In principle, these two equations can be solved for $s,t$ as functions of $x$, say $s = \beta(x)$ and $t = \gamma(x)$. But it'll be messy at best! For instance, you can solve the first equation for $s = \sqrt{R^2-t^2}$, then substitute into the second equation. You'll get some algebraic equation for $t$ which you can attempt to solve for $t$. In principle this equation can be solved for $t$: you isolate the radical, get rid of the radical by squaring, and then I think you'll get a 4th degree polynomial in $t$ for which there's a known formula for the roots. But it'll be pretty horrible.
But to continue anyway, from the midpoint formula we have
$$G = \left( \frac{x+s}{2}, \frac{y+t}{2} \right) = \left( \frac{x + \beta(x)}{2}, \frac{x - \sqrt{2} R + \gamma(x)}{2} \right)
$$
Also,
$$\tan(\theta) = \frac{x - \sqrt{2} R + \gamma(x)}{x+\beta(x)}
$$
If we could solve the last equation for $x = \delta(\theta)$ then we would be done, by plugging that function into the formula for $G$ (and then writing down $r(\theta) = |G|$).
But $\gamma$ and $\beta$ are messy functions of $x$, and I suspect this cannot be solved so easily for $x$.


text:
Q: why flutter ListTile Widget trailing property not take the Row Widget? Card(
          elevation: 10,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(10))),
          margin: EdgeInsets.only(
            bottom: 10,
          ),
          child: ListTile(
            leading: Text('tests'),
            trailing: Row(
              children:[
                IconButton(
              icon: Icon(
                Icons.update,
                color: Colors.red,
              ),
              onPressed: () {
                setState(() {
                  _update();
                });
              },
            ),

            IconButton(
              icon: Icon(
                Icons.delete,
                color: Colors.red,
              ),
              onPressed: () {
                setState(() {
                  _delete();
                });
              },
            ),
               ]
           )
          ),
        )

A: Flutter ListTitle trailing property is a widget to display after the title.
Typically an Icon widget.
To show right-aligned metadata (assuming left-to-right reading order; left-aligned for right-to-left reading order), consider using a Row with CrossAxisAlignment.baseline alignment whose first item is Expanded and whose second child is the metadata text, instead of using the trailing property.
You can see more in https://api.flutter.dev/flutter/material/ListTile-class.html

A: The row tries to take all the space. To solve that you can give it mainAxisSize: MainAxisSize.min. like this:
Card(
          elevation: 10,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(10))),
          margin: EdgeInsets.only(
            bottom: 10,
          ),
          child: ListTile(
            leading: Text('tests'),
            trailing: Row(
              mainAxisSize: MainAxisSize.min
              children:[
                IconButton(
              icon: Icon(
                Icons.update,
                color: Colors.red,
              ),
              onPressed: () {
                setState(() {
                  _update();
                });
              },
            ),

            IconButton(
              icon: Icon(
                Icons.delete,
                color: Colors.red,
              ),
              onPressed: () {
                setState(() {
                  _delete();
                });
              },
            ),
               ]
           )
          ),
        )


text:
Q: send output UIDatePicker by email with swift I am really new at programming with swift and trying to build an app that sends a date/time from UIDatePicker to a defined email address. I try to convert the output of UIDatePicker to string. How do I get this in my email?
I get an error on "  mailComposerVC.setMessageBody(strDate"
My code so far is:
@IBOutlet weak var mijnDatumTijd: UIDatePicker!
@IBAction func datumTIjd(_ sender: UIDatePicker){let dateFormatter = DateFormatter()

    dateFormatter.dateStyle = DateFormatter.Style.short
    dateFormatter.timeStyle = DateFormatter.Style.short

    let strDate = dateFormatter.string(from: mijnDatumTijd.date)
}

var email: String = ""
@IBOutlet weak var Identifier: UITextField!
    @IBAction func buttonClick(sender: UIButton) {
        //getting input from Text Field
        email = Identifier.text!
    }

@IBAction func send(_ sender: UIButton) {
    _ = configuredMailComposeViewController()
    }

func configuredMailComposeViewController() -> MFMailComposeViewController {
    let mailComposerVC = MFMailComposeViewController()
    mailComposerVC.mailComposeDelegate = self as? MFMailComposeViewControllerDelegate // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property

    mailComposerVC.setToRecipients(["example@email.com"])
    mailComposerVC.setSubject("Sending you an in-app e-mail...")
    mailComposerVC.setMessageBody(strDate, isHTML: false)

    return mailComposerVC

A: The error message you are getting (that you don't list, but can be inferred from the line you get the error on) is caused by a scope issue.
Variables cannot be accessed outside the scope they are create in. In Swift you can almost always translate scope as matching curly braces {}.
You create strDate in datumTIjd(_ sender: ) which is a function that traps strDate inside its braces. Nothing outside the function even knows strDate exists. Since you create strDate on the last line of datumTIjd(_ sender: ) and never use it the compiler may optimize it away (if it doesn't strDate only lives for the tiniest of blips in time since everything declared in the function's scope gets deleted when the function is done) and you likely have a warning telling you strDate is an unused variable.
When you get to configuredMailComposeViewController() -> MFMailComposeViewController your reference strDate, however it is not in the local scope or any higher scope.
Lose the let from:
let strDate = dateFormatter.string(from: mijnDatumTijd.date)

making it:
strDate = dateFormatter.string(from: mijnDatumTijd.date)

Then before the line
var email: String = ""

add:
var strDate: String = ""

That will move strDate from the scope of the function it currently lives in to the class's scope allowing any method in the class to access it, clearing your current error.

A: *

*You are getting this error because of the scope of strDate variable is limited inside datumTIjd function since it is local variable. So you just need to make it global so that you can access it inside your configuredMailComposeViewController() function.

*So just make a change in your code as below:

*Declare strDate where you declared email variable as:
     var strDate:String = ""

*Now change in your datumTIjd action:
Modify this line - let strDate = dateFormatter.string(from: mijnDatumTijd.date)
as
self.strDate = dateFormatter.string(from: mijnDatumTijd.date)


text:
Q: Creating a zip archive from memory stream in .Net Core I'm trying to create a zip archive from memory stream and when I download it from my API on the web-side it tells me the archive is corrupt when I try to open it (and not much else, the download itself is successful).
This is the code I use for generating the zip-archive:
    public byte[] ZipFiles(IEnumerable<FileContentResult> filesToZip)
    {
        var outputMemoryStream = new MemoryStream();
        var zipStream = new ZipOutputStream(outputMemoryStream);

        zipStream.SetLevel(3);

        foreach (var fileToZip in filesToZip)
        {
            var inputMemoryStream = new MemoryStream(fileToZip.FileContents);
            var zipEntry = new ZipEntry(fileToZip.FileDownloadName);
            zipEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(zipEntry);
            StreamUtils.Copy(inputMemoryStream, zipStream, new byte[4096]);
            zipStream.CloseEntry();
        }

        zipStream.IsStreamOwner = false;
        zipStream.Close();

        outputMemoryStream.Position = 0;

        return outputMemoryStream.ToArray();
    }

It returns the zip file as a byte array, which is then put into another filecontentresult before being returned from the API (I've tried setting contenttype to both application/octet-stream and application/zip). I've seen and tried a huge amount of different solutions here on stackoverflow, but all of them seem to fail when trying to open the downloaded file. I'm using SharpZipLib. Anyone got any pointers?
Edit/new info:
After further testing/debugging, it seems like the zip file itself is okay. If I save it to the server disk I'm able to open/unpack the files. However, the action of putting it into a filecontentresult and returning it from the controller & downloading it on a client seems to break it. The file name is okay, with a .zip extension, and as mentioned I've tried both application/octet-stream and application/zip as contenttype (I think the second is is correct to use). We do already return and download other files from the API just fine, it's just zip-files that are somehow not working correctly here.

A: If I'm not mistaken, outputMemoryStream.Position = 0 is not enough since you don't have a reference of the initial position and the current one. So, before the return of the function, you have to move the pointer of the memorystream at the very start. For that, replace outputMemoryStream.Position = 0 with outputMemoryStream.Seek(0, SeekOrigin.Begin).


text:
Q: How to convert encoding in Python? I have a string with miss encoding »Æ¹ûÊ÷. On http://2cyr.com/decode/?lang=en website, you can encode it with gb2312 then decode it with iso8859 so to display it correctly.
In C#, there's a function called Encoding.Convert, which can help you convert convert the bytes from one encoding to the other. In process is straight forward:
encode the string into bytesA, using gb2312 encoder
Encoding.Convert bytesA from gb2312 encoding to iso8859 encoding
decode the bytes using iso8859 encoder

In Python, I have tried all kinds of encoding and decoding methods I can think of, but no one can help me convert the given string to the correct codecs that can be displayed correctly.

A: Your data is UTF-8 encoded GB2312, at least as pasted into my UTF-8 configured terminal window:
>>> data = '»Æ¹ûÊ÷'
>>> data.decode('utf8').encode('latin1').decode('gb2312')
u'\u9ec4\u679c\u6811'
>>> print _
黄果树

Encoding to Latin 1 lets us interpret characters as bytes to fix the encoding.
Rule of thumb: whenever you have double-encoded data, undo the extra 'layer' of encoding by decoding to Unicode using that codec, then encoding again with Latin-1 to get bytes again.


text:
Q: How to create a Mobile Website I'm working on a project for class. To create a website and a website for mobile users. The site is to recongize the type of device/browser accessing the page and send the appropiate form. So if I was to visit the site on IE8 it will direct me to the mainpage for IE8, if I was to access the site with a mobile device it will direct me to the mobile website main page automatically.
Also, I need to design the website for at least two different screen sizes.
I'm coding in HTML5, I do not know the type of server the site will be hosted on. The use of Javascript is extra credited. The project details are to "design a small mobile web site. The web site should be tested on one or more mobile devices. The iPod Touch device will be used as the base for testing."
I know how to do 8/10 of the requirements (except the two mentioned). I looked at W3C and didn't find anything.
Any help would be much appreciated. Thank you!

A: Do a Google for:

*

*CSS Browser Detection

*JavaScript Browser Detection

Also you should think twice about creating multiple sites - with basically the same content - or creating proper stylesheets that are referred from the same site.
Hope that get's you the other 2 requirements
NOTE: Since this is homework I won't post any links...

A: I suspect that ServerFault isn't the best place for this question...but aside from that, your question is a little vague.  A google search for "designing a mobile website" turns up what looks to be several pages of relevant information.  If you first try working with the information in those documents and then come back with specific questions (e.g., "I tried this and it behaved this way instead of the way I expected") you're apt to get better answers.


text:
Q: vpn for my smart TV I am looking to connect my Samsung smart tv into a VPN connection in order to get American tv porgrams on netflix.
Unfortunately there is no app on the TV for VPN.   On my laptop I use HMA which I pay about 7$ a month and with that I just download software and it just installs and runs on windows, giving me the functionality I need.
Its becoming a bit of a chore to connect my laptop into the tv everytime I want to watch something on the american netflix esp when changing channels etc.
I share an internet connection that is a wifi adsl router.. like a standard one you get from your broadband provider...
What im wondering is if I could buy a router that has VPN software built in then connect that in the middle of the wifi router and my tv meaning that it does not intefere with other people using the wifi but when I want to use the vpn I just plug the tv into the router and then the router into the adsl wifi hub?
... or am I barking mad?