text:
Q: Effects of listening to music always in MP3 format Erstwhile I've read an article somewhere which claims that listening to music continually in MP3 format is harmful for ears. Since MP3 is a compressed format of audio tracks, some sounds in tracks are deducted and eventually the size of MP3 file is reduced. As humans, we cannot notice the difference between MP3 (e.g. 320 kbps) and original audio track while listening, but in fact, our ears can distinguish. As a consequence, the article claims that if we continually listen to MP3, this results in losing the distinguishing capability of ears, and finally ears won't notice the fine differences between sounds anymore.
Is this completely true? Are we doing harm to our ears with our MP3 addiction?
And which digital format is closest to original audio? Is it FLAC?

A: There is some evidence to suggest that continued exposure to mp3s over lossless formats tends to make you prefer the artefacts introduced during compression to the raw, unadulterated audio.
As for damage to hearing, as other people have commented it can't damage your hearing unless it is deafening you with excessive volume.

A: It sound like bunkum to me and should be assigned to the "woo" section along with gold plated connectors and kettle leads.
To answer your second point - any lossless format will be closer to the original source, so FLAC is a good candidate.

A: 1)
No, MP3's won't damage your ears any more than any other audio format. The problem is not what audio format is used, but the volume at which audio is played.

*

*Choose any audio format you want (whatever is convenient in your situation)

*Keep the volume down, don't play it too loud.

*Use headphones of decent quality - but still keep the volume down.
Headphones don't have to be super expensive, but those you get with MP3-players and cell phones are too cheap and provide sound that is uncomfortable.

2)
Any lossless audio format will do, for instance FLAC or WAV. These formats make much larger file sizes, and some players only understand MP3, which is why MP3 is often more practical.
Keep in mind that even lossless audio formats are only as good as the source that's being recorded, so it wouldn't make sense to convert MP3 to FLAC, or use FLAC for recordings off the radio or a cassette tape.
Note:
I thought there were good answers, but not very precise. I've tried to be precise and informative.

A: The claim sounds more like the lament of an audio connoisseur. In much the same way that a food connoisseur might lament that people who regularly consume foods containing corn syrup, artificial sweeteners, supermarket "meat and carrageenan" deli products, etc. that they now fail to notice or appreciate the superiority of foods made from more natural unprocessed fresher ingredients.
When listening to MP3 files was something new, the compression artifacts stood out and bothered people more, in sort of the same way that the first audience to hear Stravinsky's ballet "The Rite of Spring" in 1913 literally rioted. In time, just as people a generation ago got so used to the distortions of vinyl recordings that some actually preferred them to CDs, we got used to the MP3 compression artifacts and just learned to accept them.
You can still appreciate how an audiophile must feel when some whipper-snapper contends that his 128kbps MP3 file sounds "better than the CD" once you punch a little EQ in there and turn on the 3D stereo ambience effect.

A:
Is this completely true? Are we doing harm to our ears with our MP3 addiction?

No.
Music broadcast over FM radio is compressed and even though I've been listening to that for years I can still spot the different between an radio broadcast and a CD.
It's hard to tell without reading the source, but it sounds like pretentious audiophile drivel IMHO.
My guess the article was written by someone with a $10,000 Hi-Fi system and when someone pointed out they couldn't hear any difference between that and a $1,000 system the author said, "You can't hear the difference because you've broken your ears by listening to MP3s."
There is a separate issue that listening to music too loud will damage your hearing but that will happen no matter what the format the music is stored in.  Plenty of rock musicians have damaged their hearing listening to live music which has no encoding whatsoever.

A: It is more likely to be the loud volumes in your ears that will damage them.
Differentiating a 320Kbps MP3 from a FLAC or Audio CD is difficult even for most healthy ears.
The BBC article referred above may be similar to your source.
If so, it is an excellent example of incorrect titles for articles
that source many urban-myths.
The article title goes: MP3 users hearing damage warning ...
But says things along these lines,

A recent study by the Royal National Institute for Deaf People (RNID) found
  39% of 18 to 24-year-olds listened to personal music players for at least an hour every day
  and 42% admitted they thought they had the volume too high.

Another article clearly mentions high decibels causing hearing loss,
Experts fear iPods, MP3 players may lead to hearing-loss epidemic

"The iPods have been measured at nearly 130 decibels.
  A jet engine is 133 decibels from 100 feet away,"
  said Rick Kottler, executive director of Deaf and Hard Hearing Services of the Treasure Coast.

Bottom line, check the volume button rather than the audio bitrate.

Further reading for ear-phone users (that includes me).
Causes of Tinnitus - Protect Your Ears -- How Loud is Loud.
To hear music against the background city noise (90-96dB),
you will most likely push 20dB beyond it -- (somwhere like 110dB).
Compare that in the linked article -- add in any more references you get.

A: Persistently listening to loud music will result in a loss of hearing capability. Listening to one sound or another at safe volumes will not physically damage the ear, but listeners will most likely become accustomed to the sound of MP3s. However, most people use crap ear-buds and MP3 quality isn't the problem there. Besides, it's not a one-way street.

A: Dont be confused. The differences in audio file formats are just to help the device, e.g a computer that is interpreting it into sound to know how to go about doing it. Once this music file, however the format it was created with is changed to sound wave, then the output its sound wave and there's nothing like mp3 sound wave or AAC sound wave or whatever, sound wave is sound wave is sound wave so long as its vibration of air molecules at a frequency suitable for the ears. I think you should rather be concerned about how loud is the sounds youre feeding your ear drums.
So, the differences in music formats are the businesses of the device transforming them to sound vaves and not the business of your ears. Your ear hears sound waves so long as the frequency is not too high.

A: I don't see how it could cause physical harm JUST because it's MP3.  As mentioned by others, excessive volume is the problem.  However, some people do find listening to digitized music to be annoying versus analog (just like some people find noise-cancelling headsets to be annoying/give them a headache versus regular headsets).


text:
Q: How can I convert IP range to Cidr in C#? There has lots of example of convert CIDR to ip range. But I want to know how can I use start/end ip address to generate a/some cidr in C#?
for example:
I have start ip address(192.168.0.1) and end ip address(192.168.0.254). So use these two address to generate cidr list {192.168.0.0/31, 192.168.0.2/32}.  Is there any C# code example?

A: It is difficult to determine the what exactly is being asked here (the CIDR list you give doesn't seem to correspond with the given input addresses), however the following code will allow you to find the smallest single CIDR that contains the specified start and end addresses.
You need to first convert the start and end IP addresses into 32 bit integers (e.g. 192.168.0.1 becomes 0xc0a80001), then apply the following algorithm:
var startAddr = 0xc0a80001; // 192.168.0.1
var endAddr = 0xc0a800fe;   // 192.168.0.254

// Determine all bits that are different between the two IPs
var diffs = startAddr ^ endAddr;

// Now count the number of consecutive zero bits starting at the most significant
var bits = 32;
var mask = 0;
while (diffs != 0)
{
    // We keep shifting diffs right until it's zero (i.e. we've shifted all the non-zero bits off)
    diffs >>= 1;
    // Every time we shift, that's one fewer consecutive zero bits in the prefix
    bits--;
    // Accumulate a mask which will have zeros in the consecutive zeros of the prefix and ones elsewhere
    mask = (mask << 1) | 1;
}

// Construct the root of the range by inverting the mask and ANDing it with the start address
var root = startAddr & ~mask;
// Finally, output the range
Console.WriteLine("{0}.{1}.{2}.{3}/{4}", root >> 24, (root >> 16) & 0xff, (root >> 8) & 0xff, root & 0xff, bits);

Running it on the two addresses in your question gives:
192.168.0.0/24

A: CIDR class with static methods to split an IP range into a minimal set of disjoint CIDR ranges, which cover exactly the original IP range.
The split methods (the "real" one working on BigIntegers doing the actual work, and the wrapper for IP addresses and CIDR creation) are at the bottom.
Use with foreach (IPRangeToCidr.CIDR c in IPRangeToCidr.CIDR.split(first, last)) ...
Requires System.Numerics.dll in the references.
using System;
using System.Numerics;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;

namespace IPRangeToCidr {
    public struct CIDR {
        private IPAddress address;
        private uint network_length, bits;

        public CIDR(IPAddress address, uint network_length) {
            this.address = address;
            this.network_length = network_length;
            this.bits = AddressFamilyBits(address.AddressFamily);
            if (network_length > bits) {
                throw new ArgumentException("Invalid network length " + network_length + " for " + address.AddressFamily);
            }
        }

        public IPAddress NetworkAddress {
            get { return address; }
        }
        public IPAddress LastAddress {
            get { return IPAddressAdd(address, (new BigInteger(1) << (int) HostLength) - 1); }
        }
        public uint NetworkLength {
            get { return network_length; }
        }
        public uint AddressBits {
            get { return bits; }
        }
        public uint HostLength {
            get { return bits - network_length; }
        }

        override public String ToString() {
            return address.ToString() + "/" + NetworkLength.ToString();
        }

        public String ToShortString() {
            if (network_length == bits) return address.ToString();
            return address.ToString() + "/" + NetworkLength.ToString();
        }

        /* static helpers */
        public static IPAddress IPAddressAdd(IPAddress address, BigInteger i) {
            return IPFromUnsigned(IPToUnsigned(address) + i, address.AddressFamily);
        }

        public static uint AddressFamilyBits(AddressFamily family) {
            switch (family) {
            case AddressFamily.InterNetwork:
                return 32;
            case AddressFamily.InterNetworkV6:
                return 128;
            default:
                throw new ArgumentException("Invalid address family " + family);
            }
        }

        private static BigInteger IPToUnsigned(IPAddress addr) {
            /* Need to reverse addr bytes for BigInteger; prefix with 0 byte to force unsigned BigInteger
             * read BigInteger bytes as: bytes[n] bytes[n-1] ... bytes[0], address is bytes[0] bytes[1] .. bytes[n] */
            byte[] b = addr.GetAddressBytes();
            byte[] unsigned = new byte[b.Length + 1];
            for (int i = 0; i < b.Length; ++i) {
                unsigned[i] = b[(b.Length - 1) - i];
            }
            unsigned[b.Length] = 0;
            return new BigInteger(unsigned);
        }

        private static byte[] GetUnsignedBytes(BigInteger unsigned, uint bytes) {
            /* reverse bytes again. check that now higher bytes are actually used */
            if (unsigned.Sign < 0) throw new ArgumentException("argument must be >= 0");
            byte[] data = unsigned.ToByteArray();
            byte[] result = new byte[bytes];
            for (int i = 0; i < bytes && i < data.Length; ++i) {
                result[bytes - 1 - i] = data[i];
            }
            for (uint i = bytes; i < data.Length; ++i) {
                if (data[i] != 0) throw new ArgumentException("argument doesn't fit in requested number of bytes");
            }
            return result;
        }

        private static IPAddress IPFromUnsigned(BigInteger unsigned, System.Net.Sockets.AddressFamily family) {
            /* IPAddress(byte[]) constructor picks family from array size */
            switch (family) {
            case System.Net.Sockets.AddressFamily.InterNetwork:
                return new IPAddress(GetUnsignedBytes(unsigned, 4));
            case System.Net.Sockets.AddressFamily.InterNetworkV6:
                return new IPAddress(GetUnsignedBytes(unsigned, 16));
            default:
                throw new ArgumentException("AddressFamily " + family.ToString() + " not supported");
            }
        }

        /* splits set [first..last] of unsigned integers into disjoint slices { x,..., x + 2^k - 1 | x mod 2^k == 0 }
         *  covering exaclty the given set.
         * yields the slices ordered by x as tuples (x, k)
         * This code relies on the fact that BigInteger can't overflow; temporary results may need more bits than last is using.
         */
        public static IEnumerable<Tuple<BigInteger, uint>> split(BigInteger first, BigInteger last) {
            if (first > last) yield break;
            if (first < 0) throw new ArgumentException();
            last += 1;
            /* mask == 1 << len */
            BigInteger mask = 1;
            uint len = 0;
            while (first + mask <= last) {
                if ((first & mask) != 0) {
                    yield return new Tuple<BigInteger, uint>(first, len);
                    first += mask;
                }
                mask <<= 1;
                ++len;
            }
            while (first < last) {
                mask >>= 1;
                --len;
                if ((last & mask) != 0) {
                    yield return new Tuple<BigInteger, uint>(first, len);
                    first += mask;
                }
            }
        }

        public static IEnumerable<CIDR> split(IPAddress first, IPAddress last) {
            if (first.AddressFamily != last.AddressFamily) {
                throw new ArgumentException("AddressFamilies don't match");
            }
            AddressFamily family = first.AddressFamily;
            uint bits = AddressFamilyBits(family); /* split on numbers returns host length, CIDR takes network length */
            foreach (Tuple<BigInteger, uint> slice in split(IPToUnsigned(first), IPToUnsigned(last))) {
                yield return new CIDR(IPFromUnsigned(slice.Item1, family), bits - slice.Item2);
            }
        }
    }
}

A: Necromancing.
No, there wasn't, and I don't understand why people keep upvoting wrong answers.
Here's the code for IP-range to CIDR & vice-versa:
// https://dev.maxmind.com/geoip/
// https://stackoverflow.com/questions/461742/how-to-convert-an-ipv4-address-into-a-integer-in-c
public static string IPrange2CIDR(string ip1, string ip2)
{
    uint startAddr = IP2num(ip1);
    uint endAddr = IP2num(ip2);

    // uint startAddr = 0xc0a80001; // 192.168.0.1
    // uint endAddr = 0xc0a800fe;   // 192.168.0.254
    // uint startAddr = System.BitConverter.ToUInt32(System.Net.IPAddress.Parse(ip1).GetAddressBytes(), 0);
    // uint endAddr = System.BitConverter.ToUInt32(System.Net.IPAddress.Parse(ip2).GetAddressBytes(), 0);

    if (startAddr > endAddr)
    {
        uint temp = startAddr;
        startAddr = endAddr;
        endAddr = temp;
    }

    // uint diff = endAddr - startAddr -1;
    // int bits =  32 - (int)System.Math.Ceiling(System.Math.Log10(diff) / System.Math.Log10(2));
    // return ip1 + "/" + bits;

    uint diffs = startAddr ^ endAddr;

    // Now count the number of consecutive zero bits starting at the most significant
    int bits = 32;
    // int mask = 0;

    // We keep shifting diffs right until it's zero (i.e. we've shifted all the non-zero bits off)
    while (diffs != 0)
    {
        diffs >>= 1;
        bits--; // Every time we shift, that's one fewer consecutive zero bits in the prefix
        // Accumulate a mask which will have zeros in the consecutive zeros of the prefix and ones elsewhere
        // mask = (mask << 1) | 1;
    }

    string res = ip1 + "/" + bits;
    System.Console.WriteLine(res);
    return res;
}

// https://www.digitalocean.com/community/tutorials/understanding-ip-addresses-subnets-and-cidr-notation-for-networking
public static void CIDR2IP(string IP)
{
    string[] parts = IP.Split('.', '/');

    uint ipnum = (System.Convert.ToUInt32(parts[0]) << 24) |
        (System.Convert.ToUInt32(parts[1]) << 16) |
        (System.Convert.ToUInt32(parts[2]) << 8) |
        System.Convert.ToUInt32(parts[3]);

    int maskbits = System.Convert.ToInt32(parts[4]);
    uint mask = 0xffffffff;
    mask <<= (32 - maskbits);

    uint ipstart = ipnum & mask;
    uint ipend = ipnum | (mask ^ 0xffffffff);

    string fromRange = string.Format("{0}.{1}.{2}.{3}", ipstart >> 24, (ipstart >> 16) & 0xff, (ipstart >> 8) & 0xff, ipstart & 0xff);
    string toRange = string.Format("{0}.{1}.{2}.{3}", ipend >> 24, (ipend >> 16) & 0xff, (ipend >> 8) & 0xff, ipend & 0xff);

    System.Console.WriteLine(fromRange + " - " + toRange);
}

public static uint IP2num(string ip)
{
    string[] nums = ip.Split('.');
    uint first = System.UInt32.Parse(nums[0]);
    uint second = System.UInt32.Parse(nums[1]);
    uint third = System.UInt32.Parse(nums[2]);
    uint fourth = System.UInt32.Parse(nums[3]);

    return (first << 24) | (second << 16) | (third << 8) | (fourth);
}

public static void Test()
{
    string IP = "5.39.40.96/27";
    // IP = "88.84.128.0/19";
    CIDR2IP(IP);

    // IPrange2CIDR("88.84.128.0", "88.84.159.255");
    IPrange2CIDR("5.39.40.96", "5.39.40.127");

    System.Console.WriteLine(System.Environment.NewLine);
    System.Console.WriteLine(" --- Press any key to continue --- ");
    System.Console.ReadKey();
}

A: I use this for IpV4, let me know if there is a problem in it.
You can find the extraction source code from the following link:
https://blog.ip2location.com/knowledge-base/how-to-convert-ip-address-range-into-cidr/
using System;
using System.Collections.Generic;
using System.Net;

namespace ConsoleApp
{
    public class IPNetwork
    {
        private readonly long _firstIpAddress;
        private readonly long _lastIpAddress;

        public static IPNetwork[] FromIpRange(IPAddress firstIpAddress, IPAddress lastIpAddress)
            => FromIpRange(IpAddressToLong(firstIpAddress), IpAddressToLong(lastIpAddress));

        public static IPNetwork[] FromIpRange(long firstIpAddress, long lastIpAddress)
        {
            var result = new List<IPNetwork>();
            while (lastIpAddress >= firstIpAddress)
            {
                byte maxSize = 32;
                while (maxSize > 0)
                {
                    long mask = IMask(maxSize - 1);
                    long maskBase = firstIpAddress & mask;

                    if (maskBase != firstIpAddress)
                        break;

                    maxSize--;
                }
                double x = Math.Log(lastIpAddress - firstIpAddress + 1) / Math.Log(2);
                byte maxDiff = (byte)(32 - Math.Floor(x));
                if (maxSize < maxDiff)
                {
                    maxSize = maxDiff;
                }
                var ipAddress = IpAddressFromLong(firstIpAddress);
                result.Add(new IPNetwork(ipAddress, maxSize));
                firstIpAddress += (long)Math.Pow(2, 32 - maxSize);
            }
            return result.ToArray();
        }

        private static long IMask(int s)
        {
            return (long)(Math.Pow(2, 32) - Math.Pow(2, 32 - s));
        }

        public static long IpAddressToLong(IPAddress ipAddress)
        {
            var bytes = ipAddress.GetAddressBytes();
            return ((long)bytes[0] << 24) | ((long)bytes[1] << 16) | ((long)bytes[2] << 8) | bytes[3];
        }

        public static IPAddress IpAddressFromLong(long ipAddress)
            => new IPAddress((uint)IPAddress.NetworkToHostOrder((int)ipAddress));

        public IPNetwork(IPAddress prefix, int prefixLength = 32)
        {
            if (prefix.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
                throw new NotSupportedException("IPv6 is not supported");

            Prefix = prefix;
            PrefixLength = prefixLength;

            var mask = (uint)~(0xFFFFFFFFL >> prefixLength);
            _firstIpAddress = IpAddressToLong(Prefix) & mask;
            _lastIpAddress = _firstIpAddress | ~mask;
        }

        public static IPNetwork Parse(string value)
        {
            try
            {
                var parts = value.Split('/');
                return new IPNetwork(IPAddress.Parse(parts[0]), int.Parse(parts[1]));
            }
            catch
            {
                throw new FormatException($"Could not parse IPNetwork from {value}");
            }
        }

        public override string ToString() => $"{Prefix}/{PrefixLength}";

        public IPAddress Prefix { get; }
        public int PrefixLength { get; }
        public IPAddress LastAddress => IpAddressFromLong(_lastIpAddress);
        public IPAddress FirstAddress => IpAddressFromLong(_firstIpAddress);
        public long Total => _lastIpAddress - _firstIpAddress + 1;
    }
}

Usage 1:
var startAddress = IPAddress.Parse("192.168.0.0");
var endAddress = IPAddress.Parse("192.168.0.255");
foreach (var item in IPNetwork.FromIpRange(startAddress, endAddress))
        Console.WriteLine(item);

Result
192.168.0.0/24

Usage 2:
var startAddress = IPAddress.Parse("192.168.0.1");
var endAddress = IPAddress.Parse("192.168.0.254");
foreach (var item in IPNetwork.FromIpRange(startAddress, endAddress))
        Console.WriteLine(item);

Result:
192.168.0.1/32
192.168.0.2/31
192.168.0.4/30
192.168.0.8/29
192.168.0.16/28
192.168.0.32/27
192.168.0.64/26
192.168.0.128/26
192.168.0.192/27
192.168.0.224/28
192.168.0.240/29
192.168.0.248/30
192.168.0.252/31
192.168.0.254/32

A: I would recommend the use of IPNetwork Library https://github.com/lduchosal/ipnetwork.
As of version 2, it supports IPv4 and IPv6 as well.
Supernet
  IPNetwork network = IPNetwork.Parse("192.168.0.1");
  IPNetwork network2 = IPNetwork.Parse("192.168.0.254");

  IPNetwork ipnetwork = IPNetwork.Supernet(network, network2);

  Console.WriteLine("Network : {0}", ipnetwork.Network);
  Console.WriteLine("Netmask : {0}", ipnetwork.Netmask);
  Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast);
  Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable);
  Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable);
  Console.WriteLine("Usable : {0}", ipnetwork.Usable);
  Console.WriteLine("Cidr : {0}", ipnetwork.Cidr);

Output
Network : 192.168.0.0
Netmask : 255.255.255.0
Broadcast : 192.168.0.255
FirstUsable : 192.168.0.1
LastUsable : 192.168.0.254
Usable : 254
Cidr : 24

Have fun !

A: I found this C code and converted it into C# and it's working now.

redpajama_set_name: RedPajamaStackExchange


text:
Q: записать в виде генератора for x, y in zip(c,a):
  for i in range(y-1):
    print(x,end="")

Так выглядит финальная часть работающего кода, но изначально хотел записать в виде генератора, но не вышло.Помогите с этим плиз.(в списке "a" хранятся числа, в списке "c" хранятся буквенные значения в формате str, результат всего кода выглядит так:

PPPPPPPPPZZZZZZZZZZZZZQQQQQQQQQQQQQQaaaaaaaaaaaaaaFFFFFFFFFFFFFwwwwwwwwwwTTTTTxxxxxxxkkkkkkkkkkkkkkkkpppppppppppppppGGGGGGGGHHHHHHHHHHHHQHHHHHHHHHHqqqqZZZZZZZZZZZZZZZJJJcccccccOOOOOBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCgggggggggggggaaaaGGGGGGGGGGGGGGGGRRRRRRRRRRRRRRRRRRuuuuuuuuuuuuuuuuuuOOOOOOOOOOOOOOOO

То есть вывод должен быть чистым без кавычек, скобок и т.д.

A: https://ideone.com/Cs7qDM
print("".join(s*i for i,s in zip([1,4,2,5], ['a','q','s','z'])))

s*i - умножение строки на число. "А"*3 будет "ААА"


text:
Q: How to update multiple instance fields within a DRF Serializer? In the DRF docs: https://www.django-rest-framework.org/tutorial/1-serialization/#creating-a-serializer-class
It is shown how to update an existing instance using the update method. But the code that is shown is highly repetitive and has a DRY problem if the model is updated. How can the validated_data be passed into the instance once before then calling save?
    def update(self, instance, validated_data):
        """
        Update and return an existing `Snippet` instance, given the validated data.
        """
        instance.title = validated_data.get('title', instance.title)
        instance.code = validated_data.get('code', instance.code)
        instance.linenos = validated_data.get('linenos', instance.linenos)
        instance.language = validated_data.get('language', instance.language)
        instance.style = validated_data.get('style', instance.style)
        instance.save()
        return instance

A: You could use setattr()
def update(self, instance, validated_data):
    for key,value in validated_data.items():
        setattr(instance,key,value)
    instance.save()
    return instance


text:
Q: Wordpress multisite subdirectory on nginx behind reverse proxy I can't seem to make wordpress multisite subdirectories work behind my reverse proxy.
Locally (from lan ip addresses) all works, I can access the main domain, sub-directories and all dashboards.
The moment I add a reverse proxy, I cannot access the network dashboard (Redirect loop) nor the multisites subdirectories (redirects to lan ip).
If I try to go to the multisites by manually writing the address it will send me to the page without css.
The only one that works with the reverse proxy is the main site.
What I want :

*

*www.example.net

*www.example.net/wp-admin

*www.example.net/wp-admin/network

*www.example.net/sub1

*www.example.net/sub1/wp-admin

*www.example.net/sub2

*www.example.net/sub2/wp-admin

What happens :

*

*www.example.net --> ok

*www.example.net/wp-admin --> ok

*www.example.net/wp-admin/network --> redirect loop

*www.example.net/sub1 --> no css

*www.example.net/sub1/wp-admin --> no css

*www.example.net/sub2 --> no css

*www.example.net/sub2/wp-admin --> no css

Reverse Proxy conf
server {
        listen       80;
        server_name  *.example.net example.net;
        return 302 $scheme://www.example.net$request_uri;
}

server {
        listen       80;
        server_name  www.example.net;
        return 302 https://$host$request_uri;
}

server {
    listen       443 ssl http2;
    server_name  www.example.net;

    ssl on;
    ssl_certificate /etc/letsencrypt/live/www.example.net/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/www.example.net/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

        error_page 404 /404.html;
            location = /40x.html {
        }
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }

        location ^~ / {
                proxy_pass              http://192.168.2.30/;
                proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header      X-Real-IP $remote_addr;
                proxy_set_header        X-Forwarded-Proto       $scheme;
        }
}

wp-config.php
/* Updates asking for FTP */
define('FS_METHOD','direct');

/* Multisite */
define( 'WP_ALLOW_MULTISITE', true );
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
// define('DOMAIN_CURRENT_SITE', '192.168.2.30');
define('DOMAIN_CURRENT_SITE', 'www.example.net');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);

/* Faire fonctionner SSL (et CSS) */
if ( (!empty( $_SERVER['HTTP_X_FORWARDED_HOST'])) ||
     (!empty( $_SERVER['HTTP_X_FORWARDED_FOR'])) ) {
    $_SERVER['HTTPS'] = 'on';
}

wordpress nginx conf
server {
        listen       80 default_server;
        server_name     192.168.2.30;

        root   /var/www/html/wordpress;

        access_log      /var/log/nginx/wp.access.log;
        error_log       /var/log/nginx/wp.error.log;

        ## WordPress Perm links config
        location / {
                index index.php index.html;
                try_files $uri $uri/ /index.php?$args;
        }

        # Rewrite multisite in a subdirectory '.../wp-.*' and '.../*.php'.
         if (!-e $request_filename) {
            rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 last;
            rewrite ^/[_0-9a-zA-Z-]+.*(/wp-admin/.*\.php)$ $1 last;
            rewrite ^/[_0-9a-zA-Z-]+(/.*\.php)$ $1 last;
        }

        # Pass all .php files onto a php-fpm or php-cgi server
        location ~ \.php$ {
           try_files $uri =404;
           include fastcgi_params;
           fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
           fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
           fastcgi_index index.php;
        }
}

If I add 'proxy_set_header Host $host' to reverse proxy conf I get this error when trying to access wp-admin
Error establishing a database connection

If your site does not display, please contact the owner of this network. If you are the owner of this network please check that MySQL is running properly and all tables are error free.

Could not find site www.example.net. Searched for table wp_blogs in database wordpressDB. Is that right?

What do I do now? Read the bug report page. Some of the guidelines there may help you figure out what went wrong. If you're still stuck with this message, then check that your database contains the following tables:

    wp_users
    wp_usermeta
    wp_blogs
    wp_signups
    wp_site
    wp_sitemeta
    wp_registration_log
    wp_blog_versions

The dashboard does not keep the domain name for links (everything redirects to ip). I tried adding this bit of code to the wp-config but it still didn't change anything.
      define('WP_HOME', 'https://www.example.net');
      define('WP_SITEURL', 'https://www.example.net');

A: The problem was the sql database that did not update urls. I do not know if there is a way to do this easily but I feel like I have looked everywhere for this solution and finally found it with this answer to a somewhat similar question : https://premium.wpmudev.org/forums/topic/how-to-change-url-for-wp-multi-site#post-426799
I started over from where everything works locally (from ip address) then from there I went into the database to change :

*

*siteurl and home from wp_options to http://www.example.net/

*siteurl and home from wp_{blog_id}_options to http://www.example.net/{blog} (where {blog_id} is the ID of the additional sites and {blog} is sub1 and sub2)

*domain from wp_site and wp_blogs to www.example.net
If I leave this as is I'll get a Error establishing a database connection
As the above link says to I went back to the wp-config file to change the DOMAIN_CURRENT_SITE to www.example.net.
Letting this as is I get a gateway error, so I went to the reverse proxy and added this bit to the wordpress server location :
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header Host $host;

And voila! Wordpress multisite behind a reverse proxy!
If I want to add a new subsite It keeps all the good info, so I don't need to redo this. The only "downside" is that I cannot access the website from the local ip anymore, but then I'd just need to go over these steps and change the domain for the ip tol go back.


text:
Q: How to display a line for every python cell boundary in Visual Studio Code? In VS Code, when working with python files, if we type #%% it creates a cell separation.  When the cursor is within a cell, the editor displays a thick line for the top boundary and a thin line for the bottom boundary (of the current cell only).  How can I change the style so that a line is always displayed for every cell boundary (like in the Spyder editor)?
Edit:
I found these settings but they only apply to the interactive window and not the editor:
    "workbench.colorCustomizations": {
        "notebook.cellBorderColor": "#ff0000",
        "notebook.cellToolbarSeparator": "#00ff00"
    }

I am expecting to find a way of showing lines at the red arrows below:

I have seen screenshots showing such lines but I can't find how.
Edit 2: Is there a way to customize the style/appearance of every inserted line showing the clickable commands Run Cell | Run Above | Debug Cell ?

A: take a look at this:  extension-visualstudio
maybe we need to checkout [vscode-python] (https://github.com/microsoft/vscode-python): package.nls.json stores a lot of dicts, but i can't find Run Cell | Run Above | Debug Cell too..

A: As a possible hack, you can extend the cell commands.
The setting for that is called "Jupyter: Code Lenses".
I set mine to:
"jupyter.runcell, jupyter.runallcellsabove, jupyter.debugcell,
 jupyter.debugcell, jupyter.debugcell, jupyter.debugcell,
 jupyter.debugcell, jupyter.debugcell, jupyter.debugcell,
 jupyter.debugcell, jupyter.debugcell, jupyter.debugcell"

long cell command list to mimic a cell border

A: Jupyter is a good choice for you which has separate code cells.
Create jupyter notebook from command palette then install required module ipykernal, you can run python code cell in it. Reference: Jupyter Notebook in VS Code.


text:
Q: snmptt not translating traps, even with translate_log_trap_oid=1 I am having some trouble configuring snmptt to properly translate snmp traps.
The following is a problem:
/etc/snmp/snmptt.conf reflects:
EVENT fgFmTrapIfChange .1.3.6.1.4.1.12356.101.6.0.1004 "Status Events" Critical
FORMAT $*
EXEC /usr/local/nagios/libexec/eventhandlers/submit_check_result $r "snmp_traps" 2 "$O: $+*" "$*"
SDESC

Trap is sent to the managing FortiManager if an interface IP is changed
Variables:
  1: fnSysSerial
  2: ifName
  3: fgManIfIp
  4: fgManIfMask
EDESC

when a trap is received, /var/log/messages reflects:
Sep  6 12:07:32 SNMPMANAGERHOST snmptrapd[15385]:
2012-09-06 12:07:32 <UNKNOWN>
[UDP:
[192.168.100.2]:162->[192.168.100.31]]:
#012.1.3.6.1.2.1.1.3.0 = Timeticks: (707253943) 81 days, 20:35:39.43
#011.1.3.6.1.6.3.1.1.4.1.0 = OID: .1.3.6.1.4.1.12356.101.6.0.1004
#011.1.3.6.1.4.1.12356.100.1.1.1.0 = STRING: FGTNNNNNNNNN
#011.1.3.6.1.2.1.31.1.1.1.1.10 = STRING: internal4
#011.1.3.6.1.4.1.12356.101.6.2.1.0 = IpAddress: 192.168.65.100
#011.1.3.6.1.4.1.12356.101.6.2.2.0 = IpAddress: 255.255.255.0

Sep  6 12:07:37 SNMPMANAGERHOST icinga:
EXTERNAL COMMAND:
PROCESS_SERVICE_CHECK_RESULT;
192.168.100.2;
snmp_traps;
2;
enterprises.12356.101.6.0.1004: enterprises.12356.100.1.1.1.0:FGTNNNNNNNNN ifName.10:internal4 enterprises.12356.101.6.2.1.0:192.168.65.100 enterprises.12356.101.6.2.2.0:255.255.255.0

Since the icinga entry reflects the EXEC, it's obvious there is no translations occurring by snmptt.
I have verified that translate_log_trap_oid and net_snmp_perl_enable is enabled in snmptt.ini
When using --debug=1 to start snmptt, I see the following in the --debugfile:
********** Net-SNMP version 5.05 Perl module enabled **********

The main NET-SNMP version is reported as NET-SNMP version: 5.5.
What else can be done to verify that snmptt is configured properly to translate traps?
I have run snmptt-net-snmp-test to verify whatever net-snmp-perl version I have installed properly supports translations.  The output indicates it does.
/root/snmptt_1.3/snmptt-net-snmp-test --best_guess=2

SNMPTT Net-SNMP Test v1.0
(c) 2003 Alex Burger
http://snmptt.sourceforge.net

MIBS:RFC1213-MIB
best_guess: 2

Testing translateObj
********************

Testing: .1.3.6.1.2.1.1.1, long_names=disabled, include_module=disabled
Test passed.  Result: sysDescr

Testing: .1.3.6.1.2.1.1.1, long_names=disabled, include_module=enabled
Test passed.  Result: RFC1213-MIB::sysDescr

Testing: .1.3.6.1.2.1.1.1, long_names=enabled, include_module=disabled
Test passed.  Result: .iso.org.dod.internet.mgmt.mib-2.system.sysDescr

Testing: .1.3.6.1.2.1.1.1, long_names=enabled, include_module=enabled
Test passed.  Result: RFC1213-MIB::.iso.org.dod.internet.mgmt.mib-2.system.sysDescr

Testing: sysDescr, long_names=disabled, include_module=disabled
Test passed.  Result: .1.3.6.1.2.1.1.1

Testing: RFC1213-MIB::sysDescr, long_names=disabled, include_module=disabled
Test passed.  Result: .1.3.6.1.2.1.1.1

Testing: system.sysDescr, long_names=disabled, include_module=disabled
Test passed.  Result: .1.3.6.1.2.1.1.1

Testing: RFC1213-MIB::system.sysDescr, long_names=disabled, include_module=disabled
Test passed.  Result: .1.3.6.1.2.1.1.1

Testing: .iso.org.dod.internet.mgmt.mib-2.system.sysDescr, long_names=disabled, include_module=disabled
Test passed.  Result: .1.3.6.1.2.1.1.1

Testing getType
***************

Testing: .1.3.6.1.2.1.4.1
Test passed.  Result: INTEGER

Testing: ipForwarding
Test passed.  Result: INTEGER

Testing Description
*******************
Test passed.  Result:
-------------------------------------------------
The indication of whether this entity is acting
as an IP gateway in respect to the forwarding of
datagrams received by, but not addressed to, this
entity.  IP gateways forward datagrams.  IP hosts
do not (except those source-routed via the host).
Note that for some managed nodes, this object may
take on only a subset of the values possible.
Accordingly, it is appropriate for an agent to
return a `badValue' response if a management
station attempts to change this object to an
inappropriate value.
-------------------------------------------------

I have manually gone through the MIB with the definition that's not resolving, and verified that it is properly linking back to the proper resolved definition.  It is:
FORTINET-FORTIGATE-MIB.txt contains:

fgFmTrapIfChange NOTIFICATION-TYPE
    OBJECTS     { fnSysSerial, ifName, fgManIfIp, fgManIfMask }
    STATUS      current
    DESCRIPTION
        "Trap is sent to the managing FortiManager if an interface IP is changed"
    ::= { fgFmTrapPrefix 1004 }

fgFmTrapPrefix OBJECT IDENTIFIER
    ::= { fgMgmt 0 }

fgMgmt OBJECT IDENTIFIER
    ::= { fnFortiGateMib 6 }

fnFortiGateMib
    ::= { fortinet 101 }

IMPORTS
    FnBoolState, FnIndex, fnAdminEntry, fnSysSerial, fortinet
        FROM FORTINET-CORE-MIB

fortinet MODULE-IDENTITY
    ::= { enterprises 12356 }

LOOKS GOOD!!!!!
1.3.6.1.4.1.12356.101.6.0.1004

I've exhausted all the documentation and even posted fruitlessly in the snmptt-users mailing list.
I can not prove it is the MIB.
Why would snmptt fail to translate traps?
Simply:

*

*$O = enterprises.12356.101.6.0.1004

*when $O should = fgFmTrapIfChange

Thanks,
Matt
[UPDATE]
snmptt.ini
snmptrapd.conf:
authCommunity log,execute,net communitystr
traphandle default /usr/bin/snmptthandler

snmptt.conf
MIB where trap that isn't being translated lives (and it's referenced MIB).
Note that linkUp and linkDown are translating properly.
[UPDATE 2]
I have also tested with another MIB that isn't a default MIB contained within the net-snmp package, and this MIB also fails to resolve.
[UPDATE 3]
If I set the following in snmptt.ini:
mode = standalone
And I set the following in snmptrapd.conf:
traphandle  default /usr/sbin/snmptt --ini=/etc/snmp/snmptt.ini
I am able to translate traps as expected.
This means that whatever method /usr/sbin/snmptt uses to daemonize may not have access to the MIBs, or may be doing something other than what's described.  The documentation included within snmptt.ini likely will contain the answers I seek.
[[ SOLUTION ]]
Set mibs_environment = ALL in snmptt.ini
Description:
# Allows you to set the MIBS environment variable used by SNMPTT
# Leave blank or comment out to have the systems enviroment settings used
# To have all MIBS processed, set to ALL
# See the snmp.conf manual page for more info.

mibs_environment = ALL must be set in snmptt.ini even with snmptrapd starting with -m ALL (where ALL is a wild card statement that includes all MIBs [defined within the files]).
\o.

A: I posted this in the chat window awhile back, but it looks like you may have left it.  Your snmptt.ini file has the following translation options set :
translate_log_trap_oid = 1
translate_value_oids = 1
translate_enterprise_oid_format = 1
translate_trap_oid_format = 0
translate_varname_oid_format = 0
translate_integers = 1

The interesting one is the 'translate_trap_oid_format' which affects the value of $O.  Valid values are 0 - 4, with 0 turning off translation, the rest are listed in snmptt.ini --
Set to 0 to disable translating OID values to text (symbolic form)
Set to 1 to translate OID values to short text (symbolic form) (eg: BuildingAlarm)
Set to 2 to translate OID values to short text with module name (eg: UPS-MIB::BuildingAlarm)
Set to 3 to translate OID values to long text (eg: iso...upsAlarm.BuildingAlarm)
Set to 4 to translate OID values to long text with module name (eg:UPS-MIB::iso...upsAlarm.BuildingAlarm)


text:
Q: Any way to check count of template parameters at compile time? Is there any way to check number of template parameters and compile time? I would like to do this (this is not real code):
template<typename... Types>
class Foo
{
    // Enable this if count of 'Types' is 1.
    Types[0] Bar()
    {
        return Types[0]{};
    }

    // Enable this otherwise.
    std::variant<Types> Bar()
    {
        return std::variant<Types>{};
    }

};

Is there any way to achieve this?

A: Not like that, at least not easily. You can probably add some helper struct that defines a type with if constexpr and sizeof...() and then use helper::return_type or seomthing.
But I think this calls for template specialization:
#include <variant>

template<typename... Types>
class Foo
{
    std::variant<Types...> Bar()
    {
        return {};
    }

};

// Specialize for just one Type
template<typename Type>
class Foo<Type>
{
    Type Bar()
    {
        return {};
    }
};

A: One option is to add a template parameter and then leverage constexpr if to check if the pack is empty or not like
template<typename first_t, typename... rest_t>
class Foo
{
    auto Bar()
    {
        if constexpr (sizeof...(rest_t) == 0)
            return first_t{};
        else
            return std::variant<first_t, rest_t...>{};
    }
};

A: It's not too hard to create a alias template for the type by specializing a helper type:
template<class...Ts>
struct ReturnTypeHelper : std::type_identity<std::variant<Ts...>> {};

template<class T>
struct ReturnTypeHelper<T> : std::type_identity<T> {};

template<class...Ts>
using ReturnType = typename ReturnTypeHelper<Ts...>::type;

template<typename... Types>
class Foo
{
public:
    auto Bar()
    {
        return ReturnType<Types...>{};
    }
};

static_assert(std::is_same_v<decltype(std::declval<Foo<int>>().Bar()), int>);
static_assert(std::is_same_v<decltype(std::declval<Foo<int,float>>().Bar()), std::variant<int, float>>);


text:
Q: Symfony : How to sort ArrayCollection in a OneToMany relation (3 entities)? I have a product which can has one or many tags.
For a particular reason, I have 3 entities which correspond to :

*

*Product

*Tag

*ProductTag (relation) :

I want to order by type my ArrayCollection of tags. This collection contains ProductTag entities.
The difficulty is that I haven't a type property in ProductType, this property is in Tag entity.
Product
/**
 * @ORM\OneToMany(targetEntity="ProductTag", mappedBy="product", cascade={"persist", "remove"})
 * @Assert\Valid
 */
private $tags;

Tag
/**
 * @ORM\Column(type="string", length=15)
 */
private $type;

ProductTag
/**
 * @ORM\Column(name="Product_id", type="integer")
 * @ORM\Id
 */
private $product_id;

/**
 * @ORM\Column(name="Tag_id", type="integer")
 * @ORM\Id
 */
private $tag_id;

/**
 * @ORM\ManyToOne(targetEntity="Product", inversedBy="tags")
 * @ORM\JoinColumn(name="Product_id", referencedColumnName="Product_id")
 */
private $product;

/**
 * @ORM\ManyToOne(targetEntity="Tag")
 * @ORM\JoinColumn(name="Tag_id", referencedColumnName="Tag_id")
 */
private $tag;

The solution below can't work because ProductTag hasn't a type property :
// Product entity

/**
 * @ORM\OneToMany(targetEntity="ProductTag", mappedBy="product", cascade={"persist", "remove"})
 * @ORM\OrderBy({"type" = "ASC"})
 * @Assert\Valid
 */
private $tags;

I would like to do something like this @ORM\OrderBy({"tag.type" = "ASC"}).
Any idea ?
Thanks.
--- EDIT ---
In PhpMyAdmin, I created a view which gets the data of tags and the product id for each tags.
Then, in Symfony, I created an entity that corresponds to my view.
In the Repository of this entity, I created a query that concats my tags by their type.
public function findByProductGroupByType($productId)
{
   return $this->getEntityManager()
        ->createQuery(
            'SELECT v.tagTypeCode, v.tagType,
                GROUP_CONCAT(v.tagCode) as tagCode,
                GROUP_CONCAT(v.tagName) as tagName,
                GROUP_CONCAT(v.picto) as tagPicto
                FROM AppBundle:ProductTagView v
                WHERE v.productId = :id
                GROUP BY v.tagTypeCode
                ORDER BY v.tagType ASC'
        )->setParameter('id', $productId)
        ->getResult();
}

So that it works, it is necessary to install this bundle so that Symfony recognizes GROUP_CONCAT. After installation, add this in config.yml :
doctrine:
    orm:
        dql:
            string_functions:
                group_concat: DoctrineExtensions\Query\Mysql\GroupConcat

The complete list is here : https://github.com/beberlei/DoctrineExtensions/blob/master/config/mysql.yml
The query returns something like this :
array (size=2)
  0 =>
    array (size=5)
      'tagTypeCode' => string 'KFEAT' (length=5)
      'tagType' => string 'Key Feature' (length=11)
      'tagCode' => string 'double_sanglage' (length=15)
      'tagName' => string 'double sanglage' (length=15)
      'tagPicto' => string 'double_sanglage.jpg' (length=19)
  1 =>
    array (size=5)
      'tagTypeCode' => string 'SIZE' (length=4)
      'tagType' => string 'Size' (length=4)
      'tagCode' => string 'h26_ceintures,h21_ceintures' (length=27)
      'tagName  => string 'ceintures h26cm,ceintures H21 cm' (length=32)
      'tagPicto' => string 'h26_ceintures.jpg,h21_ceintures.jpg' (length=35)

The tags of type SIZE are concatenated with , separator.

A: You can't do it directly. But there is a workaround.

*

*Add a ordered tags property to you Product entity :
private $orderedTags;

public function __construct()
{
    //...
    $this->orderedTags = new \Doctrine\Common\Collections\ArrayCollection();
}

*Create a new doctrine Event Listener and register in in services.yml
services:
    my.listener:
        class: AppBundle\EventListener\OrderedTagsListener
        arguments: ["@doctrine.orm.entity_manager"]
        tags:
            - { name: doctrine.event_listener, event: postLoad }

// src/AppBundle/EventListener/OrderedTagsListener.php
namespace AppBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use AppBundle\Entity\Product;

class OrderedTagsListener
{
    private $em;

    public function __construct($em)
    {
        $this->em = $em;
    }

    public function postPersist(LifecycleEventArgs $args)
    {
        $product = $args->getEntity();

        // Retrieve your tags ordered with a query defined in your tags repository
        $orderedTags = $this->em->getManager()->getRepository('AppBundle:Tags')->getOrderedTags($product);

        $product->setOrderedTags();
    }
}


text:
Q: Wifi not working on fresh ubuntu installation on new computer I got the new HP all-in-one desktop with no OS. Installed latest Ubuntu. During installation it asked about wifi connection details which i provided. After restart, booting first time, i fond the wifi connection established but internet not working. Please suggest / help.

A: Internet connection maybe something different from wifi connection . If you can connect to your wireless access point it means you don't have any trouble with you NIC .
For troubleshoot this problem you may provide more detail about your Routing table and DNS configuration .
For getting know about these detail , try :
 $ ip a

which show your run time networking status . Check If your connection has IP and CIDR ( /x ) is as same as your network ( Some issue for some routers ) .
 $ ip route show

This will show you routing tables . Check default parameter is set correctly and also is same as UG flag in following command route -n .
After these you can try to checking your DNS configuration . Check /etc/resolv.conf if Network manager wrote right nameserver . Also check /etc/hosts to check if there is any mistyping . Also check /etc/nsswitch for getting know about which DNS configuration read first .
In any steps if you want to do any changes do not edit it by hands . Network manager has great utility for managing them nmcli .
Try to make new profile :
 $ nmcli connection add type ethernet ifname wlp18s0 con-name ali save yes

Then modify your connection :
$ nmcli connection modify ali ipv4.address 1.2.3.4/24

And you can find out more options to edit profile when you enter ipv4. press TAB .


text:
Q: Execute query on multiple sqlite databases in C# I have more than 400 sqlite databases. I need to query on these databases. Like simple SELECT..... query to get results.
I don't know weather it is possible within single query.
Current logic is.
foreach(FileInfo finf in Files)
{
    // query one database get result
    Datatable results = execute();
    // merge Datatable with new one.
}

at the end we get all database results in single datatable.
Is anyone having better solution for querying multiple databases?
Thanks in advance.

A: In order to get a single result set with SQLite you have to join all the databases by the ATTACH command giving to each one a different alias, then build a sql statement which group the data into a single result set by the SELECT ... UNION command.
For example:
 - ATTACH DATABASE 'Database1' As 'DB1';
 - ATTACH DATABASE 'Database2' As 'DB2';

Then :
SELECT * FROM DB1.MyTable

UNION

SELECT * FROM DB2.MyTable


text:
Q: How to build a scala application that was created in eclipse scala plugin FROM THE CL I have developed a scala application for the first time, but I have to deploy it with a "one-click" type script that can run and build the scala application from source WITHOUT ECLIPSE.
Since I'm completely new to scala I don't know how to tell it where all my source files are etc... to get it to build my app from the command line.  I also have 2 3rd party .jar libraries that I need to tell the scala compiler to link to...
Any documentation on this?  Or example command lines?   My project hierarchy is:

*

*src/packagename: contains all .scala

*bin/packagename: contains all.class files

*libs/ -> contains 2 .jar files I will need to import somehow

I'm working on debian linux
EDIT: I found this ability to export in eclipse so I created a .java file and called my main scala object from it.  Then I exported as a runnable jar.  However, when I go to run the new runnable jar "sudo java runnable.jar" it says "class not found exception: runnable.jar"

A: You should take a look at https://github.com/harrah/xsbt/wiki which is the common way to build a Scala project. Run through the tutorial in the wiki to learn how you should organise your directory structure, so that everything may run fine.
If you want to combine it with eclipse, checkout this plugin: https://github.com/typesafehub/sbteclipse


text:
Q: R: Separate data of an hts object I've being playing with the hts package in order to forecast some products that are linked through different categories, it's a typical case where the data is something like:
Business Units (BU) => Category => Sub-Category => SKU

So far I've been able to create the hts object according to the needed hierarchy and also run some forecasts for all the aggregated data.
Since there are different BU's I want to run a different model for each BU, and also analyse the data for each BU separately. I know I can make an hts object for each BU and then use combinef to aggregate all the forecasts but I was wondering if it was possible to do it with just one hts object and some modified GmatrixH function.
To make it more graphically, lets assume I have something like this in my initial hts data:
=> A
  => A20
    => A201
    => A202
  => A30
    => A301
    => A302
=> B
  => B10
    => B101
    => B102
  => B20
    => B201
    => B202

My goal is to able to separate the data to just something like this:
=> A
  => A20
    => A201
    => A202
  => A30
    => A301
    => A302

Example code: Rather than use a different data set lets assume that htseg2 is the data, so, looking at the aggts of htseg2 we see:
all_y <- aggts(htseg2)
Time Series:
Start = 1992
End = 2007
Frequency = 1
          Total         A        B       A10        A20       B30      B40      A10A       A10B       A10C       A20A        A20B        B30A      B30B      B40A
1992 -2.2112904 -5.103778 2.892488 -4.344453 -0.7593252 0.8077966 2.084691 -2.423474 -1.1620698 -0.7589091 -0.4983286 -0.26099657 0.009695794 0.3270945 0.4710063
1993 -1.7426751 -4.850060 3.107385 -4.103407 -0.7466530 0.8326560 2.274729 -2.196065 -1.1576038 -0.7497389 -0.4979251 -0.24872791 0.022737218 0.3358589 0.4740598
1994 -1.4533386 -4.688907 3.235569 -3.960646 -0.7282608 0.9080350 2.327534 -2.187683 -1.0524048 -0.7205582 -0.4954755 -0.23278530 0.064194769 0.3367939 0.5070464
1995 -1.0151533 -4.386465 3.371312 -3.695228 -0.6912372 0.9728715 2.398440 -1.932308 -1.0519018 -0.7110175 -0.4818329 -0.20940428 0.098071735 0.3611585 0.5136413
1996 -0.2687558 -3.947446 3.678690 -3.331862 -0.6155842 1.0763970 2.602293 -1.637783 -1.0139068 -0.6801723 -0.4253173 -0.19026691 0.146079487 0.3738506 0.5564668
1997 -0.1039130 -3.891031 3.787118 -3.284696 -0.6063356 1.1220049 2.665113 -1.627386 -0.9823162 -0.6749934 -0.4247379 -0.18159770 0.170240635 0.3890064 0.5627578
1998  0.0319309 -3.815398 3.847329 -3.219069 -0.5963289 1.1310482 2.716281 -1.614443 -0.9486647 -0.6559620 -0.4150329 -0.18129604 0.173920725 0.3916081 0.5655194
1999  0.2386283 -3.689795 3.928423 -3.125673 -0.5641226 1.1638044 2.764619 -1.590909 -0.8935917 -0.6411720 -0.3924141 -0.17170855 0.205094593 0.3931835 0.5655263
2000  0.4762250 -3.580883 4.057108 -3.036069 -0.5448139 1.2111129 2.845995 -1.532260 -0.8687816 -0.6350273 -0.3785346 -0.16627934 0.235250213 0.4085820 0.5672806
2001  0.7640473 -3.373380 4.137427 -2.877374 -0.4960051 1.2474490 2.889978 -1.390682 -0.8537141 -0.6329781 -0.3748754 -0.12112965 0.241523003 0.4140894 0.5918366
2002  0.9577465 -3.321418 4.279164 -2.836797 -0.4846210 1.2635735 3.015591 -1.367034 -0.8388968 -0.6308661 -0.3713899 -0.11323106 0.253885861 0.4170116 0.5926760
2003  1.1278373 -3.244452 4.372290 -2.786883 -0.4575690 1.3112792 3.061011 -1.334805 -0.8283677 -0.6237109 -0.3536588 -0.10391014 0.279924841 0.4247898 0.6065645
2004  1.3618556 -3.130861 4.492716 -2.715788 -0.4150729 1.3568514 3.135865 -1.318941 -0.8255442 -0.5713028 -0.3182323 -0.09684063 0.283730794 0.4450246 0.6280960
2005  1.7552645 -2.991873 4.747138 -2.615245 -0.3766279 1.3736268 3.373511 -1.242796 -0.8054984 -0.5669504 -0.3044265 -0.07220149 0.288582178 0.4568084 0.6282362
2006  2.0580599 -2.936933 4.994993 -2.582444 -0.3544895 1.4013893 3.593604 -1.240751 -0.7970741 -0.5446189 -0.3015478 -0.05294174 0.296206517 0.4598029 0.6453799
2007  2.3738339 -2.836078 5.209912 -2.511904 -0.3241741 1.4523193 3.757593 -1.220774 -0.7866848 -0.5044450 -0.2963444 -0.02782969 0.317670953 0.4671018 0.6675465
          B40B     B40C
1992 0.6941430 1.390548
1993 0.7440005 1.530729
1994 0.7800831 1.547451
1995 0.8195736 1.578866
1996 0.8798774 1.722416
1997 0.9265925 1.738521
1998 0.9710759 1.745205
1999 1.0151125 1.749507
2000 1.0558906 1.790104
2001 1.0990149 1.790963
2002 1.2131865 1.802404
2003 1.2471263 1.813884
2004 1.3140384 1.821827
2005 1.3778140 1.995697
2006 1.3785545 2.215049
2007 1.3875096 2.370083

If I do:
all_y_lA <- aggts(htseg2, levels=1)

I get:
Time Series:
Start = 1992
End = 2007
Frequency = 1
             A        B
1992 -5.103778 2.892488
1993 -4.850060 3.107385
1994 -4.688907 3.235569
1995 -4.386465 3.371312
1996 -3.947446 3.678690
1997 -3.891031 3.787118
1998 -3.815398 3.847329
1999 -3.689795 3.928423
2000 -3.580883 4.057108
2001 -3.373380 4.137427
2002 -3.321418 4.279164
2003 -3.244452 4.372290
2004 -3.130861 4.492716
2005 -2.991873 4.747138
2006 -2.936933 4.994993
2007 -2.836078 5.209912

And what I want is to do something like:
all_y_lA <- aggts(htseg2, levels="A")

And get:
              A        A10         A20         A10A        A10B        A10C       A20A         A20B
1992    -5.103778   -4.344453   -0.7593252  -2.423474   -1.1620698  -0.7589091  -0.4983286  -0.26099657
1993    -4.85006    -4.103407   -0.746653   -2.196065   -1.1576038  -0.7497389  -0.4979251  -0.24872791
1994    -4.688907   -3.960646   -0.7282608  -2.187683   -1.0524048  -0.7205582  -0.4954755  -0.2327853
1995    -4.386465   -3.695228   -0.6912372  -1.932308   -1.0519018  -0.7110175  -0.4818329  -0.20940428
1996    -3.947446   -3.331862   -0.6155842  -1.637783   -1.0139068  -0.6801723  -0.4253173  -0.19026691
1997    -3.891031   -3.284696   -0.6063356  -1.627386   -0.9823162  -0.6749934  -0.4247379  -0.1815977
1998    -3.815398   -3.219069   -0.5963289  -1.614443   -0.9486647  -0.655962   -0.4150329  -0.18129604
1999    -3.689795   -3.125673   -0.5641226  -1.590909   -0.8935917  -0.641172   -0.3924141  -0.17170855
2000    -3.580883   -3.036069   -0.5448139  -1.53226    -0.8687816  -0.6350273  -0.3785346  -0.16627934
2001    -3.37338    -2.877374   -0.4960051  -1.390682   -0.8537141  -0.6329781  -0.3748754  -0.12112965
2002    -3.321418   -2.836797   -0.484621   -1.367034   -0.8388968  -0.6308661  -0.3713899  -0.11323106
2003    -3.244452   -2.786883   -0.457569   -1.334805   -0.8283677  -0.6237109  -0.3536588  -0.10391014
2004    -3.130861   -2.715788   -0.4150729  -1.318941   -0.8255442  -0.5713028  -0.3182323  -0.09684063
2005    -2.991873   -2.615245   -0.3766279  -1.242796   -0.8054984  -0.5669504  -0.3044265  -0.07220149
2006    -2.936933   -2.582444   -0.3544895  -1.240751   -0.7970741  -0.5446189  -0.3015478  -0.05294174
2007    -2.836078   -2.511904   -0.3241741  -1.220774   -0.7866848  -0.504445   -0.2963444  -0.02782969

Then analyse and forecast A and all childs of A, and then the same for B.
Hope I make myself clear, thanks in advance for any help.


text:
Q: neo4j ogm different save policies Is there a possibility to change save policy.
For example I have node Person with properties name=A, surname and address.
Now I want to save object Person with same Entity Id, and with property name=B.
Can i choose somehow:

*

*to only override that name property and leave surname and address.

*to delete surname and address and only insert name=b.

A: No, these policies do not exist in the OGM. When you save a node entity, the OGM will detect if any properties have changed, and update all properties. If you've only updated the name to B, but left the surname and address as before, then the effect of save is to update the name to B.
If you update name to B but set surname and address to null, then the effect of save is to update the name to B, and remove the values of surname and address.


text:
Q: DynamoDb not able to save map data(java) I am trying to save data into the dynamoDb but that data contains some Map attributes as well.But I am getting error while saving that data. Following is my domain class which I am using for  saving data from request:
@DynamoDBTable(tableName = "ottMiddleware_rails")
public class RailsCmsDomain {

@DynamoDBHashKey(attributeName = "railId")
private String railId;

@DynamoDBTyped
@DynamoDBAttribute(attributeName = "railLogic")
private Map<String, Object> railLogic;

@DynamoDBAttribute(attributeName = "railSourceType")
private String railSourceType;

@DynamoDBAttribute(attributeName = "railTitle")
private RailCmsTitleDomain railTitle;

@DynamoDBTyped
@DynamoDBAttribute(attributeName = "restrictions")
private Map<String, Object> restrictions;

I am giving the following request:
{
    "railId": "railOne",
    "railLogic": {
        "programType": 1,
        "railSourceUrl": "http://myUrl"
    },
    "railSourceType": "myRail",
    "railTitle": {
        "tam": "Raan Phan",
        "def": "சிறப்பு கட்டமைப்பு"
    },
    "restrictions": {
        "clients": [
            "abc",
            "xyz"
        ],
        "periodStart": 1506572217
    }
}

I am using following code to save my data into the dynamoDb
public Boolean saveUpdateRailsDetails(RailsCmsDomain railsDomain) {
    DynamoDBUtil dynamoDBUtil = new DynamoDBUtil();
    AmazonDynamoDB dynamoDBClient = dynamoDBUtil.getDynamoDBClient();
    DynamoDBMapper mapper = new DynamoDBMapper(dynamoDBClient);
    mapper.save(railsDomain);
    return true;
}

Please suggest how can I save map into dynamoDb. I am taking data as map because in later stages there are chances more data can be added to those attributes which are map and that data can be of any data type. I am getting following error:
errorMessage": "not supported; requires @DynamoDBTyped or
@DynamoDBTypeConverted"
"errorType":
"com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException"

A: I would like to post this answer as an option though it is not going to store the data as map in DynamoDB. However, it will resolve the error.
You can define the restrictions attribute as mentioned below. It will store the data as JSON string in DynamoDB.
@DynamoDBTypeConvertedJson
private Map<String, Object> restrictions;

Drawbacks:-
When you would like to update the restrictions attribute, you need to get the current value from database, update it and save the data in database.
DynamoDB data:-
restrictions attribute saved as JSON string.

A: When I needed to store map in dynamodb I just annotated the getter method of the map with @DynamoDBTypeConverted(converter = MapConverter.class) and in the converter just serialized the map into a json string, this way you can retrieve the map and everything but are not going to be able to use it in queryExpressions if you need.
So in case you want to be able to query the objects in the map maybe consider annotating the object you are using in your map with @DynamoDBDocument this way it's going to be automatically serialized by dynamodb as a document and use Set instead of map into your parent object.

A: The problem is that the DynamoDB Mapper doesn't know how to marshall/unmarshall the Object in this line:
private Map<String, Object> railLogic;

If you don't want to change Object to String, then use the DynamoDBTypeConverted annotation to provide a custom marshaller for Map<String, Object> which you can then (probably) reuse for restrictions. Relevant documentation here.


text:
Q: How can I parallelize multiple instances of the same Selenium suite using Junit? I have a Junit test suite that I am using to run a series of selenium tests.  I need to run these tests on several platforms (browser/OS combos, mobile devices).  Is there a way for me to run the suite in parallel with 4 other instances of the same suite (5 total), each with different config settings (settings for the RemoteWebDriver).
Should I us a parallelized runner (I've seen a few options) on each test within the suite or parallelize the suite itself?
Also, is there a way to run a sequence of these parallel runs? (i.e. 5 parallel runs followed by another 5 parallel runs, etc.)

A: You want to use Selenium Grid for this.
To run tests in parallel with JUnit4, you will also need Maven.

A: Remember that Selenium grid does not provide the parallel distribution of your tests, it is simply a way to allow multiple threads hit the same endpoint to support parallel testing.
You still need a mechanism to support the parallel distribution of your tests.
I know this can be achieved with JUnit, but in my experience it is easier with TestNG


text:
Q: Dynamically (generic) inherit from  in swift I didn't find any solution for that and there's a good chance that it's not possible but I'll give it a try (if it's not possible I'd be very happy to get a small explanation why).
I'm trying to create a class in Swift, let's call it Foo, and I want FooChild to inherit from Foo. So far, no problems. The thing is, I want Foo to dynamically inherit "any class", maybe by generic type.
Something like
class Foo<T> : <T>{

}

class FooChild : Foo<NSObject> {

}

class FooChild2 : Foo<UIview> {

}

I want both FooChild and FooChild2 inherit from Foo, but I want foo to inherit once from NSObject, and once from UIView (used random classes for the example).
Is that possible? Even in Objective-C code that I'll bridge somehow.

A: Swift 1.2
No, that is not possible.
What you can do is something like:
protocol Foo { }

class FooChild1: NSObject, Foo { }

class FooChild2: UIView, Foo { }

Swift 2
Yes, now this is possible.

Non-generic classes may inherit from generic classes. (15520519)

See: Xcode 7 Beta Release Notes, chapter "New in Swift 2.0 and Objective-C", section "Swift Language Features"
E.g. the following is possible:
import UIKit

class Foo<T> { }

class FooChild: Foo<NSObject> { }

class FooChild2: Foo<UIView> { }

let fooChild = FooChild()

let fooChild2 = FooChild2()

Also, in Swift 2 if you need protocol Foo from Swift 1.2 example to provide some default behaviour, you can use default protocol implementations.

You can use protocol extensions to provide a default implementation to any method or property requirement of that protocol. If a conforming type provides its own implementation of a required method or property, that implementation will be used instead of the one provided by the extension.

See: The Swift Programming Language, Chapter "Protocols", Section "Providing Default Implementations"


text:
Q: Inheritance and std::shared_ptr in Cython Suppose I have the following simple example of C++ inheritance in file.h:
class Base {};
class Derived : public Base {};

Then, the following code compiles; that is, I can assign std::shared_ptr<Derived> to std::shared_ptr<Base>:
Derived* foo = new Derived();
std::shared_ptr<Derived> shared_foo = std::make_shared<Derived>(*foo);
std::shared_ptr<Base> bar = shared_foo;

Let's also say I've added the types to a decl.pxd:
cdef extern from "file.h":
    cdef cppclass Base:
        pass
    cdef cppclass Derived(Base):
        pass

Then, what I'm trying to do is mimic the above C++ assignment in Cython in a file.pyx:
cimport decl
from libcpp.memory cimport make_shared, shared_ptr

def do_stuff():
    cdef decl.Derived* foo = new decl.Derived()
    cdef shared_ptr[decl.Derived] shared_foo = make_shared[decl.Derived](foo)
    cdef shared_ptr[decl.Base] bar = shared_foo

Unlike the C++ case, this now fails with the following error (using Cython 3.0a6):
cdef shared_ptr[decl.Base] bar = shared_foo
                                ^
---------------------------------------------------------------

 Cannot assign type 'shared_ptr[Derived]' to 'shared_ptr[Base]'

Should I expect this behavior? Is there any way to mimic what the C++ examples does with Cython?
Edit: Cf. the comments to the accepted answer below, the relevant functionality has been added to Cython and is available as of version 3.0a7.

A: It should work for Cython>=3.0 as @fuglede made this PR fixing the issue described below (which is still present for Cython<3.0).

The issue is, that the the wrapper of std::shared_ptr misses
template <class U> shared_ptr& operator= (const shared_ptr<U>& x) noexcept;

of the std::shared_ptr-class.
If you patch the wrapper like that:
cdef extern from "<memory>" namespace "std" nogil:
cdef cppclass shared_ptr[T]:
    ...
    shared_ptr[T]& operator=[Y](const shared_ptr[Y]& ptr)
    #shared_ptr[Y](shared_ptr[Y]&)  isn't accepted

your code will compile.
You might ask, why operator= and not constructor shared_ptr[Y] is needed, because:
...
cdef shared_ptr[decl.Base] bar = shared_foo

looks like constructor (template <class U> shared_ptr (const shared_ptr<U>& x) noexcept;) is not explicit. But it is one of Cython's quirks with C++. The above code will be translated to
std::shared_ptr<Base> __pyx_v_bar;
...
__pyx_v_bar = __pyx_v_shared_foo;

and not
std::shared_ptr<Base> __pyx_v_bar = __pyx_v_shared_foo;

thus Cython will check the existence of operator= (lucky for us, because Cython seems not to support constructor with templates, but does so for operators).

If you want to distribute your module also on systems without patched memory.pxd you have two option:

*

*to wrap std::shared_ptr correctly by yourself

*write a small utility function, for example

%%cython
...
cdef extern from *:
    """
    template<typename T1, typename T2>
    void assign_shared_ptr(std::shared_ptr<T1>& lhs, const std::shared_ptr<T2>& rhs){
         lhs = rhs;
    }
    """
    void assign_shared_ptr[T1, T2](shared_ptr[T1]& lhs, shared_ptr[T2]& rhs)

...
cdef shared_ptr[Derived] shared_foo
# cdef shared_ptr[decl.Base] bar = shared_foo
# must be replaced through:
cdef shared_ptr[Base] bar
assign_shared_ptr(bar, shared_foo)
...

Both options have drawbacks, so depending on your scenario you might prefer one or another.

A: I have not tried Cyton, but std::shared_ptr has an static cast function std::static_pointer_cast. I think this will work
std::shared_ptr<Base> bar = std::static_pointer_cast<Base>(shared_foo);

.
def do_stuff():
    cdef decl.Derived* foo = new decl.Derived()
    cdef shared_ptr[decl.Derived] shared_foo = make_shared[decl.Derived](foo)
    cdef shared_ptr[decl.Base] bar = static_pointer_cast[decl.Base] shared_foo

As a side note
The way you create shared_foo is probably not what you want. Here you are first creating a dynamically allocated Derived. Then you are creating a new dynamically allocated shared derived that is a copy of the original.
// this allocates one Derived
Derived* foo = new Derived();
// This allocates a new copy, it does not take ownership of foo
std::shared_ptr<Derived> shared_foo = std::make_shared<Derived>(*foo);

What you probably want is either:
Derived* foo = new Derived();
std::shared_ptr<Derived> shared_foo(foo); // This now takes ownership of foo

Or just:
// This makes a default constructed shared Derived
auto shared_foo = std::make_shared<Derived>();


text:
Q: Updating large document in collection causes client to freeze for 6-8 seconds I have a relatively large document in a collection; the document is an object with ~2000 elements, each of which is itself a small object. When I update the document on the server, the client locks up for 6-8 seconds.
I've put in logging that tells me when the server has finished updating the collection, then there is the 6-8 second freeze, and the next thing which happens is that observeChanges runs in the client and everything starts running again.

*

*I've put in a timeout in the client that logs to the console every 100ms. It stops firing during the delay, so I think none of my client-side javascript is running.

*The delay seems to match the initial load time of the document (I've tried different size documents).

*I'm using Iron Router. I've put logging into the data, waitOn and action functions: they are not firing until after the delay. So I don't think the router is the problem.

*The function that updates the collection is only running on the server, so it's not slow client-side emulation.

*It's not the rendering: if I trigger the update client-side only, the page re-renders fast.

*I've checked pretty carefully and I don't think any of my client code is requesting that document, the only find() for it runs at startup, and it's not the autorun.

*I've put logging into my publish function: the collection isn't being republished. I'm not running autopublish.
Any thoughts what might be the problem or ideas for how I could investigate further? Is it as simple as an unavoidable synch time when documents are updated? I need all of the data, so while I could restructure it, I can't get rid of any of it.


text:
Q: PHP Eval alternative to include a file I am currently running a queue system with beanstalk + supervisor + PHP.
I would like my workers to automatically die when a new version is available (basically code update).
My current code is as follow
class Job1Controller extends Controller
{
public $currentVersion = 5;

public function actionIndex()
{
    while (true) {
        // check if a new version of the worker is available
        $file = '/config/params.php';
        $paramsContent = file_get_contents($file);
        $params = eval('?>' . file_get_contents($file));
        if ($params['Job1Version'] != $this->currentVersion) {
            echo "not the same version, exit worker \n";
            sleep(2);
            exit();
        } else {
            echo "same version, continue processing \n";
        }
    }
}
}

When I will update the code, the params file will change with a new version number which will force the worker to terminate. I cannot use include as the file will be loaded in memory in the while loop. Knowing that the file params.php isn't critical in terms of security I wanted to know if there was another way of doing so?
Edit: the params.php looks as follow:
<?php
return [
'Job1Version' => 5
];

A: $params = require($file);

Since your file has a return statement, the returned value will be passed along.

A: After few tests I finally managed to find a solution which doesn't require versionning anymore.
$reflectionClass = new \ReflectionClass($this);
$lastUpdatedTimeOnStart = filemtime($reflectionClass->getFileName());

while (true) {
    clearstatcache();
    $reflectionClass = new \ReflectionClass($this);
    $lastUpdatedTime = filemtime($reflectionClass->getFileName());
    if ($lastUpdatedTime != $lastUpdatedTimeOnStart) {
        // An update has been made, exit
    } else {
       // worker hasn't been modified since running
    }
}

Whenever the file will be updated, the worker will automatically exit
Thanks to @Rudie who pointed me into the right direction.


text:
Q: Solutions to Diophantine equation for Ramanujan graph construction I am working with so-called Ramanujan graphs which have the property that a lower bound on their girth can be stated. I am reading about those in paper On the Construction of Turbo Code Interleavers Based on Graphs with Large Girth where such graphs are used in order to construct good Turbo code interleavers.
While going through the construction of those graphs, they speak about having to solve the diophantine equation
$a^2+b^2+c^2+d^2=p \quad(in\quad \mathbb{Z})$
where $p$ is an odd prime and $a,b,c,d\in\mathbb{Z}$ are integers that fullfil

*

*if $p\equiv1\mod{4}$ then $a>0$ odd and $b,c,d$ are even.

*if $p\equiv 3 \mod{4}$ then $a>0$ odd; $b,c$ odd and $d$ even

It is stated that such a diophantine equation has several answers and so by using them you can construct the associated Ramanujan graph. However, as I am not an expert in diophantine equations I do not know if such an equation has to have solutions under such assumptions, and if it has, how many solutions should it have. Consequently, I am interested in knowing when does such diophantine equation have solutions, and how can I know (if possible) how many possible answers to such are possible under the conditions given by $p$.

A: You can find a little bit more about this question in the following famous paper: "Ramanujan Graphs" by Lubotzky, Phillips and Sarnak, Combinatorica,8(3), 261-277, 1988. The discussion is on the second page of the paper.


text:
Q: How can I unset a CUDA event? I have a processing loop on the host, where I record an event in a GPU stream. Then another stream waits for that event (waits for event's state "set" or "true"). Will this function (cudaStreamWaitEvent) unset this event (so, switching it to "unset" or "false")? If not, what CUDA function I can use to unset this event?

A: This sounds very much like an XY question.  You might be better off describing at a higher level what it is you are trying to accomplish, or what problem you are facing or think you are facing.
cudaStreamWaitEvent does not "unset" an event.
When the event is encountered in the stream, then cudaStreamWaitEvent will unblock, and any subsequent calls to cudaStreamWaitEvent on the same event will immediately unblock (assuming no cudaEventRecord has again been issued for that event).  This behavior is easy to prove with a trivial code sample.
The function that "unsets" a cudaEvent is cudaEventRecord().  Any cudaStreamWaitEvent calls issued after that event gets recorded will wait again, until it is encountered again.
You may want to read the runtime API documentation for cudaEventRecord and cudaStreamWaitEvent.  Note the following excerpts:
cudaEventRecord:

If cudaEventRecord() has previously been called on event, then this call will overwrite any existing state in event. Any subsequent calls which examine the status of event will only examine the completion of this most recent call to cudaEventRecord().

cudaStreamWaitEvent:

The stream stream will wait only for the completion of the most recent host call to cudaEventRecord() on event.


text:
Q: Curl Option to Rename Duplicate File Names During Download Is there an option for curl to automatically change the downloaded file's filename if that filename already exists on disk?
Wget does this automatically by appending a .1, .2, .3, .4 etc... to the end of the file name.
Curl Example:
$ ls -al
drwx------. 3 user    user       219 Sep  6 17:12 .
drwxr-xr-x. 3 user    user        21 May 12 18:54 ..
-rw-rw-r--. 1 user    user    147415 Sep  6 16:47 image.jpg

$ curl -O https://website/context/path/image.jpg

$ ls -al
drwx------. 3 user    user       219 Sep  6 17:12 .
drwxr-xr-x. 3 user    user        21 May 12 18:54 ..
-rw-rw-r--. 1 user    user    147415 Sep  6 17:35 image.jpg

The above curl command will overwrite the original image.jpg.  Is there a way in curl to cause the new file to be named image.jpg.1, or something similar, like in wget?
Wget Example:
$ rm image.jpg*
$ wget https://website/context/path/image.jpg

$ ls -al
drwx------. 3 user    user       219 Sep  6 17:12 .
drwxr-xr-x. 3 user    user        21 May 12 18:54 ..
-rw-rw-r--. 1 user    user    147415 Sep  6 17:42 image.jpg

$ wget https://website/context/path/image.jpg
$ wget https://website/context/path/image.jpg
$ wget https://website/context/path/image.jpg

$ ls -al
drwx------. 3 user    user       219 Sep  6 17:12 .
drwxr-xr-x. 3 user    user        21 May 12 18:54 ..
-rw-rw-r--. 1 user    user    147415 Sep  6 17:42 image.jpg
-rw-rw-r--. 1 user    user    147415 Sep  6 17:42 image.jpg.1
-rw-rw-r--. 1 user    user    147415 Sep  6 17:42 image.jpg.2
-rw-rw-r--. 1 user    user    147415 Sep  6 17:42 image.jpg.3

A: Nope. curl has no such option. If you really need it, you can most often work around it by doing the check yourself in a script or other wrapper program.
This feature is mentioned in curl's TODO as something that would be neat to have, so it might be added at a future point in time...


text:
Q: How to handle AG-Grid API actions inside redux or component functions? For a project I'm working on we use the AG-Grid with the data loaded from a server.
Users will have the option to upload files and those files will be displayed on the grid immediately after starting the upload (with an uploading status).
The goal is to refresh the grid after an upload is done, so when our React Redux asyncThunk function succeeds. This because that way we update the grid when an uploading status has changed, so that the user does not have to refresh the browser to see the latest updates of his upload.

What is the problem?
We currently use an AG-Grid api reference in our other components to trigger similar AG-Grid actions (such as a reload).
But, we cannot pass that reference through to our React Redux slice, as you cannot have a non-serializable value in there.

Possible solutions?
Is there a way you can pass a reference of the AG-Grid api throug to a React Redux slice to trigger actions in an asyncThunk (https://redux-toolkit.js.org/api/createAsyncThunk)?
Is there a way to use that reference in a file where we export a function that would trigger an action of that AG-Grid api reference? So this could be called in the asyncThunk.

If there is another way this might be possible, please let me know.

Thanks.

A: When the upload is complete, you can dispatch an action through thunk that adds this information to the redux state (like in the form of state.uploadStatus = 'uploaded'). Access this uploadStatus in the component where you have AG-Grid api reference using useSelector. Then, you can track changes in the uploadStatus in a useEffect hook, and trigger grid refresh acccordingly.
const uploadStatus = useSelector(uploadStatusSelector)

useEffect (()=> {
   refreshGrid()
}, [uploadStatus]);

If you are uploading multiple files and need to refresh the grid every time any of those files is uploaded, then set uploadStatus to be an array and push something like fileId into the array when any of those files is uploaded successfully.


text:
Q: Prove there is a $g:B\rightarrow\mathbb{R}$ s.t. $f(g(b))=b$ for each $b\in B$.
Suppose $f:\mathbb{R}\rightarrow B$ is surjective, where $B$ is
  finite. Prove there is a $g:B\rightarrow\mathbb{R}$ s.t. $f(g(b))=b$
  for each $b\in B$.

I'm given a hint to use induction on the cardinality of $B$. I'm not exactly sure how to go about the inductive step.
The texts give the inductive hypothesis to be: for any onto function $f:C\rightarrow D$, where $|D|=n$ and $C\subset\mathbb{R}$, there is a suitable $g:D\rightarrow C$. However, I don't see why they suppose $C\subset\mathbb{R}$, and not just take $C$ to be $\mathbb{R}$.

A: Your texts seem really weird. All those requirements are not necessary.

Let $f : A \to B$ be surjective, where $A$ is any set and $B$ is countable. Then there exists $g : B \to A$ such that $f(g(b)) = b$ for each $b \in B$.

Proof: For each $b \in B$, choose $g(b)$ to be a preimage of $b$ under $f$, i.e. choose $g(b) \in \{x : f(x) = b\}$, where $\{x : f(x) = b\}$ is always nonempty by surjectivity of $f$. Now $g$ satisfies the requirements.
By the way, if we use the axiom of choice, we can do this construction for any sets $B$, not just countable ones.


text:
Q: Segmentation Fault (core dump). Pointers issue I am trying to execute the following piece of code. It passes compilation but fails at runtime with error Segmentation fault (core dumped). I am trying to simulate a cache but am stuck with some pointer inconsistency(probably).  `
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define _GNU_SOURCE

int hit=0,miss=0,evic=0,verbose=0;

typedef struct{
    long int tag;
    int valid;
    int age;
}cLine;

typedef struct{
    cLine *Lines;
}cSet;

typedef struct{
    cSet *Sets;
}cache;

cache my_cache(int s, int E, int b){
    cache cach;
    int i=0,j=0;
    cach.Sets=malloc(sizeof(cSet)*(1<<s));
    for (i = 0; i < (1<<s); i++) {
      cach.Sets[i].Lines = malloc(sizeof(cLine) * (1<<E));
      for (j=0;j<(1<<E);j++){
        cach.Sets[i].Lines[j].tag=0;
        cach.Sets[i].Lines[j].valid=0;
        cach.Sets[i].Lines[j].age=0;
      }
    }

    return cach;
}

void printSummary(int hits, int misses, int evictions)
{
    printf("hits:%d ,misses:%d ,evictions:%d",hits,misses,evictions);
}

void increment_age(cSet *set, int E){
    printf("\n\ninside increment_age");
    int j=0;
    for (j=0;j<(1<<E);j++){
        set->Lines[j].age++;
    }

}

cLine* find_adr(cache *MyCache,long int mem_tag,int set,int E){
    printf("\n\ninside find_adr");
    increment_age(&MyCache->Sets[set], E);
    int j=0;
    for (j=0;j<(1<<E);j++){
        if(MyCache->Sets[set].Lines[j].tag==mem_tag && MyCache->Sets[set].Lines[j].valid==1){
            hit++;
            if(verbose==1){
                printf("hit ");
            }
            return &MyCache->Sets[set].Lines[j];
        }
    }
    if(verbose==1){
                printf("miss ");
            }
    miss++;
    return NULL;
}

cLine* find_empty(cache *MyCache,int set, int E){
    printf("\n\ninside find_empty");
    int j=0;
    for (j=0;j<(1<<E);j++){
        if(MyCache->Sets[set].Lines[j].valid==0){
            return &MyCache->Sets[set].Lines[j];
        }
    }
    return NULL;
}

cLine* find_evicable(cache *MyCache,int set,int E){
    cLine *ptrLine=&MyCache->Sets[set].Lines[0];
    evic++;
    if(verbose==1){
                printf("eviction ");
            }
    int j=0;
    for (j=0;j<(1<<E);j++){
        if(MyCache->Sets[set].Lines[j].age>ptrLine->age){
            ptrLine=&(MyCache->Sets[set].Lines[j]);
        }
    }
    return ptrLine;
}

void operate(cache *MyCache,long int mem_tag,int set,int E){
    cLine *opLine;
    opLine=find_adr(MyCache,mem_tag,set,E);
    if (opLine==NULL){
        opLine=find_empty(MyCache,set, E);
        if(opLine==NULL){
            opLine=find_evicable(MyCache,set,E);
        }
    }
    opLine->age=0;
    opLine->tag=mem_tag;

}
int main(int argc, char *argv[])
{
    int c;
    int hflg=0, vflg=0, sflg=0, Eflg=0, bflg=0;
    FILE *trc=NULL;
    char *tflg=NULL;
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    long int tag_size;//=(32-sflg-bflg);
    cache newcache=my_cache(sflg,Eflg,bflg);

    while ((c=getopt(argc, argv, "hvs:E:b:t:"))!=-1)
    {
        switch(c)
        {
            case 'h':
                hflg=1;
                printf("argument h was specified\n");
                break;
            case 'v':
                vflg=1;verbose=1;
                printf("argument v was specified\n");
                break;
            case 's':
                if(optarg == NULL )
                {
                    printf("mandatory argument %c is not specified\n",optopt);
                    break;
                }
                else
                {
                    sflg=atoi(optarg);
                    printf("the value of s is %d\n",sflg);
                    break;
                }
            case 'E':
                if(optarg == NULL )
                {
                    printf("mandatory argument %c is not specified\n",optopt);
                    break;
                }
                else
                {
                    Eflg=atoi(optarg);
                    printf("the value of E is %d\n",Eflg);
                    break;
                }
            case 'b':
                if(optarg == NULL )
                {
                    printf("mandatory argument %c is not specified\n",optopt);
                    break;
                }
                else
                {
                    bflg=atoi(optarg);
                    printf("the value of b is %d\n",bflg);
                    break;
                }
            case 't':
                if(optarg == NULL )
                {
                    printf("mandatory argument %c is not specified\n",optopt);
                    break;
                }
                else
                {
                    tflg=optarg;
                    printf("the value of t is %s\n",tflg);
                    char * str3 = (char *) malloc(1 + strlen("./")+ strlen(optarg) );
                    strcpy(str3, "./");
                    strcat(str3, optarg);
                    trc=fopen(str3,"r");
                    //printf("%s", str3);
                    //free(str3);
                    break;
                }
        }
    }
    tag_size=(32-sflg-bflg);

if (trc == NULL){
    printf("invalid input file");
    }
else {
    char cmd;
    long int adr;
    int size;
    long int intag,inset;
    while (fscanf(trc, " %c %lx,%d", &cmd, &adr, &size) == 3) {

        switch(cmd) {
            case 'I':
                //printf("%c, %lx\n",cmd,adr);
                //long int intag=adr>>(sflg+bflg);
                //int inset=(adr<<tag_size)>>(tag_size+bflg);
                //printf("%lx, %lx\n",intag,inset);
                break;
            case 'L':
                printf("\n%c, %lx ",cmd,adr);
                intag=adr>>(sflg+bflg);
                inset=(adr<<tag_size)>>(tag_size+bflg);
                operate(&newcache,intag,inset,Eflg);
                //printf("tag:%lx, Set:%lx\n",intag,inset);
                //par = run_sim(sim_cache, par, address);
                break;
            case 'S':
                printf("\n%c, %lx ",cmd,adr);
                intag=adr>>(sflg+bflg);
                inset=(adr<<tag_size)>>(tag_size+bflg);
                operate(&newcache,intag,inset,Eflg);
                //printf("tag:%lx, Set:%lx\n",intag,inset);
                //par = run_sim(sim_cache, par, address);
                break;
            case 'M':
                printf("\n%c, %lx ",cmd,adr);
                intag=adr>>(sflg+bflg);
                inset=(adr<<tag_size)>>(tag_size+bflg);
                operate(&newcache,intag,inset,Eflg);
                operate(&newcache,intag,inset,Eflg);
                //printf("tag:%lx, Set:%lx\n",intag,inset);
                //par = run_sim(sim_cache, par, address);
                    //par = run_sim(sim_cache, par, address);
                break;
            default:
                break;
        }
    }
}

       fclose(trc);
       printSummary(0, 0, 1);
    //printf("\n%d",1<<4);
    return 0;
}

`
Can someone please help...


text:
Q: Storing & retrieving complex data to MySQL BLOB to retrieve data in same state prior to encode & DB insertion using PHP I am building a function that is inserting complex data into a MySQL table to be used as a queue for a CSV file creation. Without going into explicit details, what I want is simply to convert an array into serialized format using json_encode, insert it to a MySQL table with a prepared statement, and then retrieve that data, json_decode, and have the original data in the exact same form it was prior to insertion.
The code as it stands looks something like this:
// Array data previously created

foreach ( $array as $key => $element ) {

  $array[$key] = htmlspecialchars($element,ENT_QUOTES);

}

$this->db->query("UPDATE `table` SET `blob_field` = '".$this->db->escape($array)."' WHERE `id` = '".(int)$id."'");

Then I retrieve the data using:
$decoded_array = $this->db->query("SELECT `blob_field` FROM `table` WHERE `id` = '".(int)$id."'")->row['blob_field'];

$decoded_array = json_decode($decoded_array);
$decoded_array = array_map('htmlspecialchars_decode',$decoded_array);

// Add to CSV using fputcsv standard process

The resulting CSV is about 99.9% perfect. But when opened in Excel about 0.1% of the rows have columns that are jumping where they should not. Furthermore, every instance of \r\n appears to be getting replaced with the Windows newline character.
My question is... what am I doing wrong? Why are the newline characters being replaced with the Windows equivalent, and why does the CSV look messed up when opened in Excel?


text:
Q: How to access argument properties when writing custom NHibernate HQL generator I have the following custom type with a method on it to determine if one span of time overlaps another
public struct DateTimeSpan
{
    public DateTime? Start { get; set; }
    public DateTime? End { get; set; }

    public bool Overlaps(DateTimeSpan overlap)
    {
        //....
    }
}

I am trying to write a custom HQL generator so that when I use this method within my data access LINQ queries it will generate to appropriate SQL when querying the database.
This is the start of my BaseHqlGeneratorForMethod that attempts to compare the End property of one DateTimeSpan with the other
public class DateSpanOverlapsDateTimeSpanHqlGenerator : BaseHqlGeneratorForMethod
{
    public DateSpanOverlapsDateTimeSpanHqlGenerator()
    {
        SupportedMethods = new[]
            {
                ReflectionHelper.GetMethodDefinition<DateTimeSpan>(x => x.Overlaps(new DateTimeSpan()))
            };
    }

    public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder builder, IHqlExpressionVisitor visitor)
    {
        var endTargetProperty = ReflectionHelper.GetProperty<DateTimeSpan, DateTime?>(x => x.End);
        Expression endTargetExpression = Expression.MakeMemberAccess(targetObject, endTargetProperty);

        var endArgumentProperty = ReflectionHelper.GetProperty<DateTimeSpan, DateTime?>(x => x.End);
        Expression endArgumentExpression = Expression.MakeMemberAccess(arguments[0], endArgumentProperty);

       return builder.GreaterThanOrEqual(visitor.Visit(endTargetExpression).AsExpression(), visitor.Visit(endArgumentExpression).AsExpression());
    }
}

I have proven that the End property in the targetObject is being evaluated fine but no matter what I do I cannot get it to evaluate the End property in arguments[0].  The above code is just one example of what I have tried (and seems the most obvious given it works for the targetObject) with most things I try ending up with the exception Antlr.Runtime.NoViableAltException
One obvious different between targetObject and arguments[0] is that targetObject is of type PropertyExpression and arguments[0] is of type ConstantExpression.  I assume this means there needs to be different ways to access them but I cannot work out what it is!

A: treeBuilder.Constant(arg.SubProperty); will cache your object so you will end up to have problem when you will run your query.
you should add an overload into your DateTimeSpan
public bool Overlaps(DateTime? start, DateTime? end)

match the signature into your DateSpanOverlapsDateTimeSpanHqlGenerator
SupportedMethods = new[]
{
ReflectionHelper.GetMethodDefinition<DateTimeSpan>(span => span.Overlaps(default(DateTime?), default(DateTime?)))
};

and get the values in this way:
public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder builder, IHqlExpressionVisitor visitor)
{
    var startProperty = ReflectionHelper.GetProperty<DateTimeSpan, DateTime?>(x => x.Start);
    var endProperty = ReflectionHelper.GetProperty<DateTimeSpan, DateTime?>(x => x.End);

    MemberExpression targetStartExpression = Expression.MakeMemberAccess(targetObject, startProperty);
    MemberExpression targetEndExpression = Expression.MakeMemberAccess(targetObject, endProperty);

    HqlExpression startDateExpression = visitor.Visit(arguments[0]).AsExpression();
    HqlExpression endDateExpression = visitor.Visit(arguments[1]).AsExpression();
    ....
}

after that business as usual:
builder.LessThanOrEqual(visitor.Visit(targetStartExpression).AsExpression(), endDateExpression)

A: I don't know if you ever resolved this or are still interested in an answer, however I stumbled across this question myself while looking for a solution to this exact problem, so thought I would add my solution for others.
While debugging I noticed that the target object parameter is passed in as an expression of type PropertyExpression, whereas my argument was passed in as a type of ConstantExpression, so while it's perfectly valid to add to PropertyExpression using Expression.Property, that doesn't work with a constant value.
Instead I extract the value of the constant and access the values of sub-properties directly, creating new constant expressions which I can then use to build the query expression.
I don't know if this is the best, or most elegant way to do it, but it worked for me. I hope it helps.
 public class MyObject
 {
    public double SubProperty { get; set; }
 }

 private HqlTreeNode GenerateHQL(
    MethodInfo method,
    Expression targetObject,
    ReadOnlyCollection<Expression> arguments,
    HqlTreeBuilder treeBuilder,
    IHqlExpressionVisitor visitor)
{
    MyObject arg = (MyObject)((ConstantExpression)arguments[0]).Value;
    HqlConstant argExpression = treeBuilder.Constant(arg.SubProperty);

    ...
    ...
}


text:
Q: SWI prolog: answers written in red and/or black I'm very new to prolog and I'm trying to (self) learn from the basics using SWI-Prolog (windows version). This question of mine is certainly a newbie problem, plese forgive my naivety.
I am working with the main interactive window, trying to follow a tutorial (this one) but there's one thing I do not understand about SWI-prolog answers.
The way I understand it, SWI-Prolog responds by writing with "true" or "false" to my query and I'm able to follow the tutorial and get the results espected.
What confuses me is that SWI print his answers using two colors, red and black. Sometimes the answers are written in red, sometimes are written in black, sometimes I get two opposite responses [ like: "true ; false"]
and one is black and the other one red!
I have searched into SWI-prolog docs but but have not been able to find the meaning of the two different colors in the responses.
Can someone point me to the relevant SWI documentation or explain why this happen?
EDIT:
To sum up:
What is the difference between a "true" answer written in red and one writtend in black ?
And the difference between a "false" answer written in red and one written in black?

A: *

*Red indicate New;Stand alone(no recursive)

*Black indicate Recursive

*Blue indicate defined in SWI-PROLOG

Hope this helpful.