text:
Q: Can't save data from custom classes with UserDefaults It is different I have 2 classes This question is not the same as - Saving custom SWIFT class with NSCoding to UserDefaults and it is different because there are 2 classes that are connected to each other and I don't know to implement NSCoding for both of them.I am beginner and I have been trying for more than 6 hours to solve this problem.And btw this is not a duplicate because all the solutions on here are outdated. I have 2 main custom classes(super class and subclass) in my app and with UserDefaults I want to make so I can save data permanently.
The first class:
class Day {
    var dayName: String
    var subjects: [Subject]?
    init(dayName: String) {
       self.dayName = dayName
    }
}

The second class:
class Subject: Day {
    var subjectName: String
    var startsAt: String?
    init(dayName: String,subjectName: String) {
       self.subjectName = subjectName
       super.init(dayName: dayName)
    }
}

I try to save a instance of Subject class like this:
UserDefaults.standard.set(Subject(dayName: "Monday",subjectName: "Programming"), forKey: "subject")
    let savedSubject = UserDefaults.standard.object(forKey: "subject") as? Subject
    print(savedSubject!.subjectName)

And then when I run the app I get a crash saying -

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: 'Attempt to insert non-property
  list object School_Class_Scedule.Subject for key subject'

I did a lot of research and found out that I should convert the subject to NSData but I don't know how to do that with swift 3 or 4 in XCode 9.
Any help would be much appreciated. Thank you for saving my life and helping me my dream to become a reality.


text:
Q: How to send SCSI command to USB mass storage using Swift on macOS? I am creating a macOS app that will update the firmware of a USB mass storage device. There are only two steps to do this, copy the files to the storage device (done with this) and send a reboot command to the device using SCSI command sets.
I've tried the library below to send a command, however, the device didn't reboot. I am not sure if there's something wrong with my request.
https://github.com/Arti3DPlayer/USBDeviceSwift
I reached to the developer of this library, however, he replied to me "Sorry, I didn't work with USB and Swift about a year, and don't remember this things:)"
The reboot command is 0xdf 0x40.
This is the request I sent to the device.
guard let deviceInterface = self.deviceInfo.deviceInterfacePtrPtr?.pointee?.pointee else {
    throw STM32DeviceError.DeviceInterfaceNotFound
}

var kr:Int32 = 0
let length:Int = 6
var requestPtr:[UInt8] = [UInt8](repeating: 0, count: length)
// Creating request
var request = IOUSBDevRequest(
        bmRequestType: USBmakebmRequestType(direction: kUSBIn, type: kUSBDevice, recipient: kUSBStandard),
        bRequest: STM32REQUEST.DETACH.rawValue,
        wValue: UInt16(0xdf),
        wIndex: 0,
        wLength: UInt16(length),
        pData: &requestPtr,
        wLenDone: 255)

kr = deviceInterface.DeviceRequest(self.deviceInfo.deviceInterfacePtrPtr, &request)

if (kr != kIOReturnSuccess) {
    throw STM32DeviceError.RequestError(desc: "Get device status request error: \(kr)")
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set language label programmatically I have problems setting labels with language specifications programmatically after the component has been rendered. I have the following:
public class DateFilterWidget extends Div implements IdSpace {
private static final long serialVersionUID = 1L;

@Wire
Datebox startDate, endDate;

@Wire
Button filterButton;

@Wire
Label datefilterLabel;

String field;

public DateFilterWidget(String name, String filterField) {
    Executions.createComponents("widgets/datefilter.zul", this, null);
    Selectors.wireComponents(this, this, false);
    Selectors.wireEventListeners(this, this);
    datefilterLabel.setValue("${labels.data.dateFilterButton.label}");

    this.field = filterField;
}
}

And the datefilter.zul
<hbox sclass="filterWidgetBox" align="center">
        <label id="datefilterLabel" />
        <datebox id="startDate" format="yyyy-MM-dd"
            weekOfYear="true" width="105px"/>
        <label value="-" />
        <datebox id="endDate" format="yyyy-MM-dd"
            weekOfYear="true" width="105px"/>
        <button id="filterButtonc"
            label="${labels.data.dateFilterButton.label}" />
</hbox>

I the above case the same label has been used for both the button and the label. The button language reference works fine, but the label that got a value programmatically don't work.
I know that I can use the Labels.getLabel("data.dateFilterButton.label"), but this solution removes the possibility to update language unless the whole application is rerendered with the new language.

A: label="${labels...}" is a static EL and will only get evaluated once the zul file is parsed, and has the same effect as calling setLabel(Labels.get(Labels.getLabel(...))).

The button language reference works fine

I don't really understand what you mean by that. When I run your example using Labels.getLabel(...) it works as expected, setting both labels in the current locale. When changing the locale during runtime e.g. from EN -> DE none of the labels update automatically, and both components need to be re-rendered and then update correctly.
To provide a solution, can you please give details on what you expect to happen? Or what you are trying to achieve regarding:

this solution removes the possibility to update language unless the whole application is re-rendered with the new language

"Update" can have several meanings, it's just not clear yet.
Robert

A: To set the value programmatically you should used the class Labels of the zk api.
You can see the javadoc clicking here:
Labels
And use the method getLabel.
Example:
datefilterLabel.setValue(Labels.getLabel("data.dateFilterButton.label");

If that is the right label key.


text:
Q: Resuming data from a database is extra slow - VBA So, i've got a Workbook that will have more than 1500 rows of data in it's database... That's... not much, it is very fast to run that;
I'll have to make a resumed table of the data, but the user will have to choose some of the filters for the table, there are three major things that will have to happen:
1st the user will select an  "OT" (That's the name the company gives to their clients, OTXXXXXX), that will have to trigger some vba code which will preset a table
2nd There will be a 3 row header, with some very simple formula in the last header's last 2 rows and the first will be the products of that client
3rd Now we are f****, the rows part will have a "header"(Is that the name?) with a 1 column width, but that little, not so little, sh**, has around 140 rows plus with invoices, and for each Invoice x Product cell there will be a number of boxes that went off
Now, i´ve already tried doing it "manually" on VBA, reading each cell's row and column, getting the references, going to DB and bringing back the number of boxes, an i7 9750H with 16Gb of ram disliked that, so I'm not able to give that to the company (their Desktops runs way slower than my laptop). So i´ve tried to use a formula to do that, I've tryed an array formula and a matrix formula, both worked meh, around 2-3 min of processing, which would translate to 8-10min it´s fine... Buuuut the database keeps increasing and each change on it triggers the calculation, and disabling it would be even worse..., I can't afford that time loss, so i'm litterally lost.
I don't know what to do, just help
Please  ;-;

A: You may divide them in more execution threads. Also, check that database to be correctly built. Check every connection you use to be sure it work. For 1.500 rows 8 mins it's too much.


text:
Q: If Statements in CMS Page This is what I am trying to do:
{{if var data.request_quote=="on"}} Yes {{else}} No {{/if}}

Where var data.request_quote is a form variable. It keeps coming out as No, even if data.request_quote is on.

A: There are two problems with this code

*

*There is no var keyword in the if directive

*The template filter cannot evaluate conditions. You should give request_quote a boolean value (or leave it empty if it is not "on")

Then the correct code is:
{{if data.request_quote}} Yes {{else}} No {{/if}}


text:
Q: Javascript RegExp non sequential characters I have this rule
var reg = new RegExp('[a-z]{3}');

Which means it is allowed to use characters between a-z and at least 3 occurrences.
So, I am wondering if there is a way to match this rule with non sequential characters.
In other words,
"abc" => valid
"aaa" => not valid

Thank you!

A: Here is a working regex for exactly 3 (or N) characters, if the number is not fixed it gets more complicated:
^([a-z])(?!\1{2})[a-z]{2}$
1   2    3 4  5    6   7 8

Explanation:

*

*^ matches the beginning of the string

*([a-z]) match one of the accepted characters and save it (group 1)

*(?!...) negative lookahead, what is in those brackets is not accepted

*\1 reference to the first group (first character here)

*{2} repeated exactly twice

*[a-z] the accepted characters

*{2} repeated exactly twice

*$ matches the end of the string

Link here (I added the gm modifiers, so that several expressions can be tested.)

A: Try to use the excluding lookahead (?![a-z]{3}), it will not match 3 equal characters in sequence.


text:
Q: May RAM failure made no beep? Several days ago, I added some more RAM to my PC (4x2 to 4x2+2x2) from my old PC. They worked before, i never had any problem with those modules. My motherboard supports up to 16gb on 1066MHZ, and actually, my modules are 1600(4x2) and 1333(2x2), so, i know they will work all together at 1066MHZ, but, since yesterday, my PC suddenly freezes, no blue screen, everything hangs up and stop working. When i tried to run again the PC, it doesn't start, no bios beep, no post message, just all leds from HD and CD drives blink 3 times, and thats all.
First, i thought it could be a CPU/motherboard problem (both of them have 8 years, and they had worked a lot), because they made no beep. I left the PC unplugged 2 minutes, plug again, and it worked, join on the BIOS menu, and realice that my CPU was 72ºC. Open the case, unmount heat sink, clean heat sink, mount again, and it worked fine (started rendering a video so CPU would have a heavy load, it didnt went through 60ºC this time)
Today, it happened again. I was sure that it wasn't CPU overheat, because the fan wasn't making much noise, tried to wait about 2 minutes but it still not working. Then, i tried, just tried, to remove the RAM modules i added 2 weeks ago, and everything start working again.
I know that RAM failures can make a blue screen, or even some beep on bios startup, but, could it be that it made no bios beep? i never heard about no bios beep on RAM failure and i'm a bit afraid that it could be a CPU/Motherboard failure.
Thanks a lot for your time

A: RAM failure is tricky. If all the RAM modules in your system are faulty which makes the system unable to boot up, you will certainly hear beeps.
However, RAM can be faulty in many other ways which compromise your system's stability but don't show outright. It's totally normal for RAM to be faulty and not cause BIOS beep, since when the computer boots, depending on the configuration RAM can be tested very briefly or even not at all.
I've had multiple systems in the past where bad RAMs caused BSOD but there was no beep nor any other error indication from the BIOS.


text:
Q: Trying to figure out the best approach to perform CRUD operations for a slightly complex SQL database I'm currently working on a C# dot net core MVC project with an MSSQL database back end. I've gone with a data first approach. Here's a simplified sample of my dbcontext.
//dbcontext//
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace redux.web.Models
{
    public partial class assetsdbContext : DbContext
    {
        public assetsdbContext()
        {
        }

        public assetsdbContext(DbContextOptions<assetsdbContext> options)
            : base(options)
        {
        }

        public virtual DbSet<AssetType> AssetType { get; set; }
        public virtual DbSet<Assets> Assets { get; set; }
        public virtual DbSet<Cpu> Cpu { get; set; }
        public virtual DbSet<Memory> Memory { get; set; }
        public virtual DbSet<Pcdetails> Pcdetails { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<AssetType>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();

                entity.Property(e => e.DisplayName)
                    .HasMaxLength(50)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<Assets>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();

                entity.Property(e => e.AssetNo)
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.AssetTypeId).HasColumnName("AssetTypeID");

                entity.Property(e => e.DisplayName)
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.PcdetailsId).HasColumnName("PCDetailsID");
            });

            modelBuilder.Entity<Cpu>(entity =>
            {
                entity.ToTable("CPU");

                entity.Property(e => e.Id).ValueGeneratedNever();

                entity.Property(e => e.DisplayName)
                    .HasMaxLength(50)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<Memory>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();

                entity.Property(e => e.DisplayName)
                    .HasMaxLength(50)
                    .IsUnicode(false);
            });

            modelBuilder.Entity<Pcdetails>(entity =>
            {
                entity.ToTable("PCDetails");

                entity.Property(e => e.Id).ValueGeneratedNever();

                entity.Property(e => e.Cpuid).HasColumnName("CPUID");

                entity.Property(e => e.MemoryId).HasColumnName("MemoryID");
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

My problem now is how to handle PC Details when entering a new asset as there will be PCs and non-pc assets. I'm thinking I'd need use AssetType maybe in a if statement within the create method? or can I design the database in a better way? Any thoughts would be really appreciated.

A: I would include a column in the PCDetails that links to the Assets table as a Foreign Key.  You can add business logic to your UI to display the options to change/add/delete the details of the Asset is of the Type "PC".


text:
Q: Elementary applications of linear algebra over finite fields I'm teaching axiomatic linear algebra again this semester.  Although the textbooks I'm using do everything over the real or complex numbers, for various reasons I prefer to work over an arbitrary field when possible.   I always introduce at least $\mathbb{F}_2$ as an example of a finite field.  To help motivate this level of generality, I'd like to cover some application of linear algebra over finite fields.  Ideally it shouldn't make explicit reference to linear algebra or finite fields in its setup, and should require as little background as possible (the students have taken calculus, but not necessarily any other advanced math — in particular applications to group theory are out).  I've looked around a little, but haven't found anything so far that requires little enough overhead to fit into a single 50-minute lecture and wouldn't seem either too abstract or too arbitrary to motivate such students.  Any suggestions?
Alternatively, I'd be interested in elementary applications of linear algebra over any other field which isn't a subfield of $\mathbb{C}$.

A: Suppose you want to compute the period of the Fibonacci sequence $\bmod p$. This reduces to examining the powers of the matrix $\left[ \begin{array}{cc} 1 & 1 \\\ 1 & 0 \end{array} \right]$ over $\mathbb{F}_p$, which requires either diagonalizing it over $\mathbb{F}_p$ or over $\mathbb{F}_{p^2}$ (or, when $p = 5$, using a nontrivial Jordan block). From here you can write down a nice number that is divisible by the period, depending on the value of $p \bmod 5$ (this uses a little quadratic reciprocity).
Edit: I suppose this requires some number-theoretic background to do properly. Never mind.

A: (1) An obvious but a very conceptual application is the basic fact that the cardinality of every finite field $F$ is a power of a prime,
as $F$ can be considered as a vector space over $\mathbb{F}_p$ for $p=char F$.
(2) Another application is the construction of finite projective planes. Consider a vector space $V$ of dimension $3$ over a finite field $F$.
Then consider the projective geometry $PG(V)$ whose points are the $1$-dimensional subspaces of $V$ and whose lines are the $2$-dimensional
subspaces of $V$. In particular, the Fano projective place can be obtained by this method over $\mathbb{F}_2$.

A: The game of Projective Set
is tantamount to finding a linear dependence on
$7$ (distinct, nonzero) vectors in $\mathbb{F}_2^6$.
Linear algebra over $\mathbb{F}_2$ shows that there's always a solution,
and moreover that the number of solutions is always $2^k-1$
for some positive integer $k$.  How large can this $k$ get, and
how many of the ${63 \choose 7} = 553270671$ possible deals attain
this maximal $k$?
[Thanks to Zach Abel for introducing me to this game.]

A: (1) you can use $\mathbb{F}_2$ to prove that every group $G$ with $Aut(G)\cong 0$ is either $0$ or $\mathbb{Z}/2\mathbb{Z}$.
This is done by noting that the group is abelian, since all conjugation-automorphisms are the identity.
Then for abelian groups one has the automorphism $g\mapsto -g$ so all elements are self inverse.
At this point one gets that $G$ is a $\mathbb{F}_2$-vector space. Since any vector space of dimension $≥2$ admits nontrivial automorphisms, the result follows.
(2) also you might want to take a look at this: http://gowers.wordpress.com/2008/07/31/dimension-arguments-in-combinatorics/

A: This one is pretty good. Kaplansky wanted squarefree numbers $x$ such that
$$ \sigma ( x^3) = y^2, $$ where $\sigma$ is the sum of divisors function. Somewhere around here I have a short note of his. He referred to this (and some very similar problems) as Ozanam's problem, from page 56 of Dickson's History, volume 1. Let's see; for each prime $p$ up to some bound, I had the computer factor $ \sigma ( p^3),$ especially recording the exponents on the output primes $q.$ So, to the best of my memory (about 18 years ago), I wound up with a big matrix with entries in the field with two elements; each column meant  a prime $p,$ each row was saying whether the exponent for the prime $q$  was even or odd. Then, a solution was a column vector, also of 0's and 1's, which my big matrix mapped to the zero vector. So, I did Gauss elimination over the field of two elements. And found hundreds of solutions.
I will see if I can find something written about this. For that matter, the program or programs I wrote should still be there in my MSRI account.
Note: i am having a little trouble remembering if it is the matrix i describe above or its transpose. So perhaps a little care is needed. It definitely worked, though, and quickly. I also built in some procedure where i could force some prime to be included, then see if i could find solutions with that restriction. As I recall, that needed more handholding for the computer, more attention by me.

A: How about binary linear codes? You can "see" the Hamming distance between codewords, and use linear transformations to encode/decode

A: Sometimes math problems crop up in high school competitions that are secretly linear algebra problems in disguise. For instance, #6 of USAMO 2008 (http://amc.maa.org/a-activities/a7-problems/USAMO-IMO/q-usamo/-pdf/usamo2008.pdf) can be approached via linear algebra over $\mathbb{F}_2$.

A: There is a Martin Gardner problem, reprinted in his Unexpected Hanging collection, that goes like this:

Miranda beat Rosemary in a set of tennis, winning 6–3.  There were five service breaks.  Who served first?

One solution is as follows.  The wins by the player who served first may be represented by a vector  $\mathbb{F}_2^9$ that is the sum of (1,0,1,0,1,0,1,0,1) and another vector of weight 5.  Such a vector must have even weight, so the player who served first won an even number of games.  Thus Miranda served first.
In the book, Gardner writes that his original solution was long and cumbersome, and that the shortest solution he received was by Goran Ohlin: "Whoever served first, served five games, and the other player served four.  Suppose the first server won $x$ of the games she served and $y$ of the other four games.  The total number of games lost by the player who served them is then $5-x+y$.  This equals $5$ [we were told that the non-server won five games].  Therefore $x=y$, and the first server won a total of $2x$ games.  Because only Miranda won an even number of games, she must have been the first server."  Though more elementary in some sense, this solution seems more ad hoc and less conceptual to me than the above argument using $\mathbb{F}_2$.

A: You can use linear algebra over $\mathbb{F}_2$ to solve the game "Lights Out": http://en.wikipedia.org/wiki/Lights_Out_%28game%29

A: I suggest Linear Feedback Shift Register (LFSR) as an easy example. They can be used as pseudo random number generators and have a wide practical use in communication and cryptography, GPS, GSM, CRC, WIFI, .. (non-math) applications which are usually accepted as usefull.
Usually they work over $\mathbb{F}_2$, but other fields are possible. Basically you have to work with polynomials (including long division) over $\mathbb{F}_2$. The need for primitive polynomials may motivate some more advanced considerations.
A brief summary for mathematicians is Nayuki's blog.
I would explicitly pick the CRC algorithm. A description is located for example in this lecture(pdf) from D.Culler. This also relates to linear codes, which is also a good idea.
More easy is an application as fancy counter. If you ever wondered how the shuffle mode of your media player works.

A: Possibly the simplest application is Berlekamp's Oddtown theorem. One reference is Section 12.2 of http://math.mit.edu/~rstan/algcomb.pdf.

A: Rubik's Clock and Its Solution by Dénes and Mullen (Math. Mag. 68 (1995), 378–381) uses linear algebra modulo 12 to solve the Rubik's clock puzzle.

A: A trivial application: The group $(\mathbb{Z}/2\mathbb{Z})^n$ is generated by no less than $n$ elements.
[Probably this is the easiest way to prove that the free profinite group on $n$ letters cannot be topologically generated by less elements. And more abstractly, it is in general hard to find the minimal number of generators of a group, UNLESS it has a vector space quotient, and then we have dimension theory of vector spaces.]


text:
Q: What kind of algorithm is used to generate a square matrix? I need generate a matrix and fill with numbers and inactive cells, but that the sum of each columns or rows are equal. I know the magic box and sudoku, but is different. Can you help me please? What kind algorithm I need use for generate this matrix?
E.g
X = 0 = block inactive
  Matrix ( 4x4 )

   0  8  4  X  | 12
   2  0  8  2  | 12
  10  1  X  1  | 12
   0  3  X  9  | 12
   ____________|
  12 12 12 12

Other example:
  Matrix ( 5x5 )

  0  2  2  3  5 | 12
  2  4  0  5  1 | 12
  8  2  0  2  0 | 12
  0  4  2  0  6 | 12
  2  0  8  2  0 | 12
  ______________|
  12 12 12 12 12

The result can be any other number, it is not always 12. Just as in Example I was easier to do for me. It's not be symmetrical.
Note: This is not magic box, also is not sudoku.
Conclusion:
1) I need build this box and fill with number and block inactive.
2) Always matrix is square(3x3, 4x4, 5x5, NxN, ...)
3) When I fill of space is not block, I can use number one, two or three digits.
4) The sum of all sides must be equal.
5) In the above example, X is block. Block mean not use for player.
6) you can inactive block can be 0, however does not affect the sum.
7) There is also no restriction on how many blocks or inactive will have no
8) To fill cells with numbers, this can be repeated if you want. There is not restriction.
9) The matrix is always a square and may be of different dimensions. (2)
Thanks guys for your help. And sorry that the problem is incomplete and for my english is too bad, but that's all.

A: In terms of agorithms, I would approach it as a system of linear equations. You can put the box as a matrix of variables:
x11 x12 x13 x14
x21 x22 x23 x24
x31 x32 x33 x34
x41 x42 x43 x44

Then you would make the equations as:
row1 = row2  (x11 + x12 + x13 + x14 = x21 + x22 + x23 + x24)
row1 = row3  (...)
row1 = row4
row1 = col1
row1 = col2
row1 = col3
row1 = col4

For N = 4, you would have 16 variables and 7 equations, so you would have a solution with a number of degrees of freedom (at least 9, as pointed out by @JamesMcLeod, and exactly 9, as stated by @Chris), so you could generate every possible matrix satisfying the restrictions just giving values to every free parameter. In the resulting matrix, you could mark every cell with 0 as an inactive cell.
To do this however you would need a library or software package with the ability to solve systems of linear equations with degrees of freedom (several math software packages can do this, but right now only Maple comes to my mind).
PD: I've just read that numbers must have one, two or three digits (and be positive, too?). To address this, you could just "take care" when choosing the values for the free parameters once the system of equations is solved, or you could add inequalities to the problem like:
x11 < 1000
x11 >= 0  (if values must be positive)
x12 < 1000
(...)

But then it would be a linear programming problem. You may approach it like this too.
PD2: You can also make simple cases with diagonal matrices:
7 X X X
X 7 X X
X X 7 X
X X X 7

But I guess you already knew that...
Edit: Thanks James McLeod and Chris for your corrections.

A: do you fill the matrix with random numbers? You need a function that has an argument as 1 dimension vector which will verify if the sum of the row's elements is 12, then you can still use this function for columns(with a loop) into your main.


text:
Q: JSON posted with @RequestParam In my app I've got this method :
RequestMapping(value = "/variable/add", method = RequestMethod.POST)
public @ResponseBody
Object addVariable(@RequestBody MyObject myObject) {
    //do something
    return saimVariable;
}

and authentication aspect :
@Around("execution(* pl.my.company.*.*(..))")
public Object advice(ProceedingJoinPoint joinPoint) {
    ServletRequestAttributes t = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    HttpServletRequest request = t.getRequest();

    String username = (String) request.getParameter("username");
    System.out.println("USER : " + username);
    try {
        if (username.equals("myname")) {
            System.out.println("*** ACCESS GRANTED *** ");
            Object response = joinPoint.proceed();
            return response;
        } else {
            System.out.println();
            return "ACCESS DENIED";
        }

    } catch (Throwable e) {
        System.out.println(e.getMessage());
        return "ACCESS DENIED";
    }

}

}
I want to create REST service so for securitu I need to authenticate EVERY request, so i need to pass also a USERNAME, not only a JSON. But i don't know how to do it, because when i use @RequestParam("myObject") instead of  @RequestBody it just don't work. So my question is :
How can I pass both JSON and other parameters (strings,ints ...etc) with ONE POST request?

A: 1) First I'll suggest you to use Spring-Security. For checking every request there is a annotation in spring @PreAuthorize that will help to check every request before processing.
2)And If you want to use check current logged in user's username then their is no need of passing two parameter.You can check current logged in user by using following code.
    @PreAuthorize("isAuthenticated()")
    @RequestMapping(value = "/current", method = RequestMethod.GET)
    public @ResponseBody Users getCurrentLoggedInUser() throws Exception {
        Object authenticatorPrincipalObject = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = null;
        if(authenticatorPrincipalObject != null && authenticatorPrincipalObject instanceof Users){
            Users authenticatorPrincipal = (Users) authenticatorPrincipalObject;
            userName = authenticatorPrincipal.getUsername();
        }else if(authenticatorPrincipalObject != null){
            userName =  authenticatorPrincipalObject.toString();
        }else{
            return null;
        }
        return userService.getCurrentLoggedInUser(userName);
    }

3)And i don't think in a single request we can pass both @RequestBody and @RequestParam .
Spring MVC - Why not able to use @RequestBody and @RequestParam together


text:
Q: RelataiveLayout positioning Im trying to achieve a layout using Android XML Layout template:
Layout Diagram
I have XML currently:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="12dp"
    android:layout_marginTop="0dp"
    android:background="@color/grey"
    android:clickable="true"
    android:orientation="horizontal"
    android:padding="0dp">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="false"
        android:layout_centerVertical="true"
        android:layout_marginBottom="0dp"
        android:duplicateParentState="true"
        android:orientation="horizontal"
        android:gravity="center_horizontal"
        android:paddingTop="@dimen/schedule_row_paddingtop">

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/home_row_teamLogoHeight"
            android:layout_centerInParent="false"
            android:layout_centerVertical="true"
            android:layout_marginBottom="0dp"
            android:duplicateParentState="true"
            android:orientation="horizontal"
            android:gravity="center_horizontal"
            android:paddingTop="6dp">

            <ImageView
                android:id="@+id/teamALogo"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:scaleType="fitCenter"
                android:src="@drawable/france_logo"
                android:visibility="visible" />
        </RelativeLayout>

        <TextView
            android:id="@+id/programmeSport"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="1"
            android:text="sport"
            android:gravity="center_horizontal"
            android:textColor="@color/yellow"
            android:textAllCaps="true"
            android:textSize="@dimen/home_row_league_title"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/programmeTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/programmeSport"
            android:ellipsize="end"
            android:gravity="center_horizontal"
            android:maxLines="1"
            android:text="programme title"
            android:textColor="@color/white"
            android:layout_marginTop="-4dip"
            android:textSize="@dimen/home_row_programmeTitle"

            />

        <TextView
            android:id="@+id/programmeDay"
            android:layout_height="wrap_content"
            android:text="2:30 PM"
            android:textAllCaps="true"
            android:gravity="center_horizontal"
            android:layout_marginTop="-6dp"
            android:textColor="@color/green"
            android:textSize="@dimen/home_row_date"
            android:layout_below="@+id/programmeTitle"
            android:layout_width="match_parent"
            />

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/home_row_teamLogoHeight"
            android:layout_centerInParent="false"
            android:layout_centerVertical="true"
            android:layout_marginBottom="0dp"
            android:duplicateParentState="true"
            android:orientation="horizontal"
            android:gravity="right"
            android:paddingTop="6dp">

            <ImageView
                android:id="@+id/teamBLogo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleType="fitCenter"
                android:src="@drawable/italy_logo"
                android:layout_alignParentRight="true"
                android:gravity="center_horizontal"
                android:visibility="visible" />

        </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>

At the moment it does not look great as there is some overlapping going on, and on larger screens the "Team A Logo" and "Team B Logo" float off (as intended to be floating on the left and right side of the text) to the edges of the screen leaving a huge game besides the text in the middle:
Sample output of the issue in Android device
I need the images which float on the left and right to be in the same position vertically for each fixture and for them to be inline with the "TeamA v TeamB" horizontally.
Any assistance will be appreciated.
Thanks

A: You should follow either ConstraintLayout or LinearLayout in order to achieve your desired output.
You can do something like the below.
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/teamALogo"
    android:layout_width="100dp"
    android:layout_height="150dp"
    android:scaleType="centerCrop"
    android:src="@drawable/ic_team_a_logo"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:orientation="vertical"
    app:layout_constraintLeft_toRightOf="@id/teamALogo"
    app:layout_constraintRight_toLeftOf="@id/teamBLogo"
    app:layout_constraintTop_toTopOf="@id/teamBLogo"
    android:layout_marginTop="10dp"
    app:layout_constraintBottom_toBottomOf="@id/teamBLogo"
    >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="League"
        android:textSize="17sp"
        android:textColor="@color/black"
        android:gravity="center"
        android:textStyle="bold"
        android:layout_marginTop="5dp"
        android:padding="5dp"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Team A"
            android:textSize="17sp"
            android:textColor="@color/black"
            android:gravity="start"
            android:textStyle="normal"
            android:layout_marginTop="5dp"
            android:padding="5dp"
            />
        <TextView
            android:layout_width="0dp"
            android:layout_weight=".5"
            android:layout_height="wrap_content"
            android:text="Vs"
            android:textSize="17sp"
            android:textColor="@color/black"
            android:gravity="start"
            android:textStyle="normal"
            android:layout_marginTop="5dp"
            android:padding="5dp"
            />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Team B"
            android:textSize="17sp"
            android:textColor="@color/black"
            android:gravity="start"
            android:textStyle="normal"
            android:layout_marginTop="5dp"
            android:padding="5dp"
            />
    </LinearLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Date"
        android:textSize="17sp"
        android:textColor="@color/black"
        android:gravity="center"
        android:textStyle="bold"
        android:layout_marginTop="5dp"
        android:padding="5dp"
        />
</LinearLayout>
<ImageView
    android:id="@+id/teamBLogo"
    android:layout_width="100dp"
    android:layout_height="150dp"
    android:scaleType="centerCrop"
    android:src="@drawable/ic_team_b_logo"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: If Element not working for code I have a function below that is supposed to check if the array contains the letter X or O in a certain position. I made it so if X or O does not exist in that element that it will insert the X or O into that element. But for some reason it is not working. If say X is in the element and its O turn to put it in it just puts in O and doesnt tell me that the move was already made.
Maybe i messed up my design here?
void makeMove()
{
    if ( choosePositionX )
    {
        if (ticTacBoard[choosePositionX - 1] != 'X' || ticTacBoard[choosePositionX - 1] != 'O' )
        {
            ticTacBoard[choosePositionX - 1] = 'X';
        }
        else
            cout << "Player O has already made this move" << endl << endl;
    }

    if ( choosePositionO )
    {
        if (ticTacBoard[choosePositionO - 1] != 'X' || ticTacBoard[choosePositionO - 1] != 'O' )
        {
            ticTacBoard[choosePositionO - 1] = 'O';
        }
        else
            cout << "Player X has already made this move" << endl << endl;
    }
}

A: should'nt this be && instead of ||
because in this case, the if condition will always return true.
If you want that both of the conditions must be true, then use '&&' But I guess that you are taking OR to the literal meaning, If you want that only One of the given condition must be true than use the following expression
If you want to achieve, Either One of Both condition is true, then basically you are trying XOR operation, that could be achieved like this
if ((ticTacBoard[choosePositionX - 1] != 'X'  ||  ticTacBoard[choosePositionX - 1] != 'O' )
  && ! (ticTacBoard[choosePositionX - 1] != 'X'  &&  ticTacBoard[choosePositionX - 1] != 'O' ))

the above condition will make sure, that only one of them is TRUE. either X or O
have not tested the condition, pardon any bugs, thats an idea

A: Whatever value it has, it is always going to be either not X or not O. You check if it is not-X OR not-O. That test will always be true.
You want to check if it is X or is O. In that case, the move is already taken. Change:
    if (ticTacBoard[choosePositionX - 1] != 'X' || ticTacBoard[choosePositionX - 1] != 'O' )
    {
        ticTacBoard[choosePositionX - 1] = 'X';
    }
    else
        cout << "Player O has already made this move" << endl << endl;

to
    if (ticTacBoard[choosePositionX - 1] != 'X' && ticTacBoard[choosePositionX - 1] != 'O' )
    {
        ticTacBoard[choosePositionX - 1] = 'X';
    }
    else
        cout << "Player " << ticTacBoard[choosePositionX - 1] << " has already made this move" << endl << endl;

If the player made the move successfully, you need to change which player goes next. If not, you need to let the same player try again.


text:
Q: list of all available CSS colors (for the background) I am writing some tiny javascript where in essence the content of a input text value is used to set the backgroundColor of a div
div.style.backgroundColor = inputText.value;
The page might look like this:
Color: [black]
DIV
Because people might mispell the color I want to change it to a combobox.
The question is how do I know the list of all available colors ?
e.g. orange, cyan,blue,aqua  are standard
but blueaqua is not

A: You can see the complete list at w3c
http://www.w3.org/TR/css3-color/


text:
Q: Filter returns an empty (null) array list I have ListView that contains spinner, an image and a TextView. Above this ListView I have an EditText where a user can type his required item name and all the related items has been shown in the ListView.
My code is working till here but the problem is when i enter string in the search edit box it does that and when i start to remove the characters the list view is just disappears and there is only a blank screen. while at first the listView that contains the spinners was created successfully but after doing filter and removing all characters in the search box the view cannot be created.
Here is my code of getFilter in LazyAdapter that extends from BaseAdapter
   @SuppressLint("DefaultLocale")
        public android.widget.Filter getFilter() {

            return new android.widget.Filter() {

                @SuppressLint("DefaultLocale")
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    FilterResults Result = new FilterResults();
                    // if constraint is empty return the original names
                    if (TextUtils.isEmpty(constraint)){
                        //Result.values = storedata;
                        Result.count = listDetails.size();
                        return Result;
                    }

                    ArrayList<items> Filtered_Names = new ArrayList<items>();
                    String filterString = constraint.toString().toLowerCase();
                    String filterableString;

                    for(int i = 0; i<listDetails.size(); i++){
                         items searchdata = listDetails.get(i);
                        String title = searchdata.title();
                        String id = searchdata.id();
                        String imageUrl = searchdata.imageUrl();
                        String pprice = searchdata.pprice();
                        String shippingPrice = searchdata.shippingPrice();
                        String stock = searchdata.stock();

                        filterableString = title+" "+id+" "+imageUrl+" "+pprice+" "+shippingPrice+" "+status+" "+stitle+" "+stock+"
                        if(filterableString.toLowerCase().contains(filterString)){
                        Filtered_Names.add(listDetails.get(i));
                        //Log.e("Added", String.valueOf(Filtered_Names.size()));
                        }

                        }
                    Result.values = Filtered_Names;
                    Result.count = Filtered_Names.size();
                    //Log.e("Results", Result.values.toString() + String.valueOf(Result.count));
                    return Result;
                }

                @Override
                protected void publishResults(CharSequence constraint,
                        FilterResults results) {
                    // TODO Auto-generated method stub
                     @SuppressWarnings("unchecked")
                    ArrayList<items> resultList =(ArrayList<items>) results.values;
        LazyAdapter.this.listDetails = resultList;
        LazyAdapter.this.notifyDataSetChanged();
                }

            };

        }

This is the constructor of LazyAdapter
public  LazyAdapte(Context context , ArrayList<items> list)
    {
        this.context = context;
        listDetails = list;
         downloader = new ImageDownloader();
    }

And here is my getCount() Method
 @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return listDetails == null ? 0 : listDetails.size();
        }

and here is the code in the Activity
public class ItemsActivity extends Activity{

    EditText inputsearch;
    LazyAdapter adapter;
    ArrayList<items> list;
    Controller control;

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.items_activity);

        RelativeLayout layout = (RelativeLayout) findViewById(R.id._view);

        control = (Controller) getApplicationContext();
        list = (ArrayList<items>) control.Table_items.GetData();
        final ListView listview = (ListView)findViewById(R.id._data);

        final LazyAdapter adapter = new LazyAdapter(this, list);
        adapter.setLayout(this, layout);
        listview.setAdapter(adapter);

    inputSearch = (EditText) findViewById(R.id.inputsearch);
    if(adapter!=null){
    }
     inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {

                try{
                    ItemsActivity.this.adapter.getFilter().filter(cs.toString());
                }catch(Exception e){
                    e.printStackTrace();
                }

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub

            }
        });
}
}

Here is the stack trace
 Android Runtime E:com.example.itemspac.LazyAdapter.<init>(LazyAdapter.java:36)
at com.example.itemspac.LazyAdapter.<init>(LazyAdapter.java:41)

Here the line number 36 is of Constructor public LazyAdapter(Context context , ArrayList<items> list) and 41 is imagedownloader in LazyAdapter

A: In this following snippet from your code:
if (TextUtils.isEmpty(constraint)){
    //Result.values = storedata;
    Result.count = listDetails.size();
    return Result;
 }

you have are not setting  Result.values. This could result in your adapter's getCount() being null.


text:
Q: Cognos Content store - decode objid I want to get a report of all user names and User IDs. I got the User names but see the UserIDs are in encrypted format. Please help me on How to decrypt the objid in the Content store table CMOBJPROPS1 or any other way to achieve this?

A: There's no report you can run or any way that you can do this from within Cognos, sorry about that.
BUT there's this nifty tool which IBM offers as is, and it does probably exactly what you're looking for: http://www-01.ibm.com/support/docview.wss?uid=swg24034217
You can even export the data if you do want to report off it.
PS: Don't report off the Content Store, it's not a good idea. If you did want to see usernames you could look at cmobjprops33 I guess. Just use the tool, it's better all around.


text:
Q: How do I install a mock Tango Control System server? I need to install a mock Tango Distributed Control System server. Following the instructions on http://www.tango-controls.org/howtos/binary_deb I have done the following (installing on a VirtualBox client running 11.10):

*

*Disabled IPv6

*Ignored wifi instructions (VB client is told it is using ethernet)

*Updated /etc/hosts to reflect current IP (my network address changes occasionally, so I will update it when it does)

*Added the ppa:tango-controls/core PPA

*Following the steps for Installing Tango on a control system main server

*

*Installed the mysql-server package, created a root password for the database

*Installed the python-pytango package - the correct hostname was already filled in when I was prompted for it

*Installed the tango-starter and tango-db packages - filled in a password here

*Did not install libtango-java package (I am using Python)

*Installed the omninotify package

*Did not install tango-accesscontrol (I don't think I need this)

*Installed the tango-test package (it seemed like a good idea)

*Did not know what to do about the following "Nevertheless, the path used by the Starter device server to find other device server process executable is not initialized. You have to do it according to how you configure your system using the Starter device property or even better using the Astor GUI."

*

*Where do I go to configure this?

*I could not find a download for Astor on http://www.esrf.eu/computing/cs/tango/tango_doc/tools_doc/astor_doc/index.html - should I be looking elsewhere?

*The Astor page above looks a bit old. Is there maybe a newer configuration tool?

*I forged ahead anyway, following the PyTango quick tour:

*

*ipython -p spock (successful)

*PyTango.__version__ (returned '7.2.0')

*tangotest = DeviceProxy("

*returns sys/access_control/1 sys/database/2 sys/tg_test/1 tango/admin/mycomputer

*tangotest = DeviceProxy("sys/tg_test/1") (no results, looks successful)

*tangotest.ping() (returns an error requesting tango_error)

*tango_error returns full version of the previous error:

API_CantConnectToDevice : Failed to connect to device sys/tg_test/1
The connection request was delayed.
The last connection request was done less than 1000 ms ago
For more detailed information type: tango_error

Spock  [9]: tango_error
Last tango error:
DevFailed[
DevError[
    desc = Failed to connect to device sys/tg_test/1
           The connection request was delayed.
           The last connection request was done less than 1000 ms ago
  origin = Connection::reconnect
  reason = API_CantConnectToDevice
severity = ERR]
]

Where to next?

A: *

*Astor is a Java application and therefore, it is part of the libtango-java package.
If you want Astor, you have to install this package.

*Pb with sys/tg_test/1. DeviceProxy creation is a stateless action. It always succeed
(except in some rare case like wrong device name syntax). The error is reported only when
you access the device (what you did with "ping"). If you want to access the device
sys/tg_test/1, you have to start the device server in charge of this device. In your case, it is the TangoTest device server.


text:
Q: Clarification of methods for using non-parametric tests to compare groups- vegan package I would like to validate my approach to comparing groups using non-parametric tests. data created below describes the structure of my data. Each var. corresponds to the average concentration of a substance that was measured in an individual (ID) that was randomly sampled from a population of interest (Loc):
set.seed(123)
data <- data.frame(
                   Loc = rep(letters[1:20], each = 20),
                   ID = sample(600,400,replace = F),
                   var1 = rnorm(400),
                   var2 = rnorm(400),
                   var3 = rnorm(400),
                   var4 = rnorm(400),
                   var5 = rnorm(400))

The data frame created above serves only to explain the structure of my data, and allow me to demonstrate how I am doing this analysis (you will not get the same answers I am describing in my questions by using this data, but the process I am using can be replicated with it).
My goal is to determine which locations (Locs) can be differentiated based on the concentrations of these substances, and which substances are contributing to those differences. The substance data does not meet the assumptions required of parametric tests, and my real data set is fairly unbalanced (samples per Loc range from n=6 to n=17). Therefore to answer my questions I have been learning to use the vegan package in R to conduct non-parametric tests, much of which is relatively new to me, which is why I am seeking validation. To perform a PERMANOVA, I started by using the vegdist function to create the distance matrix using Euclidean distance:
vars <- data[,3:7]
dmat <- vegdist(vars, method = "euclidean")

Next I used the adonis() function to fit the model, and viewed the results via aov.tab:
mod <- Adonis(dmat ~ data$Loc, method = "euclidean")
mod$aov.tab

The results were significant, indicating that there is a statistically significant difference between at least two Locs in either dispersion or location of their centroids. To rule out over-dispersion I used the betadisper() function to calculate the average distance of each group to the groups centroid, and used both an anova and a permutation test to look for differences:
betad <- betadisper(dmat, data$Loc)
anova(betad)
permutes(betad)

The dissimilarity coefficients did not produce any principle coordinate axes with negative eigenvalues, and both tests gave insignificant results (p<0.05), which suggests that there is indeed support for differences in substance concentrations between the Locs. To further support this idea, I used an anosim on the dissimilarity matrix, which compared the average-ranked dissimilarities between the Locs to the average-ranked dissimilarities within the Locs:
aosim(dmat, data$Loc)

These results came back significant (p>0.05), further suggesting differences between the Locs in terms of substances.
I believe that up to this point I have done everything correctly (correct me if I am wrong, or should have done something differently). What I am really not sure about is the appropriate next steps to take in order to determine where these differences exist. If I were doing a parametric MANOVA, the next thing I would probably do is conduct univariate ANOVAs to compare Locs using each individual var. But in this situation, it is very unclear to me what the appropriate next step would be with a categorical grouping variable and continuous predictors. What can I use to further examine where these differences exist?

A: You say that your "goal is to determine which locations (Locs) can be differentiated based on the concentrations of these substances, and which substances are contributing to those differences".
Your analysis so far focuses on the first part of your goal - I haven't run through each step, but it looks sensible to me.
Your second goal is to determine which substances contribute to the differences between locations that you have observed. For some context, vegan is normally used for analysis of ecological data, and your question is equivalent to analysis for determining which species contribute most to differences in biological communities.
There are several methods - they generally give similar results so it's up to you what to use. I'll give some names and links:
simper - see https://mb3is.megx.net/gustame/dissimilarity-based-methods/simper
Indicator species analysis - see https://jkzorz.github.io/2019/07/02/Indicator-species-analysis.html
model‐based analysis of multivariate abundance data (mvabund) - https://besjournals.onlinelibrary.wiley.com/doi/10.1111/j.2041-210X.2012.00190.x


text:
Q: How to set chmod for a folder and all of its subfolders and files in PHP? I think my question explains everything. I want to use php's chmod() function to set a 777 permission on a folder, its subfolders and files.
Any Help is appreciated. THX.

A: chmod("Folder",0770);

function in php allow you to change permission of file and
for recursive change use exec
exec ("find /path/to/folder -type d -exec chmod 0770 {} +");//for sub directory
exec ("find /path/to/folder -type f -exec chmod 0644 {} +");//for files inside directory

make sure that your webserver have write access to the Folder.
Check these for more detail
http://php.net/manual/en/function.chmod.php
http://www.w3schools.com/php/func_filesystem_chmod.asp

A: There's a long winded way to do it in php, I would personally do it via the command line which PHP can interact with.
On the command line (Linux/Unix) you can do chmod options permissions filename
To recursively change permissions you would do chmod -R 0777 masterFile
So in PHP you would do exec("chmod -R 0777 masterFile");
-R means recursive so it would go to your sub-folders
The long winded way to do in PHP alone would be to get an array of the sub folders and do a foreach loop and run the chmod() function in PHP, but this way is cleaner.
See this link for more information on linux/unix chmod
Hope this helps.


text:
Q: Mouseup after Draging without library I have some pure css snap scroll functionality and I want to detect where an element is relative to the viewport after the user stop dragging.
The thing is I don't wan't to use some fancy library because I don't need to actually move or drop something.
I just wan't to fire an event on mouseup. My problem is that the mouseup event won't fire after I moved my cursor while having the left mouse button pressed.
Btw. I'm using Vu3

I hope to find a lightweight solution, scince I don't really need all this dragging functionality

A: As far as I know you can try something like

and in your methods
methods: {
   myFunction() {
    var x = e.clientX;
    var y = e.clientY;
    var coor = "Coordinates: (" + x + "," + y + ")";
    console.log(cor);
  }
}


text:
Q: Triac get burnt after driving 2 min 1.5kW resistive load I am trying to drive a 1.5kW heating resistance using QJ6025LH5TP triac.  Schematic and PCB layout.

So the thing is that my circuit is working for a while and I trying to measure the temperature from behind the PCB using an infrared thermometer. There is a significant temperature rising after 2 min resistance switch on and after a while triac get burnt completely.
Strange thing is that I have seen 3 different scenarios these are once R28 gate resistor is get burnt second MT1 and MT2 terminals got short circuit and R40,R14 got burnt. You may also see the heatsink that I am using which should be sufficient to drive 1.5kW load.

So it is most common triac driving circuit the only big difference is generally load is placed on MT2 side however in my configuration load is connected to MT1 terminal. but for optocoupler driving usage in should be okay. Waiting for your comments.


text:
Q: Optimal way of assigning SLURM tasks/nodes/cpus/arrays for many independent jobs I'd like to run 100 python simulations independently. The bottelneck in each simulation is handled by numpy calculations. I'm trying something like
#SBATCH --ntasks-per-node=1
#SBATCH --cpus-per-task=2
#SBATCH --array=1-100

srun python -u mycode.py

but I'm really confused about the best way to go about this. Should I assign more tasks per node? Should I use more cpus per tasks? I don't have a very good understanding about how these things are related.


text:
Q: Can't Update Phone Number in Codeigniter I cant seem to update the Phone Number, I am new to Codeigniter and been trying to figure out what I am doing wrong.
This is my MODEL:
function updatePhone($submit_userid, $submit_phone) {
$this->db->where("intMemberID", $submit_userid);
$this->db->update("tblMembers", array(
    "strPhoneNumber" => $submit_phone
));

}
This is my CONTROLLER:
public function updateAccount() {
    $this->load->model('updateModel');
    $this->load->model('userModel');

    $data['userdata'] = $this->session->userdata('userobject');

    $this->form_validation->set_rules('phone', 'Phone', 'required|min_length[8]|max_length[12]|xss_clean');

    if ($this->form_validation->run() == false) {

        $this->load->view('updateView', $data);
    } else {

        $submit_userid = $this->input->post('userid');
        $submit_phone = $this->input->post('phone');

        $this->userModel->updatePhone($submit_userid, $submit_phone);

        redirect('updateController/updateAccount');
    }
}

This is my VIEW:
<?php
        echo validation_errors();
        echo form_open('updateController/updateAccount');

        echo '<input type="hidden" name="userid" value=' . $userdata->intMemberID . '/>
';
        echo "$userdata->strMemberFirstName $userdata->strMemberLastName";
        echo "
";
        echo "Phone Number: <input type='text' name='phone' placeholder='$userdata->strPhoneNumber'/>";
        echo '<INPUT type="submit" value="Update" name="submit"/>';

        echo form_close();
        ?>

A: you can try this update statement, even if this doesnot works out then please check the column type you are using (varchar or whatever and its size if its conflicting or not)
    <?php
        $data['strPhoneNumber'] = $submit_phone;
        $this->db->where('intMemberID', $submit_userid)->update('tblMembers', $data);
    ?>

A: You never perform an update to the database. The select statement is not needed in an update, you pass the table name to the update method.
function getUpdate($submit_userid, $submit_phone) {
    $this->db->where("intMemberID", $submit_userid);
    $this->db->update("tblMembers", array(
        "strPhoneNumber" => $submit_phone
    ));
}

And you shouldn't really call the method getUpdate, it's not really semantic since you're not actually getting anything. updatePhone might be a better name.

A: try to print out the error
return $this->db->update("tblMembers", array );

var_dump the updatePhone result and you will see whether there is an error with table or something else
make sure it returns true before redirecting

A: $data = array(
    "strPhoneNumber" => $submit_phone
);

$where = "intMemberID = ".$intMemberID;
//generate the query string not executing
$str = $this->db->update_string('tblMembers', $data, $where);

echo '
';
echo $str;
die;

Put the above code in your function, verify the query string


text:
Q: Django links on base template
*

*Django 1.5.1

*Experience, getting started

I'm currently working on my static side of the site.
And creating the HTML/CSS/JS stuff. In the base html i have some links.
One of them is "about" that will lead to the ...:8000/about
Now when im on the about page there are the same links cause they are in the base template.
When i click on them now i get ...:8000/about/about
and it will go on adding the /about each time i click.
How should i get this link to always point to ...:8000/about
Thank you.

A: Absolute URLs.. start your links with /
 instead of
Also, if it will "add /about" each time you click, that means you're re-rendering your view... which means your URLConf probably has a too-broad regex (make sure your line is terminated by a /$
Kind of sounds like you have a line like url(r'^about/', 'foo') where /about/about/about will continue to match.

It's also best practice to use the {% url %} tag via named urls. Sooner or later you'll change a URL and thank everyone for it.
https://docs.djangoproject.com/en/dev/topics/http/urls/#named-groups


text:
Q: How to find out if a Skype call is currently active on Android Okay, I decompiled Skype's manifest to find out if there are any Services or Broadcasts running during a call.
There are only a few internal broadcasts for incoming calls. Also only one receiver and one service exist.
I monitored all running services with my app, but the SkypeMainService is always running, even if not in a call.
Also AudioMode is not changed by skype (but according to the logcat-logs the dev wanted to, but they just don't do it), so I cannot simply check if it is MODE_IN_CALL.
Do you have any suggestions how to find out, if Skype is currently running and having an active call?
Thanks!
/edit: A brief overview of the Activities etc:
<activity android:name="com.skype.raider.Main">
<activity-alias android:name="com.skype.raider.ui.SplashScreenActivity" android:targetActivity="com.skype.raider.Main">
<receiver android:name="com.skype.MainReceiver" android:enabled="true" android:exported="false">
   <action android:name="android.intent.action.BOOT_COMPLETED" />
   <action android:name="android.intent.action.MEDIA_MOUNTED" />
   <action android:name="android.intent.action.SEARCH" />
   <action android:name="android.intent.action.CALL_PRIVILEGED" />
   <action android:name="com.skype.raider.INCOMING_GSM_CALL" />
   <action android:name="com.skype.raider.ON_GSM_CALL" />
   <action android:name="com.skype.raider.intent.action.request_sync" />
</receiver>
<service android:name="com.skype.MainService">

A: Okay, I really hoped someone would provide a useful answer. However, I picked up Reuben's advice in the comment and made this method:
/**
 * Gets the current activity
 *
 * @param context
 *            A context to use
 * @return The Activity name
 */
public static String getCurrentTopActivity(Context context) {
    ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
    ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
    return ar.topActivity.getClassName().toString();
}

Then I check if the result equals  com.skype.raider.Main. This will also return true if there is no active Skype call, but the main app is open.
Thanks for all the help, especially Reuben!
Edit: Your will need the following permission in your manifest
<uses-permission android:name="android.permission.GET_TASKS"/>

A: The day Skype changes any of this (might be in that update that's coming in 2 days from now - before you finish coding) your code might break. So I don't think its worth attempting anything of this sort.
I am sorry, this might not be an "answer", but I don't think time invested into this is worth it.

A: There is a few things that you can do to increase your chance of guessing it:
1) Check if the application is running:
ActivityManager activityManager = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
    List<RunningAppProcessInfo> procInfos = actvityManager.getRunningAppProcesses();
    for(int i = 0; i < procInfos.size(); i++){
        if(procInfos.get(i).processName.equals("com.android.browser")) {
            Toast.makeText(getApplicationContext(), "Browser is running", Toast.LENGTH_LONG).show();
        }
    }

2) Check the phone state for data exchanging using the PhoneManager
3) and finally check Skype developers page for any known api


text:
Q: Unity RayCast does hit the object but it is NOT showing in the scene view or game view I recently started Unity and I ran into a problem with RayCasting. My code seems to work since the console gives me the information that the cube has been hit, but it doesn't show me the ray in the scene view nor the game view. The script I used is the following:
public class RayCast : MonoBehaviour
{
    Ray ray;
    public LayerMask layersToHit;

    void Start()
    {
        ray = new Ray(transform.position, transform.forward);
        Debug.DrawRay(ray.origin, ray.direction * 100f, Color.blue);

        CheckForColliders();
    }

    void CheckForColliders()
    {
        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            Debug.Log(hit.collider.gameObject.name + " was hit ");
            Debug.DrawRay(ray.origin, ray.direction * 10, Color.red, 10f);
        }
    }
}

Now I also selected the LayersToHit in Unity to hit the connectors which are attached to the little cubes. What is wrong with the code for actually drawing the rays on the screen? Or do I need to change anything in the settings?
Thanks in advance!
edit: New code:
public class RayCast : MonoBehaviour
{
    private Ray ray;
    public LayerMask layersToHit;

    void Start()
    {
        ray = new Ray(transform.position, transform.forward);
        //Debug.DrawRay(ray.origin, ray.direction * 100f, Color.blue);
        CheckForColliders();
    }

    void CheckForColliders()
    {
        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            Debug.Log(hit.collider.gameObject.name + " was hit ");
            //Debug.DrawRay(ray.origin, ray.direction * 10, Color.red, 10f);

        }
    }
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawRay(ray.origin, ray.direction * 100f);
    }
}

A: I tested your code and it works fine in my computer. So I think the problem might be a setting.
Explanation:
void Start()
{
    ray = new Ray(transform.position, transform.forward);

    /* Here you are drawing the first ray, you did not have a duration set
    for this one */
    Debug.DrawRay(ray.origin, ray.direction * 100f, Color.blue, 10f);

    CheckForColliders();
}

void CheckForColliders()
{
    if (Physics.Raycast(ray, out RaycastHit hit))
    {
        Debug.Log(hit.collider.gameObject.name + " was hit ");

        // Here you are drawing the line again.
        Debug.DrawRay(ray.origin, ray.direction * 10, Color.red, 10f);
    }
}

This code runs fine but I´m not sure if you intended to draw the line twice, I presume the problem is the one I describe below, in the following link there is an image that shows the setting you may not have enabled and also shows the line being drawn.
Check if the draw Gizmos button on the top right of the scene view window is enabled.
Also if you want to be able to see the Ray without running the game your code should look like this:
private Ray ray;
public LayerMask layersToHit;

void Start()
{
    ray = new Ray(transform.position, transform.forward);
    //Debug.DrawRay(ray.origin, ray.direction * 100f, Color.blue);
    CheckForColliders();
}

void CheckForColliders()
{
    if (Physics.Raycast(ray, out RaycastHit hit))
    {
        Debug.Log(hit.collider.gameObject.name + " was hit ");
        //Debug.DrawRay(ray.origin, ray.direction * 10, Color.red, 10f);

    }
}
private void OnDrawGizmos()
{
    ray = new Ray(transform.position, transform.foward);
    Gizmos.color= Color.red;
    Gizmos.DrawRay(ray.origin, ray.direction * 100f);
}


text:
Q: Issues with passing structures into functions I have several years of experience with java, but I'm very new to C. I'm still struggling to figure out when and when not to use pointers. I was given this base code and need to finish the 'push' method so that it pushes the next element onto the stack, but I'm getting errors saying:
request for member 'top' in something not a structure.
#include <assert.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>

int exit_status = EXIT_SUCCESS;
#define EMPTY (-1)
#define SIZE 16

typedef struct stack stack;
   struct stack {
   int top;
   double numbers[SIZE];
};

void push (stack *the_stack, double number) {
    if(&&the_stack.top>=SIZE-1){
       printf("error");
    }else{
       the_stack.numbers[&&the_stack.top++ ] = number;
    }
}
int main (int argc, char **argv) {
  if (argc != 1) {
     fprintf (stderr, "Usage: %s\n", basename (argv[0]));
     fflush (NULL);
     exit (EXIT_FAILURE);
  }
stack the_stack;
the_stack.top = EMPTY;
char buffer[1024];
for (;;) {
   int scanrc = scanf ("%1023s", buffer);
   if (scanrc == EOF) break;
   assert (scanrc == 1);
   if (buffer[0] == '#') {
     scanrc = scanf ("%1023[^\n]", buffer);
     continue;
  }
  char *endptr;
  double number = strtod (buffer, &endptr);
  if (*endptr == '\0') {
     push (&the_stack, number);
  }else if (buffer[1] != '\0') {
     bad_operator (buffer);
  }else {
     do_operator (&the_stack, buffer);
  }
}
 return exit_status;
}

Am I overlooking something very basic?

A: When accessing members of a structure, there are two operators: The dot operator . which is used for non-pointer structures, and the "arrow" operator -> which is used for pointers to structures.
You have a pointer to a structure in your push function, so you need to use the "arrow" operator.

There are other problems with your code, like the double ampersand in the push function. You also don't need to flush any files when exiting the program, the runtime will do that for you.

A: It seems very clearly that you have less experience in C. There are lots of compile time errors in your code like for example :

In push function top and numbers should be invoked as :
the_stack->top
the_stack->numbers[]
An arrow is used to invoke the members of a pointer variable.
Now Comparing it with Java:
Java uses only references not pointers. But internally they are pointing to some location in memory.
https://www.dropbox.com/s/qfk86yb3drdlmz2/C%20to%20Java.JPG     Image
http://erikdemaine.org/papers/CPE98/paper.pdf                   Paper
Check this link to correlate C code and Java code.


text:
Q: Proof of Hasse-Minkowski over Number Field Can anyone point me towards a good reference which contains the proof of the Hasse-Minkowski theorem of quadratic forms over a number field? Serre's "A Course in Arithmetic" has a self contained proof for the theorem when the base field is $\mathbb{Q}$, but I am looking for the more general setting.

A: The proof of Hasse-Minkowski for more general global fields can be found in O'Meara, Introduction to Quadratic Forms, Springer-Verlag, 1973.

A: My memory is that this is given as an exercise in Cassels and Frolich (the exercises were actually written by Serre and Tate).  One uses the fact that being a norm in a cyclic extension of number fields can be detected locally (the so-called Hasse norm theorem), which deals with the case of representations by binary quadratic forms.  Forms in more variables are then handled by induction. (Possibly I'm simplifying here, but this
is the basic idea.)
If I understand correctly, this is true to history: Hasse's contribution to the theorem was to prove it over number fields, using his norm theorem for cyclic extensions as the initial input.

A: Other than O'Meara (pronounce O Marra, who knew?), Lam (2005), Introduction to Quadratic Forms over Fields, gives a proof for global fields modulo two assumed results on page 171.
Theorem 3.7 says that $a$ is a square in the global field if and only if it is a square at each place. I think that's only fair.
Theorem 3.8 says that a quaternion algebra splits if and only if it splits at each place. He mentions that this may be regarded as either a special case of either the Brauer-Hasse-Noether Theorem or as a special case of the Hasse Norm Theorem.
Cassels, Rational Quadratic Forms, points out on page 96 that there are fields where the Weak Hasse Principle holds but the Strong Hasse Principle does not. Then he sketches a proof for number fields in a page.
Cassels does use Dirichlet on primes in arithmetic progressions for Chapter 6, and Lam mentions that assuming that would be one way to deal with number fields; so I suggest that as a good exercise for a graduate student, see how far you get with Lam's treatment plus Dirichlet on primes.
Oh, try Shimura's 2010 book Arithmetic of Quadratic Forms
 if you want to do things like prove the Mass Formula.


text:
Q: Function argument for all values in R (raster extract, and velox raster extract) I'm using the package velox to speed up raster extraction.
Simple question (and probably an easy one): what is the argument in R for fun=all values?
Context:
In the raster package the function extract fun=NULL is to return all pixel values. In velox the extract requires an argument "fun=". What is the function argument that will return all the cell values like the fun=NULL of the extract in the raster package?
Bonus points if you have a function that will take the mean while ignoring NA values (which is what I'm trying to do anyhow). Something along the lines of
meanvalue <- raster::extract(testraster, testpoly, fun=mean if x !=NA)

Id then use it on a velox raster (should work the same) like this rather than the above code:
meanvalue <- velox.testraster$extract(testpoly, fun=mean if x !=NA)

Fun=mean doesn't work because some of my polygons have NA values for pixels since they are not covered by the raster.

A: Got it:
fun <- function(x){mean(x, na.rm=TRUE)})

for velox:
sample.list <- sampleVeloxraster$extract(sampleshp, fun=function(x){mean(x, na.rm=TRUE)})


text:
Q: LaTeX doesn't recognize "et al." in the Bibliography I'm using Jabref to manage my Bibliography.
Sometimes, I put directly:

First Author et al.

when adding the article author's name in Jabref.
When compiling my .tex file, LaTeX doesn't recognize the et. al as more names. It takes it as a name/surname.
This is an example of a Bibliography entry in Jabref.
@ARTICLE{Wolf2003,
  author = {Wolf, K.et al.},
  title = {Compensation mechanism in tumor cell migration: mesenchymal–amoeboid
    transition after blocking of pericellular proteolysis},
  journal = {J. Cell Biol.},
  year = {2003},
  volume = {160},
  pages = {267–277},
 }

This is a .texMWE with the bib entry mentioned:
\documentclass[11pt]{book}
\usepackage{cite}
\bibliographystyle{unsrt}
\begin{document}
Here is the bib entry mentioned\cite{Wolf2003}

\bibliography{bibfile}
\end{document}

Here's the output:

How can I solve this problem?

A: I imagine two reasons for you to ask this question:

*

*You only have partial information about your references → use egreg's great answer in this case.

*What you really want is how to display one author name only in your bibliography/citation. (You here thus face a X/Y problem.)

The solution below answer this second question.

I would suggest you to keep as much information as possible in your database (in the event that you change your mind later or in another document).
To show only one author name in your bibliography, you can use features of you bibliographical package. With the package biblatex, the relevant option is maxnames=<maximal number of authors to display>.

\documentclass{article}

    \usepackage[
        maxnames=1,%<---------- the key option
        style=authoryear-comp,
    ]{biblatex}
    \addbibresource{\jobname.bib}

    \usepackage{filecontents}

    \begin{filecontents}{\jobname.bib}
        @book{keyone,
            author = {Single Author, A.},
            year = {2001},
            title = {Title},
            publisher = {Publisher},
        }
        @book{keytwo,
            author = {Firstof Threeauthors, J. and Secondof Threeauthors, E. and Thirdof Threeautors, G.},
            year = {2017},
            title = {A catchy title},
            publisher = {Same publisher},
        }
    \end{filecontents}

\begin{document}
    First reference: \cite{keyone}. Second one: \cite{keytwo}.

    Which are these references' authors? \citeauthor{keyone} and \citeauthor{keytwo}, respectively.

    \printbibliography
\end{document}

Note that you can differentiate between the number of authors listed in a citation (option maxcitenames=), and in the bibliography (maxbibnames=). The option maxnames= just sets both of these options together.
If you have max[x]names > 1, you might want to specify the fallback number of cited names if your reference contains more than max[x]names authors. In other words, define:

If my reference has x authors or less, then cite all of them. Otherwise, cite only the y first authors, and append 'et al'.

For that, you can use the minnames= option:
    \usepackage[
        maxnames=<x>,
        minnames=<y>,
    ]{biblatex}

Obviously, one assume x >= y. And similarly, you can define mincitenames and minbibnames separately.
Example with maxnames=2, minnames=2

Same example with maxnames=2, minnames=1

A: The input conventions of BibTeX are rather strict; multiple authors must be separated by the and keyword:
author={Alpher, Ralph and Bethe, Hans and Gamow, George}

or, if you want to keep only initials,
author={Alpher, R. and Bethe, H. and Gamow, G.}

If you want only the first author and automatically add et al. in the bibliography, use the others keyword:
author={Alpher, R. and others}

A: We know that et al. is Latin, and should thus appear in italic.
Thing is author={Alpher, R. and others} generates et al. as a normal font and not italic.
A quick, also dirty fix, modified from the above is the following:
author = {Smith {\textit{et al.}}, Fred}

A: Using suggestions above, I found that this works.
To write
Fred Smith et al.
I used
author = {Smith {et al.}, Fred}


text:
Q: Possible to block traffic on port 443 by destination IP? Is it possible to block traffic on port 443 based on the destination's ip address or is that encrypted?

A: Remember that networking works with layers: (simplified)

*

*IP

*TCP

*SSL

*data (HTTP for example)

The IP address is below the SSL layers, so it is not "encrypted". Your firewall can do filtering based on the source and destination IP and destination TCP port (443).


text:
Q: setOnCloseRequest Java FXML Well, I'm using JavaFX FXML, there's less info than just JavaFX, so I can use MVC, but I'm having trouble with adding a Confirmation Dialog so if i press alt + f4 or exit button in the window, a little confirmation dialog will show.
I found this, putting a event on setOnCloseOperation, does the job.

A: import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

public class Main extends Application {

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("close.fxml"));

    Scene scene = new Scene(root);

    stage.setOnCloseRequest(e -> {
        e.consume(); // stop the event to do something before quitting
        closeRequest(stage); // method used to show a confirmation dialog
    });

    stage.setScene(scene);
    stage.show();
}

private void closeRequest(Stage stage){

    String msg =
            "Sure to quit?";
    Alert alerta = new Alert(Alert.AlertType.CONFIRMATION);
    alerta.initStyle(StageStyle.DECORATED);
    alerta.initModality(Modality.APPLICATION_MODAL);
    alerta.initOwner(stage);
    alerta.getDialogPane().setContentText(msg);
    alerta.getDialogPane().setHeaderText(null);
    alerta.showAndWait()
            .filter(response -> response == ButtonType.OK)
            .ifPresent(response -> { stage.close(); }); // then we need to call the close method for a stage, if the response is ok.

}

public static void main(String[] args) {
    launch(args);
}

}

So in your main class, the one that loads the fxml resource, you need to use the method setOnCloseOperation.
Fisrt you need to consume the event so you stop the program to be finished.
Then we call a method to show a confirmation box, then we can call .close method to close the stage.


text:
Q: SARIMA, coefficients check I would appreciate if someone could check the mathematical equation for the seasonal ARIMA (4,1,4) x (1,1,1) period 12 that I wrote. I have done it this way, but I am not really sure if it correct is. Can someone check it and correct it? I would be graetfull.
$(1+0.0789359 B - 0.0007957 B^2- 0.7559195B^3 + 0.2814265B^4)(1+0.0851737 B^{12}) (1-B) (1-B^{12}) Y_t= (1 - 0.4212575 B - 0.2042966  B^2 -0.9272988 B^3 + 0.5528213B^4)(1-0.8477401B^{12})e_t$
Please just tell me if I am thinking right.
Coefficients here:

Thank you for your answer!
but how can I simplify it?
I am very new to SARIMA and I am really facing a poblem which p,q,P,Q to use. Here is ACF and PACF of first-difference (two top plots),  and ACF and PACF of first-seasonal difference.
I think that P=1, Q=1 because ACF and PACF of first-seasonal difference drop off at lag 1 and are outside the confidence band. What about p and q ? Can I then say that p=2 and q=2 because it drop of at lag 2? Or should I take under consideration the fact that only at lag 4 ACF and PACF are outside confidence band? Is p=4 and q=4 or 2 for both?
Or should I do AIC test for (2,1,2)(1,1,1)12, (4,1,2)(1,1,1)12, (2,1,4)(1,1,1)12, (4,1,4)(1,1,1)12 and check which one has the smallest? Or assuming that p=2 and q=2 does not make any sense because its within the confidence band?


text:
Q: Native steam games don't launch (vulkan shaders don't work) Hello i have kubutnu 21.10
this happened after the update from 21.04 to 21.10
i have noticed that when i run native linux steam games they don't work, i'm suspecting that there is a problem with vulkan, but when i launch a non steam game it basically skips the processing vulkan shaders and launches the game. I remember when i launcher rocket league it used tot ake a long time to process vulkan shaders now it just doesen't do that. csgo and tf2 don't launch at all.
I hope there is a way to fix this.
Thanks in advance!
edit: portal 2 works fine with no problems

A: That package, vulkan-utils does not exist in any of the supported release.
You probably want vulkan-tools instead, which is in the repositories, and ...

Description-en: Miscellaneous Vulkan utilities  This package provides
utilities for Vulkan, including vulkaninfo.


text:
Q: Why $1$ is the only quadratic residue modulo $8$? I'm trying to understand the Proposition 5.1.1 - Ireland and Rosen, A Classical Introduction to Modern Number Theory, p.50, however, I can't understand why this argument is true:
$1$ is the only quadratic residue mod $8$.
I wrote a program to generate all quadratic residue modulo $8$, from $0$ to $7$
0 -> 0
1 -> 1
4 -> 4
9 -> 1
16 -> 0
25 -> 1
36 -> 4
Press any key to continue . . .

I saw $4$ there, so how come only $1$ satisfied?
The original text was,

Thank you,
@Bill Dubuque: Thank you for the reference.

A: Quadratic residues are usually taken from the unit group. $2$ is not in $U_8$.
The wikipedia article mentions this issue, citing Ireland and Rosen.


text:
Q: agent.add() not working, though console.log() is I am trying to implement a bot using Telegram, Dialogflow and Firebase.
I am having trouble with this function:
function findDoc(agent){
    const userId = request.body.originalDetectIntentRequest.payload.data.from.id.toString();
    const first_name = request.body.originalDetectIntentRequest.payload.data.from.first_name;
    console.log(`Telegram user ID: ${userId}, first_name: ${first_name}`);//THIS SHOWS
    agent.add(`voy a ver si existe el documento`);//THIS SHOWS
    agent.setContext({name: "firstTimer", lifespan:10});
    return db.collection('users').doc(''+userId).get()
      .then((doc) => {
        if (!doc.exists) {
          console.log(`New user created in database `);//THIS SHOWS
          agent.add(`New user created in database`);//THIS DOESN'T SHOW
          var data={
            'id':userId,
            'name':first_name,
            'contadorP': 0,
            'doneQuestions': [],
          };
          return db.runTransaction((dataDB)=>{
            dataDB.set(db.collection('users').doc(''+userId), data,{merge:true});
            return Promise.resolve();
          }).catch((err) => {
                console.error(`Error creating file: `+err);
            });
        } else {
          console.log('Found Telegram profile: ', JSON.stringify(doc.data()));//THIS SHOWS
          const data = doc.data();
          agent.add(`User ${data.id} has the name of ${data.nombre}`);//THIS DOESN'T SHOW
        }
      })
      .catch((err) => {
        console.error(err);
      });
  }

I am sure that the function works fine becasue the console.log() in the firebase console work fine as they show what they are supposed to; and I am getting no errors back either...
Here are my dependencies from my package.json:
"dependencies": {
    "actions-on-google": "^2.5.0",
    "firebase-admin": "^8.2.0",
    "firebase-functions": "^2.0.2",
    "dialogflow": "^0.6.0",
    "dialogflow-fulfillment": "^0.6.1"
  }

This is how I am handling the intents:
  intentMap.set('Default Welcome Intent', welcome);

and this is the function that calls the findDoc() function:
function welcome(agent){
    console.log(`Estoy en la funcion de welcome`);
    agent.add(`Welcome`);
    findDoc(agent);
  }

Both the console.log() and agent.add() of the welcome function are showing.
From what I have read online, the dependencies are fine and should work.So I don't know what else to try, since I have (I think) done correctly every suggestion found.Please help...

A: The issue is that, although findDoc(agent) handles things asynchronously and returns a Promise, you aren't using this promise as part of your welcome() handler. The dialogflow-fulfillment library requires you to return a Promise from your handler if you are doing any asynchronous operation.
It appears to work since the Promise is completing, so the calls to console.log() do work as expected. But since you aren't returning this Promise to the dispatcher, it only sends back everything from agent.add() up to the point of the async operations.
In your case, the solution is simple. Since findDoc() is returning a Promise, all you need to do is have welcome() return this promise as well. Something like this should work:
function welcome(agent){
  console.log(`Estoy en la funcion de welcome`);
  agent.add(`Welcome`);
  return findDoc(agent);
}


text:
Q: Magento 1.9 module oddly breaking when changing resource folder from Mysql4 to Resource It's a fresh 1.9 installation. I'm new, so I was following some guides which turned out to be outdated, and so I used Mysql4 classes instead of Resource.
I changed the extensions from Mage_Core_Model_Mysql4_Abstract to Mage_Core_Model_Resource_Db_Abstract, and they worked perfectly.
I then tried to change the name of the model/resource folder from Mysql4 to Resource.
I changed its name in the config.xml from <class>Foo_Foobar_Model_Mysql4</class> to <class>Foo_Foobar_Model_Resource</class>, and the class names of the resources from
class Foo_Foobar_Model_Mysql4_Example
To
class Foo_Foobar_Model_Resource_Example.
But for some reason, the last two steps broke the module, and I started getting:
Warning: include(/var/www/html/magento/includes/src/Foo_Foobar_Model_Resource_Example.php): failed to open stream: No such file or directory  in /var/www/html/magento/includes/src/Varien_Autoload.php on line 94

Even though the class is right there.. I tried checking the permissions and owners of the files on the server, and they're exactly the same in both cases.. What is the cause for this weird error.. Everything is the same except the folder name..

A: Disable or rebuild compilation.
Thanks to Marius too!


text:
Q: Gridsome g-image tag has limited use. What do you think? I'm building a website using Gridsome. My website has a lot of components which I then use the g-image tag.
Based on the doc, "The src attribute and options like width, height and quality must be static values because they are compiled into an object which contains URLs and other information that will be rendered into an img tag." From my understanding I can't use the tag like this (I can but it won't the benefit of using the tag):
<g-image :src="image.url" :alt="image.alt" height="100" width="100"></g-image>

Am I understanding it right? If I am I think there's very limited situation where you can use the tag, especially when most people have some sort of CMS system. What's your thought and what's your alternative?

A: Can't you just do <g-image :src="image.url" :alt="image.alt" style="height: 100px;width: 100px;"></g-image>?


text:
Q: Is there a word for "look and feel"? "Look and feel" is a term commonly used in UI, software and web design, yet we have job titles such as Web Designer, Visual Designer, Front-end Developer, UX Designer but no Look and Feel Designer. Visual Designer is probably the closest, but I've always thought this title doesn't capture the full range of what this designer does; i.e., they work on feel and visuals.
Look and Feel Designer sounds a bit awkward and wordy, but it is a good term that accurately describes the domain, so I was wondering if there were a more elegant way of stating it?

A: If you are looking for a word to describe a designer who works on both Look and Feel at the same time, without specializing in either one, you could call then a "User-Interface Designer", to refer to the fact that they are focused on making the experience of the user as easy as possible AND as appealing as possible.
Really, if a designer is working on a project at all, they should be concerned about both the look AND feel of it throughout the process (Unless, of course, it's a pure visual medium, but even then the manner in which it reaches the user could be refined).
If you're looking for a designer who manages and oversees the design process, such that they are in charge of both visual and interactive aspects of the design, you could refer to the item on which they are working (A Web Designer, or an App Designer), if it would apply to the situation.  (If they're working on a particular part of a project, like a programmer who designs the first level of a game, you could refer to the part they are working on, IE, a Level Designer).
Really the only instance I can think of where a general Designer title wouldn't encompass the entire project would be in case there is an Audio Designer separate from the person designing the "Look and Feel" aspects, in which case you could refer to the first individual as the "Interactive Designer" to reflect the fact that they are designing the interactive portion of the project.
Hopefully one of these suggestions works for you!

A: "Look and Feel", from experience, requires both programming and designing tasks, thus "Visual Designer" (too narrow) or "Web Developer" (too broad) don't cut it.
In Adobe Flex and ASP.net, a "Look and Feel" is called a Theme, and the specialty may be called Theme or Skin Developer - a person who has both the analytic skills of a programmer and the refined taste/sense of a designer. Such a person is a rare find, which might explain why there is no title for it.

A: I'm going to go out on a limb here, answer my own question, and say no, there is no word for "look and feel".
Thanks to the other two answerers for their ideas. Those thoughts serve to confirm to me that there is indeed no specific word for this concept.

A: The aesthetic (as a noun) is said to be a set of principles underlying and guiding the work of a particular artist or artistic movement. One could equate an aesthetic with a look and feel.


text:
Q: Token based authentication vs JWT or passport laravel? What's the different if I used a column in users table api_token for token auth, and if I used JWT or passport Laravel ???
My app is an e-commerce contains an API for mobile apps!

A: Token-based authentication is a protocol which allows users to verify their identity, and in return receive a unique access token. During the life of the token, users then access the website or app that the token has been issued for, rather than having to re-enter credentials each time they go back to the same webpage, app, or any resource protected with that same token.
JWT is aJSON web token (JWT) is an open standard. The finished product allows for safe, secure communication between two parties. Data is verified with a digital signature, and if it's sent via HTTP, encryption keeps the data secure
JWT has some limitations like,JWTs rely on a single key. If that key is compromised, the entire system is at risk and you can't push messages to all clients, and you can't manage clients from the server side.
Laravel Passport is native OAuth 2 server for Laravel apps. Like Cashier and Scout, you'll bring it into your app with Composer. It uses the League OAuth2 Server package as a dependency but provides a simple, easy-to-learn and easy-to-implement syntax.Passport exposes a JSON API for your frontend to consume to let you manage your clients and tokens.
Out of the box, Passport comes with Vue components that show how you might want to interact with this API in your app. You could use these components and call it done, or you could write your own tool to interact with the API.
You have to do long working Laravel Passport and it is time consuming and cinfusing.
Token-based authentication is better than JWT annd Laravel passport.


text:
Q: How to shade region under the curve in matplotlib I want to use matplotlib to illustrate the definite integral between two regions: x_0, and x_1.
How can I shade a region under a curve in matplotlib from x=-1, to x=1 given the following plot
import numpy as np
from matplotlib import pyplot as plt
def f(t):
    return t * t

t = np.arange(-4,4,1/40.)
plt.plot(t,f(t))

A: The final answer I came up with is to use fill_between.
I thought there would have been a simple shade between type method, but this does exactly what I want.
section = np.arange(-1, 1, 1/20.)
plt.fill_between(section,f(section))

A: As said before, you should use the fill_between function from pyplot.
And to fill the desired area under the curve, I recommend using the where argument that provide a filter that fit your data:
import numpy as np
from matplotlib import pyplot as plt

def f(t):
    return t * t

t = np.arange(-4,4,1/40)

#Print the curve
plt.plot(t,f(t))

#Fill under the curve
plt.fill_between(
        x= t,
        y1= f(t),
        where= (-1 < t)&(t < 1),
        color= "b",
        alpha= 0.2)

plt.show()

The where argument accepts an array of boolean. So you can use numpy arrays operations on boolean to make it easy. As you can see in the example, I simply used : (-1 < t)&(t < 1). More details on boolean array here : http://www.math.buffalo.edu/~badzioch/MTH337/PT/PT-boolean_numpy_arrays/PT-boolean_numpy_arrays.html
You can play around with the parameters alpha (opacity) and color to make it look better.
Here is the desired result :

The documentation of fill_between is available here :
https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.fill_between.html

A: Check out fill. Here's an example on filling a constrained region.