text:
Q: Linux cp Permission denied on ntfs file system Could someone kindly explain why I get this Permission Denied error?  I personally am user g and as ls shows I have read and write permission for both source and destination.  My system is slackware 14, and the device being written to is my ereader, an ntfs-3g file system.
I have other ntfs file systems, thumb drives, external HDDs etc to which I can write to as user.  There is no perceptible difference in the permissions setup for any of them.  Being ntfs, all of them are owned by root of group root.  It is only with this ereader that I have this problem (though I can write to it as root).  So I believe the problem is specific to this device, but I have no clue what it might be.
~ $ cp /home/g/MyBooks/Wyndham-TheMidwichCuckoos.txt /500gb/database/media/
cp: cannot create regular file '/500gb/database/media/Wyndham-TheMidwichCuckoos.txt': Permission denied
~ $ ls -l /home/g/MyBooks/Wyndham-TheMidwichCuckoos.txt
-rw-r--r-- 1 g users 380183 Aug 10 11:04 /home/g/MyBooks/Wyndham-TheMidwichCuckoos.txt
~ $ ls -l /500gb/database/
total 32
drwxr-xr-x 2 root root 8192 Aug 10 11:23 cache/
drwxr-xr-x 3 root root 8192 Aug  5 13:26 layout/
drwxr-xr-x 2 root root 8192 Aug  9 14:07 media/
drwxr-xr-x 2 root root 8192 Aug  5 17:28 sync/
~ $

The ereader is fat32, I had assumed it to be ntfs,
 ~ $ mount
/dev/sda3 on / type ext2 (rw)
proc on /proc type proc (rw)
sysfs on /sys type sysfs (rw)
/dev/sda4 on /home type ext2 (rw)
tmpfs on /dev/shm type tmpfs (rw)
/dev/sda1 on /winxp type fuseblk (rw,allow_other,blksize=4096,default_permissions)
/dev/sdb on /500gb type vfat (rw)
/dev/sdd1 on /3tb type fuseblk (rw,allow_other,blksize=4096)
~ $ cp /home/g/MyBooks/Wyndham-TheMidwichCuckoos.txt /3tb
~ $ cp /home/g/MyBooks/Wyndham-TheMidwichCuckoos.txt /500gb
cp: cannot create regular file '/500gb/Wyndham-TheMidwichCuckoos.txt': Permission denied
~ $
I am not able to change the permissions on this ereader, neither as root, nor as user
As root, it appears to work, but nothing changes
/home/g # chmod 777 -R /500gb/database
/home/g # ls -l /500gb/database
total 32
drwxr-xr-x 2 root root 8192 Aug 10 11:23 cache
drwxr-xr-x 3 root root 8192 Aug  5 13:26 layout
drwxr-xr-x 2 root root 8192 Aug  9 14:07 media
drwxr-xr-x 2 root root 8192 Aug  5 17:28 sync
As user, the chmod is rejected thus
~ $ chmod 777 -R /500gb/database
chmod: changing permissions of '/500gb/database': Operation not permitted
chmod: changing permissions of '/500gb/database/cache': Operation not permitted
chmod: changing permissions of '/500gb/database/cache/cacheExt.xml': Operation not permitted
chmod: changing permissions of '/500gb/database/cache/media.xml': Operation not permitted
chmod: changing permissions of '/500gb/database/cache/cacheExtSchema_1.1.xsb': Operation not permitted
chmod: changing permissions of '/500gb/database/media': Operation not permitted
chmod: changing permissions of '/500gb/database/media/Stevenson-TreasureIsland.txt': Operation not permitted
chmod: changing permissions of '/500gb/database/media/Rendell-WolftotheSlaughter.txt': Operation not permitted
This process did the trick for me, thanks to Miroslav Koskar
/home/g # mount | grep sdb
/home/g # mount /dev/sdb -o uid=1000,gid=100 /500gb
/home/g # mount | grep sdb
/dev/sdb on /500gb type vfat (rw,uid=1000,gid=100)
/home/g # ls -l /500gb/database
total 32
drwxr-xr-x 2 g users 8192 Aug 10 11:23 cache
drwxr-xr-x 3 g users 8192 Aug  5 13:26 layout
drwxr-xr-x 2 g users 8192 Aug 10 12:51 media
drwxr-xr-x 2 g users 8192 Aug  5 17:28 sync
/home/g #
~ $ cp /home/g/MyBooks/Wyndham-TheMidwichCuckoos.txt /500gb/database/media
~ $

A: It seems to me that permissions are not correctly set.

*

*you are user g and can read a file = OK

*but you can't create a file in a destination because the directory media is not writeable by you, only root can do that
So either copy as root or change the permissions on target so that you have a write permission on media directory.

As pointed out it's not possible to change permissions nor ownership on mounted NTFS filesystem. In that case there is a possibility to use proper mount options. Bellow excerpt from man mount

uid=value, gid=value and umask=value

Set the file permission on the filesystem.  The umask value is given in octal. By default, the files are owned by root and not readable by somebody else.

Example: (for /dev/sdc1 with FAT32 filesystem)
Check that the device is not mounted (following should return without output)
$ mount | grep sdc1

Mount the device with uid and gid option set
$ sudo mount /dev/sdc1 -o uid=1000,gid=1000 /mnt

Verify the mountpoint
$ mount | grep sdc1

/dev/sdc1 on /mnt type vfat (rw,relatime,uid=1000,gid=1000,fmask=0022,dmask=0022,codepage=437,iocharset=iso8859-1,shortname=mixed,errors=remount-ro)

A: The media directory is owned by root (with a group of root) and is mode 755, so it is writable only by its owner (root).  You're trying to create a file in that directory (you're not overwriting an existing file, are you?) which is treated as a modification of the directory.  And you're not running as root.
That's probably why you don't have permission.
Either chown the media directory to yourself (or chmod it so you can write to it), or run the cp under su or sudo.


text:
Q: calculation of $(x,y,z)$ in $x+\lfloor y \rfloor -\{z\} = 2.98\;\;,\lfloor x \rfloor +\{y\}-z = 4.05\;\;,-\{x\}+y+\lfloor z \rfloor = 5.01$ The no. of real solution of the equation
$x+\lfloor y \rfloor -\{z\} = 2.98\;\;,\lfloor x \rfloor +\{y\}-z = 4.05\;\;,-\{x\}+y+\lfloor z \rfloor = 5.01$.
Here I did not understand How can I solve it.
help me
Thanks.

A: I'm assuming that indeed $\{a\} = a - \lfloor a\rfloor$. Since then $0 \leqslant \{a\} < 1$ for all $a$, we have
$$-1 < \{a\} - \{b\} < 1$$
for all $a,b$. Then from the given equations we obtain, by writing $x = \lfloor x\rfloor + \{x\}$ and analogously for $y,z$, the three equations
$$\begin{gather}
\{ x\} - \{ z\} = -0.02,\tag{1}\\
\{ y\} - \{ z\} = 0.05,\tag{2}\\
\{ y\} - \{ x\} = 0.01.\tag{3}
\end{gather}$$
Adding $(1)$ and $(3)$ yields $\{y\} - \{z\} = -0.01$, which contradicts $(2)$, hence there is no solution to the system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: My for loop won't output anything (Matlab) I'm trying to get this for loop to work on Matlab so I can plot these three histograms. I'm guessing it won't output because it says that my variables such as a_M_S1 keep changing size on every loop iteration, so the process is essentially inefficient. Any help? Below is the code.
I'm basically trying to generate 500 samples of 100 readings so I can then plot a histogram using estimated parameter values.
clear
clc

% Importing Data

%a = 0.9575
for m=1:500
    seed=m;
    rng(seed);
    syms x
    F=((1/atanh(0.9575))*((0.9575^(2*x-1))/(2*x-1)));

   for n=1:100
    data_1(n)=ceil(vpasolve(F==rand(1)));
   end
    Data_1(m,:)=data_1;
end

clear
clc

Data_1=[49     1     3    17    13     3     5    51     7     1
     9     3    67     1     3     1     1     1     1    99
     5    13    21    17    41     1     1     9    23     1
     1     5     1     1    41     1    13     1     5    27
     5    37    99     1     1    33     1     1     9     1
     1     3    47    11     7     1     1    41    21    27
     5     1     1    11    45     7     3     5     1    17
    13     5     3     3     1    99     1    59     1    13
     3     5     1    35     1     1     1     1     5    19
     5     1     1     1    79     3     1     1     1     1
    31     3     1     1     1    21    69    39     1    29
     3     3     1     1     5     1     3     1     1    15
     1     1     9     1     7     1     1     1     1    11
    27     9     1     3    39     5     1     5     7     1
     1     1     7     5     1     1     3     1     3    23
     5     1    21     1     1     7     1    17     1     3
    11    11     5     1     9     1     1     1     1    37
    33     1     9     7     1     1    31    27     1     1
     5     5     1    17     3    31     1    45    37     1
     1     1    19    47     9     7     5     1     9     1
    11     1    61     5    29     1    95     1     1     1
    13    19     1     1    13     1    23     7    73     1
     1     1    11     1     5     1     3     1     7     1
    15     1     9    53     3     7     3    21     7     3
     1     7     1     1    23     7     5     1     3     1
     1     7     1     3     1     1     1     7     3     5
     1     1     1    43     7     3     1     1    21     5
     1    39     1     5    13     3     1     5     1     3
     1    11     1     1    29    17    25     1     9     1
    17     9    13    11     1     5    29     3     3     1
    65     5    63     1     1     3     5     1     7     1
    21     3     7     1     1     1    27    11    15     3
     1     1     1     1    21     1     5     3     1    11
     5     1     3     7     1     5    43     5     7    75
    29     7    83     1     3     5    15     1     1     3
     1     1     9     1    13     1    17    23     1     5
    99     1     1     1     5     7     9     3     7     1
     1    11     1    11    21     1     5     9     5     1
    33    49     3     9    15     1     1     5     1     1
     1    17     1     1     1     1    13     1     1     9
     5    13     1     1     5     3     1     1    67     1
     5     1     1     1     7    27     1    21    47     1
     1     1     1    21     3    17     1     5     5     1
     1     1    17    29    99     1     9     1     5    15
    17     5     1    13     1     1     1     1     1    21
     1    21     1     1     1    11     9    35    31    15
    99    15     1     1     9     3     1    21     1     1
     1     1     9    33     1     1    31     9    29    47
    41    99     1     7    17     5     9     3     3    13
     1    29     9     5    11     1     1     7    37    15];

 Data_2=[1     1     3     3     5     7     1     3     1     1
     1     1     1     1     1     1     1     1     1    13
     5     1     5     1     1     1     1     3     1     1
     1     1     3     1     1     1     1     3     1     1
     1     1    13     5     1     3     1     1     5     1
     3     3     1     7     3     5     3     1     3     1
     1     1     1     1     1     3     3     5     1     1
     1     1     1     9     1     1     1     1     5     1
     1     1     1     1     1    11     7     1     5     1
    17     1     1     7     3     7     3     5     5     1];

for o=1:500
    syms a
    %Method of Moments (MM)
    mean_S1 = mean(transpose(Data_1(o,:)));
    a_MM_S1(o) = vpa(vpasolve((a)/((atanh(a))*(1-a.^2)) == mean_S1,a),4);

    mean_S2 = mean(transpose(Data_2(o,:)));
    a_MM_S2(o) = vpa(vpasolve((a)/((atanh(a))*(1-a.^2)) == mean_S2,a),4);

    %Using Lower Quantile (OS)
    lower_S1 = floor(quantile(Data_1(o,:),0.25));
    a_LQ_S1(o) = vpa(vpasolve((a)/(atanh(a)) == 0.25,a),4);

    lower_S2 = floor(quantile(Data_2(o,:),0.25));
    a_LQ_S2(o) = vpa(vpasolve((a)/(atanh(a)) == 0.25,a),4);

    %Using Median (OSM)
    median_S1 = floor(quantile(Data_1(o,:),0.5));
    a_M_S1(o) = vpa(vpasolve((a)/(atanh(a)) == 0.5,a),4);

    median_S2 = floor(quantile(Data_2(o,:),0.5));
    a_M_S2(o) = vpa(vpasolve((a)/(atanh(a)) == 0.5,a),4);

end

a_MM_S1=transpose(a_MM_S1);
a_LQ_S1=transpose(a_LQ_S1);
a_M_S1=transpose(a_M_S1);
a_MM_S2=transpose(a_MM_S2);
a_LQ_S2=transpose(a_LQ_S2);
a_M_S2=transpose(a_M_S2);

figure(1)
histogram([double(a_MM_S1),double(a_MM_S2)],20),title('Method of Moments')
figure(2)
histogram([double(a_LQ_S1),double(a_LQ_S2)],20),title('Using Lower Quartile as Estimator')
figure(3)
histogram([double(a_M_S1),double(a_M_S2)],20),title('Using Median as Estimator')


text:
Q: mac & windows backup solutions - Offsite Backups Im looking for some advice on a system Im looking to impliment within our company, but so far I have not found an adequate solution too.
I need to provide my users with a way to backup there laptops whilst in the office and if possible offsite as well, we have a mixture of Windows & Mac laptops so software should ideally be multi platform. This is the first time i am attempting to-do something like this as we normally charge the users with responsibility for their backups.
I have ruled out most of the services like dropbox, sugarsync (unless one exists that does this) as whilst they does exactly what I want it does not give me any control over restoring / recovering data in the event of the user being unavailable, as it requires their account password to access data.

A: I you want a program that fits these discriptions, you might want to look at SparkeShare. Free, open source, and you can set everything to sync with your server.

A: Have a look at BackBlaze.com
Not sure if it has an option for a master password, but if you are dealing with business data the account passwords of all the employee's backup accounts should all be recorded and managed by the person handling your backup solution anyway.

A: OK to answer this question (thanks for all the replies btw) Our company decided upon a product from a company called BackupDirect. it allows centralised backups / restores of data from clients and servers and is very easy to get working and lightweight on our bandwidth.


text:
Q: Create Navigation Background CSS I came upon this website today:
http://leaverou.me/2010/12/checkered-stripes-other-background-patterns-with-css3-gradients/
and made me curious as to how you create the strip coming out from behind the white div without using images?  If anyone can tell me, I'd surely appreciate it.  Also, if someone doesn't understand what I mean, please let me know.

A: There are a lot of tutorials for making 3D Ribbons (as it's called). Example: http://www.pvmgarage.com/2010/01/how-to-create-depth-and-nice-3d-ribbons-only-using-css3/


text:
Q: sybase - showplan drops estimated I/O greatly by adding another table to query The application of the query has been changed, but the theory is the same.
4 tables:
states - list of states (index on state)
stores - stores, and the state they're in (separate indexes on state, store)
store_orders - ties an order to a store (separate indexes on store, order)
order_statuses - has order and status (separate indexes on order, status)
I want to count how many orders are in each status for a particular state.
One query:
select os.order_status, count(os.order_status)
from stores sto, store_order so, order_statuses os
where sto.state = 'PA'
and sto.store = so.store
and so.order = os.order
group by os.order_status
in the real application, a showplan here comes back with estimated I/O of around 500,000
But if I do:
select os.order_status, count(os.order_status)
from states sta, stores sto, store_order so, order_statuses os
where sta.state = 'PA'
where sto.state = sta.state
and sto.store = so.store
and so.order = os.order
group by os.order_status
The I/O is estimated at around 2,000, and all I did to change the query was join the states table to the stores table, and specify the exact value in states instead of stores.
Isn't the DBM still going to have to do the same searching of stores whether I specify an explicit value, or I join another table with that explicit value?
I'm trying to figure out why the estimated I/O is so much higher.
I'm no DBA, but trying to learn as much as I can, because I hit things like this all the time, and I'm never quite sure why.

A: Lazy Bob, Can you please also turn IO statistics on and then add the results to the question:

set statistics io on

showplan by itself will not give that info as you reported in the comments
also, please post exact working query - ideally, formatted correctly.
Your query says "where sta.state = 'PA' where sto.state = sta.state " and obviously not something you could have run


text:
Q: 2 things that I am confused about tail recursion I've several confusion about tail recursion as follows:

*

*some of the recursion functions are void functions for example,

// Prints the given number of stars on the console.
// Assumes n >= 1.
void printStars(int n) {
    if (n == 1) {
        // n == 1, base case
        cout << "*";
    } else {
        // n > 1, recursive case
        cout << "*";        // print one star myself
        printStars(n - 1);  // recursion to do the rest
    }
}

and another example:
// Prints the given integer's binary representation.
// Precondition: n >= 0
void printBinary(int n) {
    if (n < 2) {
        // base case; same as base 10
        cout << n;
    } else {
        // recursive case; break number apart
        printBinary(n / 2);
        printBinary(n % 2);
    }
}

As we know by definition tail recursion should return some value from tail call. But for void functions it does not return any value. By intinction I think they are tail recursion but I am not confident about it.
another question is that, if a recursion function has several logical end, should tail recursion come at all logical ends or just one of the logical ends? I saw someone argued that only one of the logical ends is OK, but I am not sure about that. Here's my example:
// Returns base ^ exp.
// Precondition: exp >= 0
int power(int base, int exp) {
    if (exp < 0) {
        throw "illegal negative exponent";
    } else if (exp == 0) {
        // base case; any number to 0th power is 1
        return 1;
    } else if (exp % 2 == 0) {
        // recursive case 1: x^y = (x^2)^(y/2)
        return power(base * base, exp / 2);
    } else {
        // recursive case 2: x^y = x * x^(y-1)
        return base * power(base, exp - 1);
    }
}

Here we have logical end as tail recursion and another one that is not tail recursion. Do you think this function is tail recursion or not? why?


text:
Q: Spring Boot will auto configure JPA transaction manager I am creating Spring Boot application which interact with single DB.I have used @EnableAutoconfiguration and @EnableTransactionManagement and provided spring-data-jpa.
I want to use Hibernate JPA vendor and its dialect. Does spring will auto configure this and JPA transactionmanager or Do I need to manually register these beans.

A: You need to provide this minimal jpa configuration in your application.yml so that spring could configure hibernate. Please change the property format accordingly if you are using application.properties file.
spring:
    datasource:
        url: jdbc:mysql://<mysql_db_url_here>
        username: <mysql_username>
        password: <mysql_pwd>
        driver-class-name: <db_driver_class> (e.g. com.mysql.jdbc.Driver)

    jpa:
        database-platform: <db_dilect_class> (e.g. org.hibernate.dialect.MySQL5Dialect)


text:
Q: Swift 4 Codable Realm Object Subclasses trying to switch some of my codebase over to Swift 4's new nifty Codable protocol. My setup looks something like this:
class Base: Object, Codable {

    dynamic var id: String = ""
    dynamic var timestamp: String = ""

    private enum CodingKeys: String, CodingKey {

        case id = "_id"
        case timestamp = "timestamp"

    }

}

class User: Base {

    dynamic var name: String = ""

    private enum CodingKeys: String, CodingKey {
        case name = "name"
    }

    required init(from decoder: Decoder) throws {

        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)
        try super.init(from: decoder)

    }

}

I have a base realm object class that conforms to Codable, and a subclass of Base that also has it's own coding keys. I override init(decoder:) on the User subclass to map my additional coding keys, then call super.init(decoder:) to map Base's coding keys. However, once I override init(decoder:) I get the following errors:

*

*required initializer 'init()' must be provided by subclass of 'Base'

*required initializer 'init(realm:schema:)' must be provided by subclass of 'Base'

*required initializer 'init(value:schema:)' must be provided by subclass of 'Base'
I'm not sure what the correct way is to go about fixing these issues.

A: You cannot override init() or other initializers of Realm Object. You can use convenience initializer instead. Then you cannot call super.init(from:), so define a method that decodes superclass' properties like Base.decode(from:).
See following code sample:
class Base: Object, Codable {
    dynamic var id: String = ""
    dynamic var timestamp: String = ""

    private enum CodingKeys: String, CodingKey {
        case id = "_id"
        case timestamp = "timestamp"
    }

    func decode(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try container.decode(String.self, forKey: .id)
        self.timestamp = try container.decode(String.self, forKey: .timestamp)
    }
}

class User: Base {
    dynamic var name: String = ""

    private enum CodingKeys: String, CodingKey {
        case id = "_id"
        case timestamp
        case name = "name"
    }

    required convenience init(from decoder: Decoder) throws {
        self.init()

        try decode(from: decoder)

        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)
    }
}

A: You cannot override just one initializer of a class. If you are going to override, do it for all of them. If you don't really use or care about the other initializers just at least call super.<respective init> in them.
For init(realm: RLMRealm, schema: RLMObjectSchema) and init(value: Any, schema: RLMSchema) compiler is going to complain that it doesn't know what RLMRealm, RLMObjectSchema and RLMSchema are. So import Realm besides RealmSwift.

A: As I just answered on another question, whilst you may be able to use your subclass as a Codable type with Katsumi's advice above, you may run into another gotcha.
You cannot have collections of Base as a reference type that contain subclass instances and have that collection survive Codable. It will only decode as Base instances.
Polymorphic persistence appears to be broken by design.
The bug report SR-5331 quotes the response they got on their Radar.
Unlike the existing NSCoding API (NSKeyedArchiver), the new Swift 4 Codable implementations do not write out type information about encoded types into generated archives, for both flexibility and security. As such, at decode time, the API can only use the concrete type your provide in order to decode the values (in your case, the superclass type).
This is by design — if you need the dynamism required to do this, we recommend that you adopt NSSecureCoding and use NSKeyedArchiver/NSKeyedUnarchiver
I am unimpressed, having thought from all the glowing articles that Codable was the answer to some of my prayers. A parallel set of Codable structs that act as object factories is one workaround I'm considering, to preserve type information.


text:
Q: Why the info panel of collider is grey in unity3d? I added a collider2D component to my Player to collide with the floor, but I noticed that the info panel which contains physic parameters like Friction, Bounciness is grey.I have to create a physics material by myself.So is that what it is(read only)?
image

A: Those values there are only readable and not able to be written on or to be changed.
Therefore if you would like to change them you need to make a PhysicsMaterial2D and apply it to the CircleCollider2D. You can also change the extents and centre of the CircleCollider2D by referencing the component in a script.
https://docs.unity3d.com/ScriptReference/CircleCollider2D.html


text:
Q: How to filter IDs based on dates? I have the following table:
ID | DATES
---+-----------
1   02-09-2010
2   03-08-2011
1   08-01-2011
3   04-03-2010

I am looking for IDs who had at least one date before 05-01-2010 AND at least one date after 05-02-2010
I tried the following:
WHERE tb1.DATES < '05-01-2010' AND tb1.DATES > '05-02-2010'

I don't think it's correct because I wasn't getting the right IDs when I did that and there's something wrong with that logic.
Can someone explain what I am doing wrong here?

A: The SQL command SELECT * FROM tb1 WHERE tb1.DATES < '05-01-2010' AND tb1.DATES > '05-02-2010' is asking "find all the rows where the 'dates' field is before 1 May and after 2 May" which - when put in English - is obviously none of them.
Instead, the command should be asking "find all the IDs which have a record that is before 1 May, and another record after 2 May" - creating the need to look at multiple records for each ID.
As @Martheen suggested, you could do this with two (sub)queries e.g.,
SELECT A.ID
FROM
    (SELECT DISTINCT tb1.ID
      FROM mytable tb1
      WHERE tb1.[dates] < '20100501'
    ) AS A
INNER JOIN
    (SELECT DISTINCT tb1.ID
      FROM mytable tb1
      WHERE tb1.[dates] > '20100502'
    ) AS B
    ON A.ID = B.ID;

or using INTERSECT
SELECT DISTINCT tb1.ID
    FROM mytable tb1
    WHERE tb1.[dates] < '20100501'
INTERSECT
    SELECT mt2.ID
    FROM mytable mt2
    WHERE mt2.[dates] > '20100502';

The use of DISTINCT in the above is so that you only get one row per ID, no matter how many rows they have before/after the relevant dates.
You could also do it via GROUP BY and HAVING - which in this particular case is easy as if any dates are before 1 May, then their earliest date must be before 1 May (and correspondingly for their max data and 2 May) e.g.,
SELECT mt1.ID
    FROM mytable mt1
    GROUP BY mt1.ID
    HAVING MIN(mt1.[dates]) < '20100501' AND MAX(mt1.[dates]) > '20100502';

Here is a db<>fiddle with all 3 of these; all provide the same answer (one row, with ID = 1).
Finally, you should use an unambiguous format for your dates. My preferred one of these is 'yyyyMMdd' with no dashes/slashes/etc (as these make them ambiguous).
Different countries/servers/etc will convert the dates you have there differently e.g., SQL Server UTC string comparison not working

A: This is one solution to use between to specify range.
SELECT * from Table_name where
From_date BETWEEN '2013-01-03'AND '2013-01-09'

Other solution is to what you mentioned but see that the logic is correct
SELECT * from Table_name where
From_date > '2010-01-05'AND From_date <'2010-02-05'


text:
Q: Updating a specific value in row with conditions nodejs google sheet I've been trying to update an existing row with the same name, email, etc.. my problem is that I can't figure out how to add a number in the second trial WPM for the same user.
to be more clear, the user submits a form and start the operation in the web app, when the first operation ends, the data is sent to google sheets and the user moves to the second operation. I want to send the data of the second operation to the user with the same name, email.
before
after
app.post("/competition" , async (req, res) => {
const {Name, Email, Number, Faculty, University, first_Trial_WPM , first_Trial_CPM} = req.body;
const auth = new google.auth.GoogleAuth({
    keyFile: "credentials.json",

    scopes: "https://www.googleapis.com/auth/spreadsheets",

    });

const client = await auth.getClient();

const googleSheets = google.sheets({version: "v4", auth: client});

const spreadsheetId = "###";

await googleSheets.spreadsheets.values.append({

    auth,
    spreadsheetId,
    range: "Sheet1!A:G",
    valueInputOption: "USER_ENTERED",

    resource : {
        values: [
            [Name, Email, Number, Faculty, University, first_Trial_WPM , first_Trial_CPM]
        ]
    }
})

res.render("competition2");
});

 app.post("/home" , async (req, res) => {

const {Name, Email, Number, Faculty, University, second_Trial_WPM , second_Trial_CPM} = req.body;

    const auth = new google.auth.GoogleAuth({
        keyFile: "credentials.json",

        scopes: "https://www.googleapis.com/auth/spreadsheets",

    });

    const client = await auth.getClient();

    const googleSheets = google.sheets({version: "v4", auth: client});

    const spreadsheetId = "###";

    await googleSheets.spreadsheets.values.update({

        auth,
        spreadsheetId,
        range: "Sheet1!A2:I1000",
        valueInputOption: "USER_ENTERED",

        resource : {
            values: [
                [Name, Email, Number, Faculty, University, second_Trial_WPM , second_Trial_CPM]
            ]
        }
    })

    res.render('home');
});

A: I believe your goal is as follows.

*

*You want to put the values to the columns "H" and "I" by searching the columns "A" and "B".

*You want to achieve this using googleapis for Node.js.

In this case, how about the following modification?
Modified script:
In this modification, please modify your 2nd script for putting the values of second_Trial_WPM and second_Trial_CPM as follows. This modified script uses the variables of Name and Email, second_Trial_WPM, and second_Trial_CPM.
  const spreadsheetId = "###";
  const range = "Sheet1";
  const values = (await googleSheets.spreadsheets.values.get({spreadsheetId, range})).data;
  const rows = values.values.map(([a, b], i) => (a == Name && b == Email ? i + 1 : "")).filter(String);
  const data = rows.map((e) => ({values: [[second_Trial_WPM, second_Trial_CPM]], range: `'${range}'!H${e}`}));
  const res = await googleSheets.spreadsheets.values.batchUpdate({spreadsheetId, resource: {valueInputOption: "USER_ENTERED", data}});

*

*In this modification, first, the values are retrieved from "Sheet1". And, retrieve the row numbers for putting values using the values of Name and Email. And then, second_Trial_WPM and second_Trial_CPM are put into the columns "H" and "I" of the searched row.

*If the same names are retrieved in columns "A" and "B" of "Sheet1", the values of second_Trial_WPM and second_Trial_CPM are put to those rows.
References:

*

*Method: spreadsheets.values.get

*Method: spreadsheets.values.batchUpdate


text:
Q: "Illegal parameter number in definition of \reserved@a" following \IfFileExists I tried to use a switch \IfFileExists to define a command differently, but I get the illegal parameter error. I am running LaTeX from TeX Live 2021.
A minimal example is:
\documentclass[12pt,fleqn]{article}
\usepackage[dvipsnames]{xcolor}
\IfFileExists{filename}
{\newcommand{\ABC}[1]{{\begin{color}{Red}{#1}\end{color}}}}
{\newcommand{\ABC}[1]{{\begin{color}{Blue}{#1}\end{color}}}}

\begin{document}
\ABC{Why?}
\end{document}

A: \IfFileExists doesn't work like "usual" conditionals: it stores the true and false branches in macros, and uses them later.  This requires you to double every # in there:
\documentclass[12pt,fleqn]{article}
\usepackage[dvipsnames]{xcolor}
\IfFileExists{filename} %                 VV
{\newcommand{\ABC}[1]{{\begin{color}{Red}{##1}\end{color}}}}
{\newcommand{\ABC}[1]{{\begin{color}{Blue}{##1}\end{color}}}}

\begin{document}
\ABC{Why?}
\end{document}

A: You're best served with a different approach.
\documentclass{article}
\usepackage[dvipsnames]{xcolor}

\newcommand{\ABCdo}[2]{\leavevmode{\color{#1}#2}}

\IfFileExists{filename}
  {\newcommand{\ABC}{\ABCdo{Red}}}
  {\newcommand{\ABC}{\ABCdo{Blue}}}

\begin{document}
\ABC{Why?}
\end{document}

Output with filename (which does not exist):

Output with latex.ltx (which exists):

There is no color environment and, anyway, the text should not be braced.


text:
Q: What is the difference between asset_pack_path and image_pack_tag in rails 6? According to my opinion image_pack_tag is the helper that we use in the views to place the images in our HTML form. But in the documentation of webpack I see asset_pack_path also. Now I am confused about this.Anyone here knows the exact difference?

A: asset_pack_path just returns the path. image_pack_tag returns a string containing a  html element.
module Webpacker::Helper
  ...

  # Computes the relative path for a given Webpacker asset.
  # Returns the relative path using manifest.json and passes it to path_to_asset helper.
  # This will use path_to_asset internally, so most of their behaviors will be the same.
  #
  # Example:
  #
  #   # When extract_css is false in webpacker.yml and the file is a css:
  #   <%= asset_pack_path 'calendar.css' %>  # => nil
  #
  #   # When extract_css is true in webpacker.yml or the file is not a css:
  #   <%= asset_pack_path 'calendar.css' %> # => "/packs/calendar-1016838bab065ae1e122.css"
  def asset_pack_path(name, **options)
    if current_webpacker_instance.config.extract_css? || !stylesheet?(name)
      path_to_asset(current_webpacker_instance.manifest.lookup!(name), options)
    end
  end

  # Computes the absolute path for a given Webpacker asset.
  # Returns the absolute path using manifest.json and passes it to url_to_asset helper.
  # This will use url_to_asset internally, so most of their behaviors will be the same.
  #
  # Example:
  #
  #   # When extract_css is false in webpacker.yml and the file is a css:
  #   <%= asset_pack_url 'calendar.css' %> # => nil
  #
  #   # When extract_css is true in webpacker.yml or the file is not a css:
  #   <%= asset_pack_url 'calendar.css' %> # => "http://example.com/packs/calendar-1016838bab065ae1e122.css"
  def asset_pack_url(name, **options)
    if current_webpacker_instance.config.extract_css? || !stylesheet?(name)
      url_to_asset(current_webpacker_instance.manifest.lookup!(name), options)
    end
  end

  # Creates an image tag that references the named pack file.
  #
  # Example:
  #
  #  <%= image_pack_tag 'application.png', size: '16x10', alt: 'Edit Entry' %>
  #
  #
  #  <%= image_pack_tag 'picture.png', srcset: { 'picture-2x.png' => '2x' } %>
  #
  def image_pack_tag(name, **options)
    if options[:srcset] && !options[:srcset].is_a?(String)
      options[:srcset] = options[:srcset].map do |src_name, size|
        "#{resolve_path_to_image(src_name)} #{size}"
      end.join(", ")
    end

    image_tag(resolve_path_to_image(name), options)
  end
end


text:
Q: WPF Docking library error? I use DockingLibrary :
 http://www.codeproject.com/KB/WPF/WPFdockinglib.aspx
but when I want to dock dockablecontent in the center(just in the center) of dockmanager an error raise:
object reference not set to an instance of an object
note: I use VS2010.
what can I do to solve this?

A: This doesn't answer your actual question, but have you thought about using AvalonDock? AvalonDock is a newer version of the WPF Docking Library that you linked to.
http://avalondock.codeplex.com/

A: and Sofa, its wrapper.


text:
Q: Error 500 upon adding shipping_save_after observer on Magento 2 upon adding my observer, I got error 500 when I'm trying to complete shipping process. What I want to achieve is, I want to send a review request after the shipment is done.I've started using Magento for about a month ago, that's why I don't know if I made an error on Observer, events.xml or it just doesn't work.  I've been doing this for about three days, please help.
Vendor name: Lns
Module Name: ReviewRequest
Review.php
<?php

namespace Lns\ReviewRequest\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class Review implements ObserverInterface
{
    protected $transportBuilder;
    protected $storeManager;
    protected $logger;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        TransportBuilder $transportBuilder,
        StoreManagerInterface $storeManager,
        LoggerInterface $logger

    ) {
        $this->transportBuilder = $transportBuilder;
        $this->storeManager = $storeManager;
        $this->logger = $logger;
    }

    /**
     * Below is the method that will fire whenever the event runs!
     *
     * @param Observer $observer
     */

    public function execute(Observer $observer)
    {

        $store = $this->storeManager->getStore();

        $templateParams = ['store' => $store, 'customer' => $customer, 'administrator_name' => $receiverInfo['name']];

        $transport = $this->transportBuilder
                        ->setTemplateIdentifier('Entrelabel Add Review')
                        ->setTemplateOptions(['area' => 'frontend', 'store' => $store->getId()])
                        ->addTo($receiverInfo['email'], $receiverInfo['name'])
                        ->setTemplateVars($templateParams)
                        ->setFrom('general')
                        ->getTransport();

        try {
            // Send an email
            $transport->sendMessage();
        } catch (\Exception $e) {
            // Write a log message whenever get errors
            $this->logger->critical($e->getMessage());
        }
        return var_dump($e);
    }
}

Events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_shipment_save_after">
        <observer name="reviewRequest" instance="Lns\ReviewRequest\Observer\Review" />
    </event>
</config>

A: add before class start
use Magento\Framework\Mail\Template\TransportBuilder
use Magento\Store\Model\StoreManagerInterface

and check log files in var folder


text:
Q: Were there ever two people jointly leading a noble house? Are/Were there any cases where there were two people at the head of a noble house? Perhaps as Brothers?
I'm planning to play in an ASOIAF rpg, and me and a friend of mine are going to be a noble house in service to the Tyrells in The Reach. We are twins of the house, and will one day succeed our father. I realize Head of the house goes to the eldest, even by a few seconds, but would it be unheard of if we choose to rule as joint lords? Would it be accepted?

A: I'm not aware of any examples in Westeros.
There is a precedent from British history: After the so-called Glorious Revolution in 1688, Parliament declared King William III and Queen Mary II to be joint monarchs. They shared the authority of the crown and if one of them died, the other was to continue ruling alone.
Westeros has no equivalent of the British Parliament, but it does have a legal system, as administered by the Master of Laws in the Small Council. There must be laws relating to the authority and responsibilities of Lords. If the King allowed it, then in principle those laws could be modified to allow joint headship of a House.

A: As Mooz already said in the comments, there are no mentions of houses with more than one ruler.
But often the Lord gives some of his responsibilities to other people.
The most common example found in the books would be the Castellan. His responsibility is the defense of a castle, fort or city.
Also there are examples where there is a Lord but he is not the actual ruler.
The most familiar example would be Robert Arryn who is the Lord of the Vale but, because he is under-aged, Littlefinger was granted the title Lord Protector and is currently the de facto ruler.
The Game of Thrones RPG from Telltale features House Forrester, a minor house from the north sworn to House Glover of Deepwood Motte.
The game introduced the title of Lord Sentinel which is granted by the Lord.
The Lord Sentinel has total power over the House and is only second the actual Lord. So the position of the Lord Sentinel is quite similar to the position of the Hand of the King.


text:
Q: Registro duplicado en consulta SQL Tengo esta consulta de SQL
SELECT DISTINCT COUNT(*) AS registros, DATE(fechaValidacion) AS fecha, nodo_id,motivorechazo_id
FROM registro AS r INNER JOIN prueba AS p
GROUP BY nodo_id,fecha,motivorechazo_id
ORDER BY fecha, nodo_id,motivorechazo_id;

El cual arroja un resultado duplicado por cada motivorechazo_id
#      fecha    nodo_id motivorechazo_id
1578 2019-07-24  403    1
789  2019-07-24  403    1
7    2019-07-24  403    4
14   2019-07-24  403    4
4    2019-07-24  403    5
2    2019-07-24  403    5
104  2019-07-24  403    8
208  2019-07-24  403    8
14   2019-07-24  403    9
28   2019-07-24  403    9
10   2019-07-24  403    10

Como se evidencia se duplica el id del motivo del rechazo y por ende la cantidad de registros que se presentaron por día. Ya en el query tengo la sentencia DISTINCT. Y con eso aún me trae registros duplicados y he de señalar que sin el DISTINCT la cantidad de registros duplicados seria aún mayor.
Lo ideal seria que aparezca así
    #      fecha    nodo_id motivorechazo_id
    789  2019-07-24  403    1
    14   2019-07-24  403    4
    2    2019-07-24  403    5
    208  2019-07-24  403    8
    28   2019-07-24  403    9
    10   2019-07-24  403    10

La estructura de las tablas son
---------------------            ----------------
|   Registro         |            |   Prueba     |
---------------------            ----------------
| id                 |            | id           |
---------------------            ----------------
| placa              |            | placa        |
---------------------            ----------------
| fecha              |            | estado_id    |
---------------------            ----------------
| nodo_id            |            | usuario_id   |
--------------------            ----------------
| tipoinfraccion_id  |            | velocidad    |
---------------------            ----------------
| velocidad          |            | registro_id  |
---------------------           ------------------
| video_id           |           | imagenprincipal |
---------------------          ---------------------
                                 | fechaValidacion |
                                --------------------

Y con datos sería.

A: Como ha comentado @juandej18, es probable que el omitir como se unen las tablas registro y prueba este provocando que se dupliquen los registros.
Modifica tu consulta y agrega como se unen ambas tablas:
SELECT
  COUNT(*) AS registros,
  DATE(fechaValidacion) AS fecha,
  nodo_id,
  motivorechazo_id
FROM registro AS r
  INNER JOIN prueba AS p
    ON p.registro_id = r.id -- AQUI indicamos como se unen
GROUP BY
  nodo_id,
  fecha,
  motivorechazo_id
ORDER BY
  fecha,
  nodo_id,
  motivorechazo_id;

A: Ya logre solucionar el problema
SELECT COUNT(*) AS registros, r.id,nodo_id, DATE(fechaValidacion) AS fecha_registros,motivorechazo_id
FROM prueba AS p
INNER JOIN registro AS r ON r.id = p.registro_id
GROUP BY fecha_registros,nodo_id
ORDER BY fecha,nodo_id

Es muy simple, el alias de FechaValidacion que le puse fue fecha y en un campo de la tabla registro ya habia un campo de nombre fecha por lo tanto esta generaba conflicto. Simplemente coloque un alies diferente


text:
Q: Can i use Google Maps on my Windows 10 (UWP) Apps So, I was looking to create Universal Windows Platform app (targeting both mobile and desktop) that actually showing a maps with a marker that came from lat & long saved in a database. But I want to using Google Maps to show it.
How can I do this? I mean, is it possible?
Which GMaps API should I use? JavaScript API, or the Web Srvice API?
I've been thinking that maybe I could use the web view to achieve this, to show the maps. But is this the right way or any other way?
Glad if someone can help and give an opinion.
(and sorry for my bad grammar, if any)

A: Google does not provide any SDKs for working with Google Maps.
Basically, proposed to use native MapControl. You can look Source Code Sample.
But you can add WebView to display Google Maps. You can create your own html page with JavaScript functions. For invoke your JavaScript functions use InvokeScriptAsync. You can look the simple sample: HOW TO COMMUNICATE WITH WEBVIEW JAVASCRIPT FROM C#

A: You can create a MapControl just as you would on a website.
Include their script at the top of your page:

Then include a div to contain the map:

You can manipulate the map and add new items to it (markers, long / lat, etc) but referencing that id "map-canvas" from any additional JS file you create.


text:
Q: XBOX One - Microsoft Family Accounts I might need a little hand-holding here. I have two boys who bought an Xbox One on which they both use my Xbox/Microsoft account (I don't actually play, just used to set the console up for them) to play games (i.e. Fortnite).
I just created a Microsoft "Family" account, and created "Child" accounts for my sons, and would now like to get them set up so they can each log in to their own profile on Xbox, and play their respective games through their profile, and not the master "Family" profile.
How do I get this all set up so that they have their own profile (not sure about the Xbox gamertag versus the Fortnite name), and can play under the Family account and both have access to the Xbox Live subscription?

*

*Can they both play under the master account and both have access to Xbox Live?

*Can I transfer the "history" of their previous Fortnite gameplay to the oldest sons' new profile?

*Is the Xbox gamertag the same as the Fortnite player name?

Goal:

*

*Master Account (dad@example.com) - Holds Xbox Live Subscription, Gamertag "Dad1" (which is the original gamertag)

*

*Son 1 (son1@example.com), Gamertag "Son1", Fortnite name "Son1"

*Son 2 (son2@example.com), Gamertag "Son2", Fortnite name "Son2"

A: First things first, there are, yes you correctly summarized, three things that matter and that are separate.

*

*Your Microsoft account which you used with your mail (dad@example.com) and which bought the Live subscription. This account can administer the family and be used to access all the neat features of a Microsoft account. These features include OneDrive, Office 365 (if bought), Outlook Calendars, and many more. One of the benefits is also...

*Your Gamertag. This is an alias you use across all Microsoft platforms, in the Xbox Live "universe" to track your game progress (saves are stored in the cloud on the Xbox One), your gamerscore, friends, purchase history, etc.

*Your Fortnite name which is tied to Fortnite and has nothing to do with your Xbox.

What you want to do is, on your Xbox One, log in your son's profiles. Here is how. this will enable your sons to go online and, since they are part of your family, have access to your Live subscription.
As for the Fortnite account, have you linked your Fortnite account to your gamertag? If so, you can unlock them and link your Fortnite account to a new gamertag. Progress on Fortnite (in game) is tied to your Fortnite account, not your gamertag. You gamertag only holds the related achievements.


text:
Q: How to display the unique elements between two object lists? I have two lists filled with object elements. Using these two lists, I want to create another list which contains only the uncommon elements between them.
I tried using an iterator:
for(Row currentRowObject: currentRow) {
    for (Iterator<Row> newError = newErrorRow.iterator(); newError.hasNext(); ) {
        Row rowObject = newError.next();
        if (rowObject.getAll().equals(currentRowObject.getAll())) {
            newError.remove();
        }
    }
}

After I run this, the newError list is completely removed. I checked that the two lists are different, they differ in size and there are objects that differ between these two lists.
How can I solve this problem?

A: You can use Sets retainAll property & the use removeAll !
Set < Row > rows1 = new HashSet(currentRow);
Set < Row > rows2 = new HashSet(newErrorRow);
rows1.retainAll(rows2); // rows1 now contains only elements in both set !
rows2.removeAll(rows1); // rows2 now contains only the unique elements !

A: to explain this in logic format(not Java):
UncommonRows = (currentRow union newErrorRow ) - (currentRow intersection newErrorRow)

here is a quick and dirty way of doing it in Java. hope the comments explains what I've done.
Set<Row> uncommonRows=new HashSet<Row>(currentRow);
uncommonRows.addAll(newErrorRow); //at this point uncommonRows contains all the Rows
Set<Row> retained=new HashSet<Row>(currentRow);
retained.retainAll(newErrorRow); //retained contains all rows that are in both sets.
uncommonRows.removeAll(retained) ; // at this point uncommonRows contains the uncommon Rows

A: Using java8 you can do something like:
    final List<Row> allErrors = new ArrayList<>();
    allErrors.addAll(currentRow);
    allErrors.addAll(newErrorRow);

and then:
final List<Row> result = allErrors.stream().filter(p -> Collections.frequency(allErrors, p) == 1)
            .collect(Collectors.toList());


text:
Q: How to use HList to validate input? I'm using Shapeless 2.0 and I'm trying to use HList to validate input — with as much of the checking as possible performed at compile time.
I have an HList spec that specifies what type of input I'm expecting (the types should be checked at compile time) and may also include a runtime check to be performed (e.g., to test if a number is even or odd).
Consider the following specification:
trait Pred[T] { def apply(t: T): Boolean }
val IsString = new Pred[String] { def apply(s: String) = true }
val IsOddNumber = new Pred[Int] { def apply(n: Int) = n % 2 != 0 }
val IsEvenNumber = new Pred[Int] { def apply(n: Int) = n % 2 == 0 }
val spec = IsEvenNumber :: IsString :: IsString :: IsOddNumber :: HNil

And various sample inputs:
val goodInput = 4 :: "foo" :: "" :: 5 :: HNil
val badInput = 4 :: "foo" :: "" :: 4 :: HNil
val malformedInput = 4 :: 5 :: "" :: 6 :: HNil

How would I make a function where I can effectively do:
input.zip(spec).forall{case (input, test) => test(input)}

So the following would happen:
f(spec, goodInput) // true
f(spec, badInput) // false
f(spec, malformedInput) // Does not compile

A: These answers by Travis Brown include most of what's needed:

*

*https://stackoverflow.com/a/20452151/86485

*https://stackoverflow.com/a/21005225/86485
but it took me a long time to find those answers, figure out that they were applicable to your problem, and work out the details of combining and applying them.
And I think your question adds value because it demonstrates how this can come up when solving a practical problem, namely validating input. I'll also try to add value below by showing a complete solution including demo code and tests.
Here's generic code for doing the checking:
object Checker {
  import shapeless._, poly._, ops.hlist._
  object check extends Poly1 {
    implicit def apply[T] = at[(T, Pred[T])]{
      case (t, pred) => pred(t)
    }
  }
  def apply[L1 <: HList, L2 <: HList, N <: Nat, Z <: HList, M <: HList](input: L1, spec: L2)(
    implicit zipper: Zip.Aux[L1 :: L2 :: HNil, Z],
             mapper: Mapper.Aux[check.type, Z, M],
             length1: Length.Aux[L1, N],
             length2: Length.Aux[L2, N],
             toList: ToList[M, Boolean]) =
    input.zip(spec)
      .map(check)
      .toList
      .forall(Predef.identity)
}

And here's the demo usage code:
object Frank {
  import shapeless._, nat._
  def main(args: Array[String]) {
    val IsString     = new Pred[String] { def apply(s: String) = true       }
    val IsOddNumber  = new Pred[Int]    { def apply(n: Int)    = n % 2 != 0 }
    val IsEvenNumber = new Pred[Int]    { def apply(n: Int)    = n % 2 == 0 }
    val spec = IsEvenNumber :: IsString :: IsString :: IsOddNumber :: HNil
    val goodInput       = 4 :: "foo" :: "" :: 5 :: HNil
    val badInput        = 4 :: "foo" :: "" :: 4 :: HNil
    val malformedInput1 = 4 :: 5     :: "" :: 6 :: HNil
    val malformedInput2 = 4 :: "foo" :: "" :: HNil
    val malformedInput3 = 4 :: "foo" :: "" :: 5 :: 6 :: HNil
    println(Checker(goodInput, spec))
    println(Checker(badInput, spec))
    import shapeless.test.illTyped
    illTyped("Checker(malformedInput1, spec)")
    illTyped("Checker(malformedInput2, spec)")
    illTyped("Checker(malformedInput3, spec)")
  }
}

/*
results when run:
[info] Running Frank
true
false
*/

Note the use of illTyped to verify that code that should not compile, does not.
Some side notes:

*

*I initially went down a long garden path with this, where I thought it would be important for the polymorphic function check to have a more specific type than Poly1, to represent that the return type in all cases is Boolean. So I kept trying to make it work with extends (Id ~>> Boolean). But it turns out not to matter whether the type system knows that the result type is the Boolean in every case. It's enough that the only case that we actually have has the right type. extends Poly1 is a marvelous thing.

*Value-level zip traditionally allows unequal lengths and discards the extras. Miles followed suit in Shapeless's type-level zip, so we need a separate check for equal lengths.

*It's a bit sad that the call site has to import nat._, otherwise the implicit instances for Length aren't found. One would prefer these details to be handled at the definition site. (A fix is pending.)

*If I understand correctly, I can't use Mapped (a la https://stackoverflow.com/a/21005225/86485) to avoid the length check, because some of my checkers (e.g. IsString) have singleton types that are more specific than just e.g. Pred[String].

*Travis points out that Pred could extend T => Boolean, making it possible to use ZipApply. I leave following this suggestion as an exercise for the reader :-)


text:
Q: How to create an HTML Table out of HTML Form submissions without server side programming? I would like to know if this is possible in Javascript? I need to create an HTML Table that will be updated everytime a user submits a form. I do not have php or sql access because I was only provided with Sharepoint access. It 's actually a sub site of the enterprise sharepoint page but I have admin rights to this sub site so I was able to create a home for our region.
What I need to create is an employee evaluation/coaching form but I do not want to use sharepoint forms/surveys because the design is limited. I need to be able to track every form submission that can be pasted to an excel file. I hope this is something that can be done. Thanks!!!!


text:
Q: Responsive image inside a div with padding We have an #inner with padding-top and padding-bottom. The content inside the div is centered. We have an image to with max-width:100% and max-height:100%.
The image is responsive but it gets the height of the #inner with padding, and it's not centered.
CSS
*, *:before, *:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

#inner {
    height:100px;
    padding:15px 0;
    background:yellow;
}

#container {
    height: inherit;
}

a {
    float: left;
    height: inherit;
    width: auto;
}

img {
    max-height:100%;
    max-width:100%;
}

The HTML:

I tried to add padding to the  tag, add an other container around the  but the image became smaller. The image should be the height of the #inner - 30px (padding).
I understand the problem is with the inherit property, but I don't know the solution.
Here is the jsfiddle link: http://jsfiddle.net/b8o2t31e/

A: Try like this: Demo
CSS:
#container {
    height: 100%;
}
a {
    float:left;
    height: inherit;
    width: auto;
    background:red;
}
img {
    max-height:100%;
    max-width:100%;
    display:block;
    margin:0 auto;
}

Edit : or if you want to place image in center of div you can use like this Demo
CSS:
#container {
    height: 100%;
    background:red;
    display:block;
    margin:0 auto;
    text-align:center;
}
a {
    max-height:100%;
    width: auto;
}
img {
    max-height:100%;
    max-width:100%;
}

Edit : To remove Extra space use width and height as 100% for  like this: Demo
CSS:
#container {
    height: 100%;  }
a {
    height: inherit;
    background:red;
    margin:0;
    padding:0;
    display:inline-block;
}
img {
    height:100%;
    width:100%;
}

A: Try changing height of the #container from inherit to 100%.

*, *:before, *:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

#inner {
    height:100px;
    padding:15px 0;
    background:yellow;
}

#container {
    height: 100%;
}

a {
    float: left;
    height: inherit;
    width: auto;
}

img {
    max-height:100%;
    max-width:100%;
}


text:
Q: Scraping bylines from web page using ImportXML in Google Sheets Looking to extract the author name from articles. Currrently using =IMPORTXML(G2,"//*[@class='author-details']")
When I do this, it creates 4 cells underneath which contain the word 'By', which I can't get rid of.
Very new to code - what am I doing wrong?
Attached example: https://docs.google.com/spreadsheets/d/1Mi1D5G1-_gNsQwVQ6I_ealDqcWixKA2p-hFqJpjlGt4/edit?usp=sharing

A: You can use:
=index(IMPORTXML(G2,"//*[@class='author-details']"),1,2)

This displays only the first row of the second column of what is returned. The information You are after.
Edit:
Additionally, since you highlighted that you want author name. If all the names are in that format "By FIRST LAST @TwitterHandle Affiliation" then you can use this to get just the author's name:
=trim(split(right(index(IMPORTXML(G2,"//*[@class='author-details']"),1,2),len(index(IMPORTXML(G2,"//*[@class='author-details']"),1,2))-3),"@",true,true))

Will likely look like voodoo but paste it in, it works. It removes the first 3 characters ("By "), splits the text at the "@" symbol, and then keeps only the text on the left side of it, the name.


text:
Q: how to build game puzzle 3 * 3? Currently i am building game puzzle sliding using java. First My algorithm is create button array 2d with set image on those button and add them to panel(with grid layout 3*3). my problem is how can I compare each piece of image on those button  with original image?
       Code below where i add button to Jpanel.
private void set() throws Exception {
    position = new int[row][col];
    lstBtn = new JButton[row][col];
    count = new int[row * col];
    arr=new ArrayList<>(9);

    panelContainer.setLayout(null);
    panelContainer.setLayout(new GridLayout(row, col));
    BufferedImage img;
    int numCount = 0;
    int posNum=0;

    orgImg=new BufferedImage[row][col];
    for (int i = 0; i < row; i++) {
         for (int j = 0; j < col; j++) {

           position[i][j] = posNum++;

            if (i ==0 & j == 0) {
           // For blank Button
                lstBtn[i][j] = new JButton();
                lstBtn[i][j].setBackground(Color.WHITE);
               // panelContainer.add(lstBtn[i][j]);
                lstBtn[i][j].setVisible(true);
                arr.add(lstBtn[i][j]);
                count[0] = numCount;
            }
            else {
                   numCount++;
                lstBtn[i][j] = new JButton();
                lstBtn[i][j].addActionListener(this);
             img = image_cutting.getSubImage(j,i);//160, 116 //120, 87,
             orgImg[j][i]=img;
              lstBtn[i][j].setIcon(new ImageIcon(orgImg[j][i].getScaledInstance(160, 116, BufferedImage.SCALE_SMOOTH)));
                lstBtn[i][j].setHorizontalTextPosition(JButton.CENTER);
                lstBtn[i][j].setVerticalTextPosition(JButton.CENTER);
                lstBtn[i][j].setFont(new Font("Dialog",2,20));
                lstBtn[i][j].setForeground(Color.BLUE);
                 lstBtn[i][j].setText("" + numCount);
                arr.add(lstBtn[i][j]);
             //  panelContainer.add(lstBtn[i][j]);
               lstBtn[i][j].setVisible(true);
            }
            if (numCount == 0) {
                continue;
            }
            count[numCount] = numCount;
        }

This image bellow is sample of puzzle sliding with match image

A: This is a conceptual idea, which will need some fleshing out, but.  Start with an idea of a single piece, which holds it's "order" or "index" within the puzzle and it's image
public class PuzzelPiece {
    private int index;
    private Image img;

    public PuzzelPiece(int index, Image img) {
        this.index = index;
        this.img = img;
    }

    public Image getImage() {
        return img;
    }

    public int getIndex() {
        return index;
    }

}

Next, wrap this in some kind of model.  It should manage the pieces, provide access to them and possibly provide a "is ordered" check to determine if the pieces are in order.
This example takes a source image, the number of cols/rows you want and slice and dices the image into pieces.  It then shuffles the pieces and adds a blank piece in place of the first piece (the piece with the index of 0)
public class Puzzle {

    private List<PuzzelPiece> pieces;

    public Puzzle(BufferedImage source, int cols, int rows) {

        int rowHeight = source.getHeight() / rows;
        int colWidth = source.getWidth() / cols;

        pieces = new ArrayList<>(25);
        int index = 0;
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                Image img = source.getSubimage(col * colWidth, row * rowHeight, colWidth, rowHeight);
                pieces.add(new PuzzelPiece(index++, img));
            }
        }
        pieces.remove(0);
        Collections.shuffle(pieces);
        pieces.add(new PuzzelPiece(0, null)); // Blank
    }

    public boolean isOrdered() {
        // Instead of sorting the list like this each time
        // you could just maintain two lists to start with
        // one ordered and one shuffled
        List<PuzzelPiece> ordered = new ArrayList<>(pieces);
        Collections.sort(ordered, new Comparator<PuzzelPiece>() {
            @Override
            public int compare(PuzzelPiece o1, PuzzelPiece o2) {
                return o1.getIndex() - o2.getIndex();
            }
        });
        boolean isOrdered = true;
        for (int index = 0; index < ordered.size(); index++) {
            if (ordered.get(index) != pieces.get(index)) {
                isOrdered = false;
                break;
            }
        }
        return isOrdered;
    }

    public int size() {
        return pieces.size();
    }

    public PuzzelPiece getPieceAt(int index) {
        return pieces.get(index);
    }

    public void swap(PuzzelPiece piece, PuzzelPiece with) {
        int pieceIndex = pieces.indexOf(piece);
        int withIndex = pieces.indexOf(with);

        pieces.set(pieceIndex, with);
        pieces.set(withIndex, piece);
    }
}

It provides a simple swap method to swap pieces and simple isOrdered method to check to see if the list is ordered
This is untested and comes "as is" and is meant to drive the idea, to provide an implementation


text:
Q: No Facebook notifications in Notification Center – How can I fix it? When I upgraded to Yosemite, I happily used Notification Center to receive alerts upon getting a message or so. I then turned them off at some point and recently changed my password (not sure if that matters). Since then, despite the notification type being set to "Alerts" and having updated the password in Internet Accounts, I do not receive Notifications. I can use the notification center to post to Facebook, which makes it weirder.
The problem does not appear to be exclusive to me (see these discussions). I tried removing and readding the account, turning off Little Snitch, resetting SMC (can't imagine why that would help, but it fixed it for some people), but no. Does anyone have any suggestions what to do?

A: Go to Notifications pane in the System Preferences. Check if Facebook is allowed or not.


text:
Q: Lambda Calculus: Is a given variable free in a constant term? In a term with no occurrences of the variable? Consider a pure lambda calculus, $L$. Denote by $V$ $L$'s set of variables, and by $C$ $L$'s (possibly empty) set of constants. Let $P$ be a term in $L$ (a.k.a. a $\lambda$-term). Denote by $\text{FV}(P)$ the set consisting of all variables $x\in V$ that are free in $P$.

*

*Suppose $P=a$ for some constant $a\in C$. What is $\text{FV}(P)$? Is it $\emptyset$, or is it $V$?

*Denote by $R(P)$ the set consisting of all variables $x\in V$ that occur in $P$. Suppose $x\in V$ is such that $x\notin R(P)$. Is $x\in\text{FV}(P)$?


text:
Q: Python : Regex, Finding Repetitions on a string I need to find repetitions in a text string.
I already found a very nice elegant solution here from @Tim Pietzcker
I am happy with the solution as is but would like to know whether it's possible to extend it little further such that it would accept a string with whitespaces.
For example "a bcab c" would return [(abc,2)]
I tried using the regex pattern "([^\s]+?)\1+") with no luck.
Any help is much appreciated.

A: You should think about removing " " from the text first. You can do it by regex itself.
>>> def repetitions(s):
...    r = re.compile(r"(.+?)\1+")
...    for match in r.finditer(re.sub(r'\s+',"",s)):
...        yield (match.group(1), len(match.group(0))/len(match.group(1)))
...

Output.
>>> list(repetitions("a bcab c"))
[('abc', 2)]

If you still want to retain the space in the original text, Try this regex: r"(\s*\S+\s*?\S*?)\1+" . But this has limitations.
>>> def repetitions(s):
...    r = re.compile(r"(\s*\S+\s*?\S*?)\1+")
...    for match in r.finditer(s):
...        yield (match.group(1), len(match.group(0))/len(match.group(1)))
...

Results:
>>> list(repetitions(" abc abc "))
[(' abc', 2)]
>>> list(repetitions("abc abc "))
[('abc ', 2)]
>>> list(repetitions(" ab c ab c "))
[(' ab c', 2)]
>>> list(repetitions("ab cab c "))
[('ab c', 2)]
>>> list(repetitions("blablabla"))
[('bla', 3)]

A: Using (\S+ ?\S?)\1, you can make it tolerable to spaces for strings as below where the positions of the spaces are in the same location in the repetetive words ab c.
ab cab c

However, if the space locations in the repetitive words are not the same. Then it means, you have to replace the meaningless spaces with an empty string "" to find the repetitive words with your approach.


text:
Q: Why are network packets getting sent to incorrect switch port All,
I have multiple security monitoring devices that lose communication/connectivity on a regular basis throughout the week.
I have set up WireShark to monitor the network traffic going to/from one of the switch ports.  I see that when communication with the security device fails, a large, abnormal amount of traffic is directed through the switchport(it typically takes 2-8 hours to generate a 200M pcap file, when the communication fails, I see that a 200M file has been generated in just a few seconds).  This traffic is typically between our network video servers(2), the video wall(2 workstation servers), and the network cameras(approx 50). The IP and mac addresses fields in the packets sent to the security device do not match the security device.
The security devices(7-8), network video servers, the video wall servers, and cameras are all on the same switch(3 stacked 48-port HPE switches), and on the same VLAN.  We have other VLANs and devices that are not affected by this issue.
The security devices, NVR's, cameras, video wall workstations are all static configurations with reservations set up in Active Directory(Windows Server 2016)
The arp table and the mac address table on the switch are both set up with static addresses for the security devices.
What are the troubleshooting steps to determine why this network traffic is getting sent to the switchport--I've ran Wireshark, and I see the traffic going to the switchport, I have looked at the arp and mac-address tables, I've set up the addresses statically in the mac/arp tables.
Thanks for your assistance--
Clyde Reed


text:
Q: Fit the process in the container Form I want to start a process in my C# application and I am able to do so by using this code:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "chrome.exe";
startInfo.WorkingDirectory = @"C:\Program Files\Google\Chrome\Application";
Process process = Process.Start(startInfo);

But when I open this it opens on whole screen, means it covers the whole screen. I need that to be contained within the boundary of my form. Lets say size of form is 906, 495 then this application should open within this area.
I am unable to find that that how can I do this. Secondly I need to set the size of any application. Like I have used Chrome but it may be any other process. Is it possible?

A: You can do it like this:
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "chrome.exe";
startInfo.WorkingDirectory = @"C:\Program Files\Google\Chrome\Application";

//Force chrome to run in a new process
startInfo.Arguments = @"--user-data-dir=C:\sometempdir";

Process process = Process.Start(startInfo);

process.WaitForInputIdle();

//Need to do a little more work make sure we get the Window handle properly
do
{
    System.Threading.Thread.Sleep(100);
    process.Refresh();
}
while (process.MainWindowHandle == IntPtr.Zero && !process.HasExited);

//Set these appropriately
int xPos = 0;
int yPos = 0;

MoveWindow(process.MainWindowHandle, xPos, yPos, 906, 495, true);

A: Just as mclaassen suggested, you should use the MoveWindow API, however you might want to wait until the window shows up:
        [DllImport("user32.dll", SetLastError = true)]
        internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = "notepad.exe";
        Process process = Process.Start(startInfo);
        process.WaitForInputIdle(); // Wait for interface to load

        MoveWindow(process.MainWindowHandle, 0, 0, 100, 100, true);


text:
Q: Is there a way to quickly make all photos in a onenote notebook searchable? For instance I have a notebook filled with scans of documents that i need to be searchable, but I don't have the time to right click them all and manually make them searchable.

A: Images are recognised and indexed automatically. You don't need to do each individually. It is very effective, even recognising sideways text and text in poor quality images. But it isn't perfect, especially on longer texts.
Only video and audio file indexing needs turning on separately and you can only do that in the full version of OneNote not that universal app designed for tablet mode and phones.
The only other control is in Indexing Options (part of Control Panel). There you can turn off OneNote indexing totally which should stop Windows recognising
text in OneNote images.


text:
Q: How to reset default app in Android Things OS? Yesterday I started an Android Things project and I was testing the app using Android Studio. In order to connect to the device using adb.exe, I used the IP of the android device that I saw on the default OS's app (the starting screen). So, after the yesterday's testing it seems that my app is now the default app even if I don't have it connected to the PC.
The problem is that now I cannot see the device's IP address so I can connect to it using adb.exe.
Is there a way of going back to the default OS's app?
PS. The only solution I found is re-installing the Android Things OS.

A: To go back to default android thing logo screen.Uninstall the  app using
adb uninstall <pkg name>

If you want to connect to AT without knowing ip use following command
adb connect Android.local

Also you can use serial cable to find ip of AT.
If you install multiple apps.AT will ask for your choice as below

A: uninstall the app using adb
adb uninstall <package-name>

if you have connected a keyboard to the raspberry pi board, you can go to the home screen by pressing escape button

A: (I don't have enough reputation to comment so I make an answer, sorry)
If you want to know the IP of your Raspeberry from your computer, you can use the ARP table.
From Ubuntu/Linux or Windows, just type arp -a
Your Android Things device will appear in this list with its IP !

A: If you don't need to uninstall your app, you can just close it:
adb shell am force-stop <package-name>

and of course you can close it from your app:
this.finish();

Also you can show your ip address in your app if you have screen. For me adb connect Android.local doesn't work.

A: An easy way is to log into your router and see all of the connected devices and pull the ip address from there. Really easy with Google Wifi


text:
Q: Passing the values of variable values in C I have a function say formula(f), where f is a TERM and TERM is a structure pointer. This function prints a formula like forall([U,V],implies(U,V)].These U and V are variable. I need to pass the values in these variable and have to generate the forumula according the combination of the values of the variable.Suppose the values of the U and V are 2 and 2 then it has to generate the 4 formulas like forall([a_1,b_1]implies(a_1,b_1),forall([a_1,b_2]implies(a_1,b_2)) and so on... Can anybody please help me how to generate it?

A: Presuming that your TERM structure has U and V as integer members:
void formula(TERM* term) {
  int x = 0;
  int y = 0;
  for (x; x < (*term).U; ++x)
    for (y; y < (*term).J; ++y)
      printf("forall([a_%d,b_%d] implies(a_%d, b_%d))\n", x, y, x, y);
}

Is this what you're looking for?


text:
Q: Angular exception : attempt to use a dehydrated detector After looking at several topics discussing this error, I can't find any reason for my code to produce EXCEPTION: Attempt to use a dehydrated detector: PortsInputComponent_1 -> valueChange. I don't think the stacktrace is usefull, since it is only angular code, and not mine.
I've looked at those posts : Angular2 EXCEPTION: Attempt to detect changes on a dehydrated detector, EXCEPTION: Attempt to detect changes on a dehydrated detector, What is a dehydrated detector and how am I using one here?, and at this github issue https://github.com/angular/angular/issues/6786.
They all seem to be using some asynchronous operations, which I'm not, and none of those solutions fit my project. Please don't close it as duplicate.
Basically what I'm trying to do is a special input for multiple ports. I want to always have a blank input, so the user don't have to press a button in order to add a new one. I don't want to have more than one blank input though, so I need to remove them when the user deletes the last character. The demo below does this perfectly.
Here is the code inside the plunker :
import { Component, Input }             from 'angular2/core';

@Component({
  selector: 'my-ports-input',
  template:`

  <md-input-container class="md-block" flex-gt-sm
      *ngFor="#port of values() ; #i = index ;">
    Port
    <input md-input class="ports-input" type="text" size="6"
        [value]="port.title" (input)="changeValueAtIndex(i, $event)" />
  </md-input-container>

`
})

export class PortsInputComponent {
  // More complex model that contains an array of string values
  @Input() attribute: {value : string[]}
  strings = []

  changeValueAtIndex(index, event) {
    // Case where we changed the value of the latest port : we add a new input
    if (!this.attribute.value[index]) {
      this.strings.push({ title: '' })
    }

    this.attribute.value[index] = event.target.value

    if (event.target.value.length === 0) {
      this.attribute.value.splice(index, 1)
      this.strings = [] // Should reload the array, but also causes the issue below
    }
  }

  // Use this function that returns an array of objects instead of an array of string.
  // Using directly attribute.value (array of string) cause this error:
  // https://github.com/angular/angular/issues/6786
  //
  // Returning directly this.attribute.value.map((value) => { return {title: value} })
  // causes an infinite loop of error... for some reason
  // So use an intermediate variable instead
  values() {
    if (!this.strings.length) {
      let values: string[] = this.attribute.value
      this.strings = values.map((value) => { return {title: value} })
      this.strings.push({ title: '' })
    }
    return this.strings
    // return this.attribute.value.map((value) => { return {title: value} })
  }
}

Does anyone understands why this error is thrown in my case ?
I wanted to reproduce this error in a plunker, but unfortunately it doesn't cause any exception, the only difference I see between my app and the plunker is the attribute variable. In my app it is a model and not a JSON object, could it change something ?

A: Delaying this code a bit might be able to work around (not tested because I can't reproduce)
  changeValueAtIndex(index, event) {
    setTimeout(() => {
      // Case where we changed the value of the latest port : we add a new input
      if (!this.attribute.value[index]) {
        this.strings.push({ title: '' })
      }

      this.attribute.value[index] = event.target.value

      if (event.target.value.length === 0) {
        this.attribute.value.splice(index, 1)
        this.strings = [] // Should reload the array, but also causes the issue below
      }
    },0});
  }


text:
Q: puppet define array loop I am playing with define array but not understand why its not working in following example. I am trying to create following directions
/tmp/foo.0
/tmp/foo.1
/tmp/foo.2

My init.pp
class loop {

define loop ( $x ) {

exec {"$name":
        command => "/bin/mkdir /tmp/$name.$x",
        creates => "/tmp/$name.$x",
        }
}
loop{ "foo": x => ["0", "1", "2"] }

}

Its creating directory like /tmp/tomcat7.012

A: Not sure this is a good idea to name the define with same name than class.
It would work if you invert the $name and $x
class loop {

  define loop::loop ( $x ) {

    exec {"$x":
      command => "/bin/mkdir /tmp/$x.$name",
      creates => "/tmp/$x.$name",
    }
  }
  loop::loop{ ["0", "1", "2"]: x => "foo" }
}

Hope this helps


text:
Q: issues with gridLayout in swift So I have these delegate methods that help me layout my collectionView. I am trying to create somewhat of a grid layout where there are X numberOfSections and X numberOfItemsInSection. Based off of what I have now it lays out all of the rights next to each other and spaces them out a little too far as to where cells go to the next line. How do I go about fitting all the cells for a section on one line.
 //Asks the delegate for the size of the header view in the specified section.
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return .zero
    }
    //Asks the delegate for the size of the footer view in the specified section.
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return .zero
    }
    //Asks the delegate for the size of the specified item's cell.
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (collectionView.bounds.size.width - CGFloat(numberOfItemsInSection))/2.2, height: collectionView.bounds.size.height - 50)

    }
    //Asks the delegate for the margins to apply to content in the specified section.
    //in short in controls the amount of space between the items above,left,right, and below
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
    }
    //Asks the delegate for the spacing between successive rows or columns of a section.
    //controls the space in between rows and columns
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1.0
    }
    //Asks the delegate for the spacing between successive items of a single row or column.
    //controls the space between each cell
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1.0
    }

I feel like it has to do with the sizeForItemAt but I can't exactly figure out how to change it.
This is what it currently looks like.

A: You're right, it has to do with sizeForItemAt method, you should use the indexPath parameter so you can use its property section to define the size for each item in each section.
Just remember that there is a space between items so you need to take that into account when calculating the width and height, so you can adjust the spacing using minimumLineSpacingForSectionAt and minimumInteritemSpacingForSectionAt methods.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    if indexPath.section == 0 {
        return CGSize(width: 200, height: 100)
    }

    return CGSize(width: (collectionView.bounds.size.width - CGFloat(numberOfItemsInSection))/2.2, height: collectionView.bounds.size.height - 50)

}


text:
Q: C++: extern and inline functions I have a couple of files written in C, and I want them to be C++-compatible, so for my C headers I use;
#ifdef __cplusplus
extern "C" {
#endif

at the beginning of the file and of course
#ifdef __cplusplus
}
#endif

...at the end. But it seems to create problems with the 'inline' keyword. My solution is to simply remove the inline keyword for C++, but I guess it could have a bad effect on C++ programs (these functions are called gazillions of times).
Is there a better solution ?

A: If I understand correctly, I would do:

 #ifdef __cplusplus
 #define D_INLINE static
 extern "C" {
 #else
 #define D_INLINE inline
 #endif

And use the D_INLINE for the functions that I think should need inline. As delnan said, the compiler will optimize it anyway and the inline keyword is just a hint to the compiler that the programmer thinks that the compiler should inline the function. It doesn't force the compiler to inline the function.

A: Inline functions are expected to be multiply defined, so:
#ifdef __cplusplus
extern "C" {
#elif __STDC_VERSION__ >= 199901L
   /* do nothing, C99 supports inline */
#else
#  define inline static
#endif

Many C compilers have non-standard extensions to mark functions as inline, you could also define it as __attribute__((always_inline)) (if __GNUC__ is defined)
EDIT: For better and more complete advice, see: http://www.greenend.org.uk/rjk/2003/03/inline.html


text:
Q: Binding button state (isEnabled) with array state in NSUserDefaults I need to bind the state of a button (isEnabled) to the state of an array (empty/not empty) in the NSUserDefaults.
I might need a NSValueTransformer mapping an empty array to NO and an array with at least an object to YES.
This is not correct, but near:
    [showEmptyFolders bind:@"enabled" toObject:[NSUserDefaults standardUserDefaults] withKeyPath:@"kPreferencesFolderArray" options:nil];

thanks

A: Link the array with an array controller and bind button's Enabled binding to arrangedObjects.@count keypath. Zero count works as boolean NO and any non-zero value is treated as YES. (It may work without array controller too, I just didn't try it).
BTW, you can add NSNegateBoolean standard transformer if you need it the opposite way.

A: You can create a value transformer that takes an array and returns YES or NO whether it has a non-zero element count or not. Something like this:
@interface PositiveCountTransformer : NSValueTransformer
@end

@implementation PositiveCountTransformer

+ (Class)transformedValueClass
{
    return [NSNumber class];
}

+ (BOOL)allowsReverseTransformation
{
    return NO;
}

- (id)transformedValue:(id)value
{
    NSInteger result;
    if ( [value isKindOfClass:[NSArray class]] )
        result = [value count];
    else
        result = 0; // Or however you want to handle it

    return [NSNumber numberWithBool:(result > 0)];
}

@end


text:
Q: How to overwrite beginning of a device with random bits or zeros? Just looking to overwrite a small portion of a device with zeros or random bits. More precisely I would like to overwrite the first 1% of all the sectors or few MiB. Is there an easy way to do that ?

A: Although /dev/urandom is extremely slow and as such not suitable for overwriting large amounts of data (entire disk), it might do for small regions.
Example overwriting 8MiB:
dd bs=1M count=8 iflag=fullblock if=/dev/urandom of=/dev/destroyme

Alternatively you can use shred:
shred -v -n 1 -s 8M /dev/destroyme

You can also use losetup to create devices of specific size and offsets, and overwrite them with utilities that don't have their own size / offset options.
losetup --find --show --offset 0 --sizelimit $((8*1024*1024)) /dev/destroyme
# will print /dev/loopX
cat /dev/urandom > /dev/loopX
losetup -d /dev/loopX

A: Same as with any file to overwrite the first 10 MiB with zeros:
head -c10M < /dev/zero 1<> /dev/sdax

For block device files, the 1<> to open without truncation is not even needed as there's no such thing as truncating a block device, so you can simply do:
head -c10M < /dev/zero > /dev/sdax

Not all head implementations support -c, and when they do, not all support that M suffix (and when they do M may mean megabyte (1000000 bytes) like ksh93's head builtin or mebibyte (1048576 bytes) like GNU head). In that case, you can do:
head -c "$((10 * 1024 * 1024)"

to make it explicit.
If we compare with dd bs=1M count=10 < /dev/zero > /dev/sdax:

*

*conceptually

*

*head is the command to read a specified number of bytes or lines from a file and write it to stdout

*while dd is a low level command to read and write data in the exact way you want it to.

I'd use head here on the ground that it's the command designed for the task. I'd use dd if I wanted to optimise for a specific use case, or use one of the specific features of dd (see also the note on portability).

*The read+write loop:

*

*head -c10M will try and read the requested data no matter what and only fail with a non-zero exit status if an error is encountered.

*dd bs=1M count=10, will do exactly 10 reads (as long as there's no error) and for each read that returns some data, do a corresponding write with the amount of data that was read. That only works as long as each read returns exactly the 1M requested. In practice, that's true for /dev/zero, but on Linux (4.6 at least), for /dev/urandom, I can't get more than 32MiB minus 1 byte in a single read (so still OK for 1MiB, though YMMV if you're using a different version of Linux), and for /dev/random, only a few bytes (what's currently in the entropy pool). The GNU implementation of dd has a iflag=fullblock to keep reading until the request buffer is full to behave like head, but if you don't have GNU dd, the only option is to do 1 byte reads at a time that would have dramatic impacts on the performance.

*performance:
For anything other than small amounts (less than a few hundred megabytes) where the data is written to buffers that will be flushed to disk later, or writing to /dev/null, the process will be I/O bound. If reading to /dev/urandom or /dev/random the bottle neck will be either the random number generation or the disk I/O. In those cases, you won't find much difference between dd and head. In any case head is likely to have a higher CPU overhead (unnoticed when the performance is I/O bound).

*

*head is a basic tool. Implementations will try to do the job as efficiently as possible while still being reliable for all types of input and output and not use too much resource. It will do the same read+write loop as dd, the main difference in terms of performance is the size of reads and writes which will determine the number of system calls being made.
Those sizes will depend on the implementation and version of head and possibly the system. With the latest version of GNU head on my system, the reads are of size BUFSIZE (8KiB on GNU systems), and the writes of size 4KiB, though that can be changed with stdbuf -o 1M for instance.
ksh93's head builtin seems to do 64KiB reads and writes and doesn't use the libc's stdio, at least on my system.
GNU head using stdio also means extra overhead incurred by stdio (the implementation of which is system dependant).
Current versions of GNU cat use fadvise to tell the system that it will read the data sequentially so it can optimise caching accordingly. It's not impossible some implementations of head do that as well, or will do in the future. dd being low-level, I would expect it would only do it if you told it to (I'm not aware of any dd implementation that has such support).

*dd is very low level, it will call the read() and write() system calls directly. You can't get much more efficient than that other than by using specialised APIs like Linux' sendfile().
It gives you much more control on the size of the read() and write(), so lets you optimise yourself based on the type of the input/output and the available resources. For instance, if you have a lot of memory available, you might as well read the whole data in one go (though in my tests while copying from /dev/zero to /dev/null, I can't see any significant improvement past a block size of 32KiB and performance even start to degrade after a blocksize of 1MiB).

*portability
None of -c, bs=10M, conv=fullblock are portable. The only POSIX command to read a certain amount of data from a file is dd, but to use it reliably (except on /dev/zero), as discussed above, you need bs=1 which means dreadful performance.

*consequence of write errors.
Both head and dd will exit at once when trying to write past the end of the  block device. If the disk has failing sectors, that will generally not be detected because the actual writing to disk is asynchronous. With the GNU implementation of dd, you can force the write to be direct with oflag=direct which means dd will stop on the first error. You may want to use the default block size of 512 then if you want to write as much as possible before the first failing sector.

*consequence of read errors
You shouldn't get any read error on /dev/zero, /dev/urandom or /dev/random. But more generally, both head and dd will exit with an error upon the first read error. With dd, you can carry on upon errors with conv=noerror. In that case, you'll probably want to add the sync option (conv=noerror,sync) so that the failed blocks are padded with zeros. head will not give you any option to do that as it's not been designed for that.
Alternatives.

*

*pv -Ss 10M < /dev/zero > /dev/sdax will copy those 10M and give you a progress bar. By default the read/write size are 128KiB in my test. You can change it with the -B option, but in my tests, 128KiB gives the best results already. pv has a -E option equivalent to dd's conv=noerror,sync.
On Linux, it's also good for I/O on pipes as it uses the splice() system call to optimise performances.

*If you want to play with the sendfile() system call, you can use xfs_io.
xfs_io -c 'sendfile -i src 0 10M' dst

sends 10M from src to dst. However, it only does one sendfile() and the system call can't be used on /dev/zero, /dev/random nor /dev/urandom. It can be used on sparse files though.
 truncate -s 1T empty-file
 xfs_io -c 'sendfile -i empty-file 0 10M' /dev/sdax

would work but for large amounts (several Gibibytes), because that's one sendfile() system call, that much memory must be allocated which means it's going to be less efficient than dd bs=1M. Ideally, we'd want to do multiple sendfile()s of only a few mebibytes at a time, but I'm not aware of any command that does that.

*For /dev/zero input, you don't really need to read the data for each block you write. After all, it's only zeros. It's easy enough to create a buffer with only zeros without having to read /dev/zero, and we can reuse it between every write. For example:
PERLIO=:unix perl -e '$x = pack("x" . 1024*1024); print $x for 1..10000' > /dev/sdax

to write 10000 MiB would be a lot more efficient (despite the perl overhead) than any solution that repeatedly reads /dev/zero.

A: You can use dd to do that using the /dev/urandom device which will provide you with random data. An example :
dd if=/dev/urandom of=/dev/sdX bs=1M count=100

this will write 100mbyte of random data :

*

*if is the input file

*of is the output file

*bs=1M is the block size 1Mbyte

*count is how many times should be this blocks written

You can as well use as input file /dev/zero, /dev/null or anything else which provides you data. This command will start writing the data at the beginning of the output file/device.


text:
Q: Put Facebook like XFBML button in line with Pinterest button I know similar questions have been aske before but I'm new at this and can't make sense of it. I'm fairly sure its a straightforward task but I can't do it.
I'm using a CMS on which I cannot access the css template currently.
All I want is to add a Pinterest button and facebook like button to my individual product pages using the html source code editor in a nice neat row. At the moment they display one below the other.
These are the codes:

<fb:like send="true" layout="button_count" width="100" show_faces="false"></fb:like>

How to write the correct styling code to achieve this?


text:
Q: MOSFET as OE for 74HC165 I am using SPI with an Arduino Uno for a few different things. My project's buttons are all running through a 74HC165 shift register to the Arduino's MISO. Unfortunately, the 165 has no 0E. As such, it seems that the 165's  output is constantly on even though it's slave select is off. This is interfering with the MISO of other SPI devices I am using at the same time.  I need a way of turning the 165's output off (ie linked to slave select).
Is it possible to use an n-MOSFET to control the data flow from the 165's output to the Arduino's MISO? Or do I need to use an IC like the 74HC125?
Thank you very much in advance!

A: Yes, the '165 is just a shift register. It was never intended to be a fully SPI-compatible device.
Using an N-channel MOSFET would convert its output into an open-collector (really open-drain) output with enable. If you go this route, you'll need to have a pullup resistor on the MISO line, because the MOSFET will only be able to pull it low. Also, the gate of the MOSFET is active-high, so you'll need to invert your SS signal to match. (Actually, I guess you can use the same signal that you're driving the '165's \$\text{SH}/\overline{\text{LD}}\$ input to drive the MOSFET as well, since you want it enabled while you're shifting.)
The '125 has an active-low enable, and its output is true 3-state, so this is actually the more direct approach, especially if you have more than one device you want to connect to MISO.


text:
Q: How do I read session properties using useSession() in getServerSideProps() using nextjs and next-auth? I am trying to only show data where the "Heading" is the same as the logged-in user's name. I'm using Next.js and I'm trying to server render the data from my Prisma database, but when I try to filter the data to only show "Segments" where the "Heading" is the same as the currently logged-in user it throws an error:

Server Error
TypeError: Cannot read properties of null (reading 'useContext')

I am using Next-Auth for user authentication and previously I have use this method to access the currently logged in user's data:
import { useSession } from "next-auth/react";
.
.
.
const { data: session } = useSession();
.
.
.

User name: {session.user.name}

But when I use getServerSideProps() that method doesn't work.
This is what I tried so far:
export async function getServerSideProps() {
  const { data: session } = useSession();

  const segments: Segment[] = await prisma.segment.findMany({
    where: {
      Heading: session.user.name,
    },
  });
  return {
    props: {
      initialSegments: segments,
    },
  };
}

But it shows me the error shown above.

A: useSession is unavailable on the server side according to next-auth's docs.
You may be able to use unstable_getServerSession(), however do note that it's experimental and its API may change in the future (as noted in the docs).


text:
Q: Show that $A_n$ is the kernel of a group homomorphism of $S_n \rightarrow \{−1,1\}$. I know that the kernel is always normal but how to prove or show that $A_n$ is the kernel?

A: Try building an explicit homomorphism
$$\phi : S_n \longrightarrow \{-1, 1\} $$
Let us show that $\phi(\pi_i) = sgn(\pi_i)$ is an homomorphism as asked.
Remember that any permutation $\pi_i$ can be decomposed in a number of transpositions. Although this decomposition is not unique, it can be shown that if some permutation $\pi_a$ has a decomposition with an even amount of transpositions, then all decompositions of $\pi_a$ must use an even number of transpositions and $\pi_a$ is said to be even. Analogously, if a permutation $\pi_b$ has a decomposition with an odd number of transpositions, then all decompositions of $\pi_b$ have an odd number of transpositions and $\pi_b$ is said to be odd.
When then define $sgn(\pi_i)$ as $1$ if $\pi_i$ is even and $-1$ if $\pi_i$ is odd.
I leave it to you as an exercise to show that $sgn(\pi_i \circ \pi_j) = sgn(\pi_i)\times sgn(\pi_j)$
Now all you have to do is show that this homomorphism has $A_n$ as kernel.